diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/src/main/java/it/unipd/dei/webqual/converter/Main.java b/src/main/java/it/unipd/dei/webqual/converter/Main.java
index 8bc9f64..4201f29 100644
--- a/src/main/java/it/unipd/dei/webqual/converter/Main.java
+++ b/src/main/java/it/unipd/dei/webqual/converter/Main.java
@@ -1,134 +1,134 @@
package it.unipd.dei.webqual.converter;
import it.unimi.dsi.big.webgraph.*;
import it.unimi.dsi.fastutil.Function;
import it.unimi.dsi.logging.ProgressLogger;
import it.unipd.dei.webqual.converter.merge.ArrayComparator;
import it.unipd.dei.webqual.converter.merge.ArrayLongComparator;
import it.unipd.dei.webqual.converter.merge.GraphMerger;
import it.unipd.dei.webqual.converter.sort.GraphSorter;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;
import java.io.*;
import java.util.Comparator;
public class Main {
public static void main(String[] args) throws IOException {
Options opts = new Options();
CmdLineParser parser = new CmdLineParser(opts);
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
System.err.println(e.getMessage());
parser.printUsage(System.err);
System.exit(1);
}
Comparator<byte[]> comparator = new ArrayLongComparator();
ProgressLogger pl = new ProgressLogger();
pl.displayFreeMemory = true;
File[] sortedChunks;
- if(opts.skipSplitting){
+ if(!opts.skipSplitting){
pl.logger().info("Building hash function");
Function<byte[], Long> mapFunc =
FunctionFactory.buildDeterministicMap(opts.inputGraph, opts.idLen, pl);
// String mphSerializedName = opts.inputGraph + "-mph";
// pl.logger().info("Storing hash function to {}", mphSerializedName);
// serialize(mphSerializedName, mapFunc);
if(opts.intermediateChecks)
Checks.checkMap(opts.inputGraph, opts.idLen, mapFunc, pl);
pl.logger().info("Loading graph from {}", opts.inputGraph);
ImmutableGraph originalGraph =
ImmutableAdjacencyGraph.loadOffline(opts.inputGraph.getCanonicalPath(), opts.idLen, mapFunc, pl);
pl.logger().info("Sorting graph");
File[] chunks = GraphSplitter.split(originalGraph, opts.outputDir, opts.chunkSize, pl);
sortedChunks = GraphMerger.sortFiles(chunks, 8, comparator);
} else {
sortedChunks = opts.outputDir.listFiles();
}
pl.logger().info("Merging files");
File mergedFile;
if(sortedChunks.length < 2) {
mergedFile = sortedChunks[0];
} else {
mergedFile = GraphMerger.mergeFiles(sortedChunks, opts.outputFile, sortedChunks.length, 8, comparator, 0);
}
if(opts.intermediateChecks) {
Checks.checkSorted(mergedFile, 8, comparator, pl);
Checks.checkDuplicates(mergedFile, 8, pl);
}
pl.start("==== Loading graph from " + mergedFile);
Function<byte[], Long> map =
FunctionFactory.buildIdentity(mergedFile, pl);
ImmutableGraph iag =
ImmutableAdjacencyGraph.loadOffline(mergedFile.getCanonicalPath(), 8, map, pl);
pl.stop("Loaded graph with " + iag.numNodes() + " nodes");
if (opts.intermediateChecks)
Checks.checkIncreasing(iag, pl);
String efOut = opts.outputFile + "-ef";
ImmutableGraph efGraph = Conversions.toBVGraph(iag, efOut, pl);
if(opts.intermediateChecks)
Checks.checkPositiveIDs(iag, pl);
if(opts.intermediateChecks || opts.finalCheck)
Checks.checkEquality(iag, efGraph, pl);
pl.logger().info("All done");
// Metrics.report();
Metrics.reset();
}
private static void serialize(String name, Object o) throws IOException {
ObjectOutputStream oos =
new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(name)));
oos.writeObject(o);
oos.close();
}
public static class Options {
@Option(name = "-i", metaVar = "FILE", required = true, usage = "the input graph")
public File inputGraph;
@Option(name = "--id-len", metaVar = "N", usage = "the input ID length, defaults to 16")
public int idLen = 16;
@Option(name = "-d", metaVar = "OUTPUT_DIR", required = true, usage = "Output directory")
public File outputDir;
@Option(name = "-o", metaVar = "FILE", required = true, usage = "Output file")
public File outputFile;
@Option(name = "-c", metaVar = "CHUNK_SIZE", usage = "Chunk size for intermediate sorted files. Defaults to 300'000")
public int chunkSize = 300_000;
@Option(name = "--checks", usage = "Perform intermediate checks")
public boolean intermediateChecks = false;
@Option(name = "--final-check", usage = "Perform final equality checks")
public boolean finalCheck = false;
@Option(name = "--skip-splitting", usage = "Skips the splitting phase")
public boolean skipSplitting = false;
}
}
| true | true | public static void main(String[] args) throws IOException {
Options opts = new Options();
CmdLineParser parser = new CmdLineParser(opts);
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
System.err.println(e.getMessage());
parser.printUsage(System.err);
System.exit(1);
}
Comparator<byte[]> comparator = new ArrayLongComparator();
ProgressLogger pl = new ProgressLogger();
pl.displayFreeMemory = true;
File[] sortedChunks;
if(opts.skipSplitting){
pl.logger().info("Building hash function");
Function<byte[], Long> mapFunc =
FunctionFactory.buildDeterministicMap(opts.inputGraph, opts.idLen, pl);
// String mphSerializedName = opts.inputGraph + "-mph";
// pl.logger().info("Storing hash function to {}", mphSerializedName);
// serialize(mphSerializedName, mapFunc);
if(opts.intermediateChecks)
Checks.checkMap(opts.inputGraph, opts.idLen, mapFunc, pl);
pl.logger().info("Loading graph from {}", opts.inputGraph);
ImmutableGraph originalGraph =
ImmutableAdjacencyGraph.loadOffline(opts.inputGraph.getCanonicalPath(), opts.idLen, mapFunc, pl);
pl.logger().info("Sorting graph");
File[] chunks = GraphSplitter.split(originalGraph, opts.outputDir, opts.chunkSize, pl);
sortedChunks = GraphMerger.sortFiles(chunks, 8, comparator);
} else {
sortedChunks = opts.outputDir.listFiles();
}
pl.logger().info("Merging files");
File mergedFile;
if(sortedChunks.length < 2) {
mergedFile = sortedChunks[0];
} else {
mergedFile = GraphMerger.mergeFiles(sortedChunks, opts.outputFile, sortedChunks.length, 8, comparator, 0);
}
if(opts.intermediateChecks) {
Checks.checkSorted(mergedFile, 8, comparator, pl);
Checks.checkDuplicates(mergedFile, 8, pl);
}
pl.start("==== Loading graph from " + mergedFile);
Function<byte[], Long> map =
FunctionFactory.buildIdentity(mergedFile, pl);
ImmutableGraph iag =
ImmutableAdjacencyGraph.loadOffline(mergedFile.getCanonicalPath(), 8, map, pl);
pl.stop("Loaded graph with " + iag.numNodes() + " nodes");
if (opts.intermediateChecks)
Checks.checkIncreasing(iag, pl);
String efOut = opts.outputFile + "-ef";
ImmutableGraph efGraph = Conversions.toBVGraph(iag, efOut, pl);
if(opts.intermediateChecks)
Checks.checkPositiveIDs(iag, pl);
if(opts.intermediateChecks || opts.finalCheck)
Checks.checkEquality(iag, efGraph, pl);
pl.logger().info("All done");
// Metrics.report();
Metrics.reset();
}
| public static void main(String[] args) throws IOException {
Options opts = new Options();
CmdLineParser parser = new CmdLineParser(opts);
try {
parser.parseArgument(args);
} catch (CmdLineException e) {
System.err.println(e.getMessage());
parser.printUsage(System.err);
System.exit(1);
}
Comparator<byte[]> comparator = new ArrayLongComparator();
ProgressLogger pl = new ProgressLogger();
pl.displayFreeMemory = true;
File[] sortedChunks;
if(!opts.skipSplitting){
pl.logger().info("Building hash function");
Function<byte[], Long> mapFunc =
FunctionFactory.buildDeterministicMap(opts.inputGraph, opts.idLen, pl);
// String mphSerializedName = opts.inputGraph + "-mph";
// pl.logger().info("Storing hash function to {}", mphSerializedName);
// serialize(mphSerializedName, mapFunc);
if(opts.intermediateChecks)
Checks.checkMap(opts.inputGraph, opts.idLen, mapFunc, pl);
pl.logger().info("Loading graph from {}", opts.inputGraph);
ImmutableGraph originalGraph =
ImmutableAdjacencyGraph.loadOffline(opts.inputGraph.getCanonicalPath(), opts.idLen, mapFunc, pl);
pl.logger().info("Sorting graph");
File[] chunks = GraphSplitter.split(originalGraph, opts.outputDir, opts.chunkSize, pl);
sortedChunks = GraphMerger.sortFiles(chunks, 8, comparator);
} else {
sortedChunks = opts.outputDir.listFiles();
}
pl.logger().info("Merging files");
File mergedFile;
if(sortedChunks.length < 2) {
mergedFile = sortedChunks[0];
} else {
mergedFile = GraphMerger.mergeFiles(sortedChunks, opts.outputFile, sortedChunks.length, 8, comparator, 0);
}
if(opts.intermediateChecks) {
Checks.checkSorted(mergedFile, 8, comparator, pl);
Checks.checkDuplicates(mergedFile, 8, pl);
}
pl.start("==== Loading graph from " + mergedFile);
Function<byte[], Long> map =
FunctionFactory.buildIdentity(mergedFile, pl);
ImmutableGraph iag =
ImmutableAdjacencyGraph.loadOffline(mergedFile.getCanonicalPath(), 8, map, pl);
pl.stop("Loaded graph with " + iag.numNodes() + " nodes");
if (opts.intermediateChecks)
Checks.checkIncreasing(iag, pl);
String efOut = opts.outputFile + "-ef";
ImmutableGraph efGraph = Conversions.toBVGraph(iag, efOut, pl);
if(opts.intermediateChecks)
Checks.checkPositiveIDs(iag, pl);
if(opts.intermediateChecks || opts.finalCheck)
Checks.checkEquality(iag, efGraph, pl);
pl.logger().info("All done");
// Metrics.report();
Metrics.reset();
}
|
diff --git a/src/fr/iutvalence/java/mp/RollingBall/RollingBallGame.java b/src/fr/iutvalence/java/mp/RollingBall/RollingBallGame.java
index e076948..5dd853b 100644
--- a/src/fr/iutvalence/java/mp/RollingBall/RollingBallGame.java
+++ b/src/fr/iutvalence/java/mp/RollingBall/RollingBallGame.java
@@ -1,83 +1,83 @@
package fr.iutvalence.java.mp.RollingBall;
/**
*
* see readme.md Means and rules of the game.
*
* @author andrejul
*
*/
public class RollingBallGame
{
/**
* the name of the player
*/
private String nameOfThePlayer;
/**
* the map used by the player
*/
private Map mapUsedByThePlayer;
/**
* the ball used by the player
*/
private MovingBall ballUsedByThePlayer;
/**
* the score of the player
*/
private Score scoreOfThePlayer;
/**
* rollingball game created with three parameters : the name of the player, the
* map where the player wants to play and the ball the player want to use
*
* @param nameOfThePlayerPlaying
* the name of the player
* @param mapChoosedByThePlayer
* the map used by the player
* @param ballChoosedByThePlayer
* the ball choose by the player
*/
public RollingBallGame(String nameOfThePlayerPlaying, Map mapChoosedByThePlayer, MovingBall ballChoosedByThePlayer)
{
this.nameOfThePlayer = nameOfThePlayerPlaying;
this.mapUsedByThePlayer = mapChoosedByThePlayer;
this.ballUsedByThePlayer = ballChoosedByThePlayer;
}
/**
* play the game
*/
public void play()
{
boolean youCanPlay = true;
Point gravityPower = new Point(0, -10);
- int t;
+ int time;
- // TODO (fix) rename local variable (more explicit)
- int i;
+ // TODO (FIXED) rename local variable (more explicit)
+ int indiceOfTheSegmentsField;
- t = 0;
+ time = 0;
while (youCanPlay)
{
- i = 0;
- while (!(this.mapUsedByThePlayer.getSegmentsOfTheField()[i].intersect(this.ballUsedByThePlayer))
- && i < this.mapUsedByThePlayer.getSegmentsOfTheField().length)
+ indiceOfTheSegmentsField = 0;
+ while (!(this.mapUsedByThePlayer.getSegmentsOfTheField()[indiceOfTheSegmentsField].intersect(this.ballUsedByThePlayer))
+ && indiceOfTheSegmentsField < this.mapUsedByThePlayer.getSegmentsOfTheField().length)
{
- i++;
+ indiceOfTheSegmentsField++;
}
- if (i == this.mapUsedByThePlayer.getSegmentsOfTheField().length)
+ if (indiceOfTheSegmentsField == this.mapUsedByThePlayer.getSegmentsOfTheField().length)
{
this.ballUsedByThePlayer.setSpeed(gravityPower);
}
else
{
}
}
}
}
| false | true | public void play()
{
boolean youCanPlay = true;
Point gravityPower = new Point(0, -10);
int t;
// TODO (fix) rename local variable (more explicit)
int i;
t = 0;
while (youCanPlay)
{
i = 0;
while (!(this.mapUsedByThePlayer.getSegmentsOfTheField()[i].intersect(this.ballUsedByThePlayer))
&& i < this.mapUsedByThePlayer.getSegmentsOfTheField().length)
{
i++;
}
if (i == this.mapUsedByThePlayer.getSegmentsOfTheField().length)
{
this.ballUsedByThePlayer.setSpeed(gravityPower);
}
else
{
}
}
}
| public void play()
{
boolean youCanPlay = true;
Point gravityPower = new Point(0, -10);
int time;
// TODO (FIXED) rename local variable (more explicit)
int indiceOfTheSegmentsField;
time = 0;
while (youCanPlay)
{
indiceOfTheSegmentsField = 0;
while (!(this.mapUsedByThePlayer.getSegmentsOfTheField()[indiceOfTheSegmentsField].intersect(this.ballUsedByThePlayer))
&& indiceOfTheSegmentsField < this.mapUsedByThePlayer.getSegmentsOfTheField().length)
{
indiceOfTheSegmentsField++;
}
if (indiceOfTheSegmentsField == this.mapUsedByThePlayer.getSegmentsOfTheField().length)
{
this.ballUsedByThePlayer.setSpeed(gravityPower);
}
else
{
}
}
}
|
diff --git a/core/src/org/checkthread/parser/bcel/ProcessInstruction.java b/core/src/org/checkthread/parser/bcel/ProcessInstruction.java
index bcd0eb1..1e56f0b 100644
--- a/core/src/org/checkthread/parser/bcel/ProcessInstruction.java
+++ b/core/src/org/checkthread/parser/bcel/ProcessInstruction.java
@@ -1,1344 +1,1344 @@
/*
Copyright (c) 2008 Joe Conti
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
package org.checkthread.parser.bcel;
import java.util.*;
import org.apache.bcel.classfile.*;
import org.apache.bcel.Constants;
import org.checkthread.parser.*;
import org.apache.bcel.verifier.structurals.*;
import org.apache.bcel.generic.*;
import org.apache.bcel.classfile.Utility;
import org.checkthread.config.*;
/**
* Main class for handling Java byte
* code instructions. This class contains
* a big switch statement for delegating
* the JVM spec byte codes.
*/
public class ProcessInstruction {
private static boolean wide = false;
static void logInfo(String msg) {
Log.logByteInfo(msg);
}
static void logLocking(String msg) {
Log.logByteInfo(msg);
}
static void processInstruction(
short opcode,
HashMap<Integer,Boolean> visitedByteOffsets,
Queue<BranchState> branchQueue,
BranchState currBranch,
HashMap<Integer,Type> runtimeVariableTable,
JavaClass jClass,
ArrayList<IClassFileParseHandler> handlerList,
HashMap<String,java.lang.reflect.AccessibleObject> hashMapSynthetic,
Method parentMethod,
java.lang.reflect.AccessibleObject parentMethodR,
ByteReader bytes,
IMethodInfo parentMethodInfo)
throws Exception {
ConstantPool constant_pool = jClass.getConstantPool();
Code code = parentMethod.getCode();
boolean parentIsSynthetic = parentMethod.isSynthetic();
LineNumberTable lineTable = code.getLineNumberTable();
OperandStack stack = currBranch.getStack();
LockStack lockStack = currBranch.getLockInfo();
//ByteReader bytes = new ByteReader(code.getCode());
//bytes.mark(bytes.available());
//bytes.reset();
//bytes.skipBytes(currBranch.getIndex());
int currOffset = bytes.getIndex();
//ToDo: get this from BCEL
boolean isStaticBlock = parentMethod.getName().equals(ByteCodeConstants.STATICBLOCK_IDENTIFIER);
//logInfo("opcode: " + opcode + " ALOAD_1: " + Constants.ALOAD_1);
String name, signature;
String className = null;
int default_offset = 0, low, high;
int index, class_index, vindex, constant;
int[] jump_table;
int no_pad_bytes = 0, offset;
Type t;
BranchState branchState;
// varTable may be null in some situations
LocalVariableTable varTable = code.getLocalVariableTable();
int line_number_ind = bytes.getIndex();
int invokedLineNumber;
if (lineTable != null) {
invokedLineNumber = lineTable.getSourceLine(line_number_ind);
} else {
invokedLineNumber = org.checkthread.main.Constants.NO_LINE_NUMBER;
}
Log.logByteInfo("Byte Offset: " + bytes.getIndex() + " Stack size: " + stack.size());
/*
* Special case: Skip (0-3) padding bytes, i.e., the following bytes are
* 4-byte-aligned
*/
if ((opcode == Constants.TABLESWITCH)
|| (opcode == Constants.LOOKUPSWITCH)) {
int remainder = bytes.getIndex() % 4;
no_pad_bytes = (remainder == 0) ? 0 : 4 - remainder;
for (int i = 0; i < no_pad_bytes; i++) {
bytes.readByte();
}
// Both cases have a field default_offset in common
default_offset = bytes.readInt();
}
switch (opcode) {
// TABLESWITCH - Switch within given range of values, i.e., low..high
case Constants.TABLESWITCH:
logInfo("TABLESWITCH");
stack.pop();
low = bytes.readInt();
high = bytes.readInt();
offset = bytes.getIndex() - 12 - no_pad_bytes - 1;
default_offset += offset;
// Print switch indices in first row (and default)
jump_table = new int[high - low + 1];
for (int i = 0; i < jump_table.length; i++) {
jump_table[i] = offset + bytes.readInt();
}
break;
// AALOAD - Load reference from array
// Stack: ..., arrayref, index -> value
case Constants.AALOAD:
logInfo("AALOAD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.NULL);
break;
// AASTORE - Store into reference array
// Stack: ..., arrayref, index, value -> ...
case Constants.AASTORE:
logInfo("AASTORE, stack size: " + stack.size());
stack.pop(3);
break;
// ACONST_NULL - Push null reference
// Stack: ... -> ..., null
case Constants.ACONST_NULL:
logInfo("ACONST_NULL, stack size: " + stack.size());
stack.push(ObjectType.NULL);
break;
// ALOAD - Load reference from local variable
// Stack: ... -> ..., objectref
case Constants.ALOAD_0:
wide = ProcessInstruction_Util.processALOAD(0,stack, wide, bytes, varTable, runtimeVariableTable);
break;
case Constants.ALOAD_1:
wide = ProcessInstruction_Util.processALOAD(1,stack, wide, bytes, varTable, runtimeVariableTable);
break;
case Constants.ALOAD_2:
wide = ProcessInstruction_Util.processALOAD(2,stack, wide, bytes, varTable, runtimeVariableTable);
break;
case Constants.ALOAD_3:
wide = ProcessInstruction_Util.processALOAD(3,stack, wide, bytes, varTable, runtimeVariableTable);
break;
case Constants.ALOAD:
wide = ProcessInstruction_Util.processALOADn(stack, wide, bytes, varTable, runtimeVariableTable);
break;
// ANEWARRAY - Create new array of references
// Stack: ..., count -> ..., arrayref
case Constants.ANEWARRAY: {
logInfo("ANEWARRAY, stack size: " + stack.size());
bytes.readShort();
stack.pop();
t = new ArrayType(ObjectType.NULL,1);
stack.push(t);
break;
}
// ARETURN - Return reference from method
// Stack: ..., objectref -> <empty>
case Constants.ARETURN:
logInfo("ARETURN, stack size: " + stack.size());
stack.pop(stack.size());
break;
// ARRAYLENGTH - Get length of array
// Stack: ..., arrayref -> ..., length
case Constants.ARRAYLENGTH:
logInfo("ARRAYLENGTH, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.INT);
break;
// ASTORE - Store reference into local variable
// Stack ..., objectref -> ...
case Constants.ASTORE_0:
wide = ProcessInstruction_Util.processASTORE(0,stack, wide, bytes, runtimeVariableTable);
break;
case Constants.ASTORE_1:
wide = ProcessInstruction_Util.processASTORE(1,stack, wide, bytes, runtimeVariableTable);
break;
case Constants.ASTORE_2:
wide = ProcessInstruction_Util.processASTORE(2,stack, wide, bytes, runtimeVariableTable);
break;
case Constants.ASTORE_3:
wide = ProcessInstruction_Util.processASTORE(3,stack, wide, bytes, runtimeVariableTable);
break;
case Constants.ASTORE:
wide = ProcessInstruction_Util.processASTOREn(stack, wide, bytes, runtimeVariableTable);
break;
// ATHROW - Throw exception
// Stack: ..., objectref -> objectref
case Constants.ATHROW:
logInfo("ATHROW, stack size: " + stack.size());
stack.pop(stack.size());
//stack.push(ObjectType.NULL);
break;
// BALOAD - Load byte or boolean from array
// Stack: ..., arrayref, index -> ..., value
case Constants.BALOAD:
logInfo("BALOAD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
// BASTORE - Store into byte or boolean array
// Stack: ..., arrayref, index, value -> ...
case Constants.BASTORE:
logInfo("BASTORE, stack size: " + stack.size());
stack.pop(3);
break;
// BIPUSH - Push byte on stack
// Stack: ... -> ..., value
case Constants.BIPUSH:
logInfo("BIPUSH, stack size: " + stack.size());
bytes.readByte();
stack.push(ObjectType.INT);
break;
// CALOAD - Load char from array
// Stack: ..., arrayref, index -> ..., value
case Constants.CALOAD:
logInfo("CALOAD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
// CASTORE - Store into char array
// Stack: ..., arrayref, index, value -> ...
case Constants.CASTORE:
logInfo("CASTORE, stack size: " + stack.size());
stack.pop(3);
break;
// CHECKCAST - Check whether object is of given type
// Stack: ..., objectref -> ..., objectref
case Constants.CHECKCAST:
logInfo("CHECKCAST, stack size: " + stack.size());
index = bytes.readShort();
break;
// D2F - Convert double to float
// Stack: ..., value.word1, value.word2 -> ..., result
case Constants.D2F:
logInfo("D2F, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.FLOAT);
break;
// D2I - Convert double to int
// Stack: ..., value.word1, value.word2 -> ..., result
case Constants.D2I:
logInfo("D2I, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.INT);
break;
// D2L - Convert double to long
// Stack: ..., value.word1, value.word2 -> ..., result.word1, result.word2
case Constants.D2L:
logInfo("D2L, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.LONG);
break;
// DADD - Add doubles
// Stack: ..., value1.word1, value1.word2, value2.word1, value2.word2 ->
// ..., result.word1, result1.word2
case Constants.DADD:
logInfo("DADD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.DOUBLE);
break;
// DALOAD - Load double from array
// Stack: ..., arrayref, index -> ..., result.word1, result.word2
case Constants.DALOAD:
logInfo("DALOAD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.DOUBLE);
break;
// DASTORE - Store into double array
// Stack: ..., arrayref, index, value.word1, value.word2 -> ...
case Constants.DASTORE:
logInfo("DASTORE, stack size: " + stack.size());
stack.pop(3);
break;
// DCMPG - Compare doubles: value1 > value2
// Stack: ..., value1.word1, value1.word2, value2.word1, value2.word2 ->
// ..., result
case Constants.DCMPG:
logInfo("DCMPG, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
case Constants.DCMPL:
logInfo("DCMPL, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
// DCONST - Push 0.0 or 1.0, other values cause an exception
// Stack: ... -> ...,
case Constants.DCONST_0:
logInfo("DCONST_0, stack size: " + stack.size());
stack.push(ObjectType.DOUBLE);
break;
case Constants.DCONST_1:
logInfo("DCONST_1, stack size: " + stack.size());
stack.push(ObjectType.DOUBLE);
break;
// ..., value1, value2 ..., result
case Constants.DDIV:
logInfo("DDIV, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.DOUBLE);
break;
// DLOAD - Load double from local variable
// Stack ... -> ..., result.word1, result.word2
case Constants.DLOAD_0:
wide = ProcessInstruction_Util.processDLOAD(0, stack, wide, bytes, varTable);
break;
case Constants.DLOAD_1:
wide = ProcessInstruction_Util.processDLOAD(1, stack, wide, bytes, varTable);
break;
case Constants.DLOAD_2:
wide = ProcessInstruction_Util.processDLOAD(2, stack, wide, bytes, varTable);
break;
case Constants.DLOAD_3:
wide = ProcessInstruction_Util.processDLOAD(3, stack, wide, bytes, varTable);
break;
case Constants.DLOAD:
wide = ProcessInstruction_Util.processDLOADn(stack, wide, bytes, varTable);
break;
// ..., value1, value2 ..., result
case Constants.DMUL:
logInfo("DMUL, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.DOUBLE);
break;
// ..., value ..., result
case Constants.DNEG:
logInfo("DNEG, stack size: " + stack.size());
stack.pop(1);
stack.push(ObjectType.DOUBLE);
break;
// ..., value1, value2 ..., result
case Constants.DREM:
logInfo("DREM, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.DOUBLE);
break;
// ..., value [empty]
case Constants.DRETURN:
logInfo("DRETURN, stack size: " + stack.size());
stack.pop(stack.size());
break;
// DSTORE - Store double into local variable
// Stack: ..., value.word1, value.word2 -> ...
case Constants.DSTORE_0:
wide = ProcessInstruction_Util.processDSTORE(0, stack, wide, bytes);
break;
case Constants.DSTORE_1:
wide = ProcessInstruction_Util.processDSTORE(1, stack, wide, bytes);
break;
case Constants.DSTORE_2:
wide = ProcessInstruction_Util.processDSTORE(2, stack, wide, bytes);
break;
case Constants.DSTORE_3:
wide = ProcessInstruction_Util.processDSTORE(3, stack, wide, bytes);
break;
case Constants.DSTORE:
wide = ProcessInstruction_Util.processDSTOREn(stack, wide, bytes);
break;
// ..., value1, value2 ..., result
case Constants.DSUB:
logInfo("DSUB, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.DOUBLE);
break;
// DUP - Duplicate top operand stack word
// Stack: ..., word -> ..., word, word
case Constants.DUP: {
logInfo("DUP, stack size: " + stack.size());
if(stack.size()>=stack.maxStack()) {
Log.severe("Stack filled up: " + parentMethodInfo.getFullUniqueMethodName());
}
stack.push(stack.peek());
break;
}
// ..., value2, value1 ..., value1, value2, value1
case Constants.DUP_X1:
logInfo("DUP_X1, stack size: " + stack.size());
stack.push(stack.peek());
break;
// Form 1:
// ..., value3, value2, value1 ..., value1, value3, value2, value1
- // where value1, value2, and value3 are all values of a category 1 computational type (�3.11.1).
+ // where value1, value2, and value3 are all values of a category 1 computational type.
//
// Form 2:
// ..., value2, value1 ..., value1, value2, value1
- // where value1 is a value of a category 1 computational type and value2 is a value of a category 2 computational type (�3.11.1).
+ // where value1 is a value of a category 1 computational type and value2 is a value of a category 2 computational type.
case Constants.DUP_X2:
logInfo("DUP_X2, stack size: " + stack.size());
t = stack.peek();
// category 2
if(t == ObjectType.DOUBLE || t == ObjectType.LONG) {
stack.push(stack.peek());
// category 1
} else {
stack.push(stack.peek());
}
// Form 1:
// ..., value2, value1 ..., value2, value1, value2, value1
- // where both value1 and value2 are values of a category 1 computational type (�3.11.1).
+ // where both value1 and value2 are values of a category 1 computational type.
// Form 2:
// ..., value ..., value, value
- // where value is a value of a category 2 computational type (�3.11.1).
+ // where value is a value of a category 2 computational type
case Constants.DUP2:
logInfo("DUP2, stack size: " + stack.size());
t = stack.peek();
// category 2
if(t == ObjectType.DOUBLE || t == ObjectType.LONG) {
stack.push(stack.peek(2));
stack.push(stack.peek(3));
// category 1
} else {
stack.push(stack.peek());
}
break;
// Form 1:
// ..., value3, value2, value1 ..., value2, value1, value3, value2, value1
- // where value1, value2, and value3 are all values of a category 1 computational type (�3.11.1).
+ // where value1, value2, and value3 are all values of a category 1 computational type.
// Form 2:
// ..., value2, value1 ..., value1, value2, value1
- // where value1 is a value of a category 2 computational type and value2 is a value of a category 1 computational type (�3.11.1).
+ // where value1 is a value of a category 2 computational type and value2 is a value of a category 1 computational type.
case Constants.DUP2_X1:
logInfo("DUP2_X1, stack size: " + stack.size());
t = stack.peek();
// category 2
if(t == ObjectType.DOUBLE || t == ObjectType.LONG) {
stack.push(stack.peek());
// category 1
} else {
stack.push(stack.peek());
stack.push(stack.peek());
}
break;
// DUP_X2 - Duplicate top operand stack word and put three down
// Stack: ..., word3, word2, word1 -> ..., word1, word3, word2, word1
case Constants.DUP2_X2:
logInfo("DUP2_X2, stack size: " + stack.size());
stack.push(stack.peek());
break;
// Float operations
case Constants.F2D:
logInfo("F2D, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.DOUBLE);
break;
case Constants.F2I:
logInfo("F2I, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.INT);
break;
case Constants.F2L:
logInfo("F2L, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.LONG);
break;
case Constants.FADD:
logInfo("FADD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.FLOAT);
break;
case Constants.FALOAD:
logInfo("FALOAD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.FLOAT);
break;
case Constants.FASTORE:
logInfo("FASTORE, stack size: " + stack.size());
stack.pop(3);
break;
case Constants.FCMPG:
logInfo("FCMPG, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
case Constants.FCMPL:
logInfo("FCMPL, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
case Constants.FCONST_0:
logInfo("FCONST_0, stack size: " + stack.size());
stack.push(ObjectType.FLOAT);
break;
case Constants.FCONST_1:
logInfo("FCONST_1, stack size: " + stack.size());
stack.push(ObjectType.FLOAT);
break;
case Constants.FDIV:
logInfo("FDIV, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.FLOAT);
break;
// FLOAD - Load float from local variable
// Stack ... -> ..., result
case Constants.FLOAD_0:
wide = ProcessInstruction_Util.processFLOAD(0,stack, wide, bytes, varTable);
break;
case Constants.FLOAD_1:
wide = ProcessInstruction_Util.processFLOAD(1,stack, wide, bytes, varTable);
break;
case Constants.FLOAD_2:
wide = ProcessInstruction_Util.processFLOAD(2,stack, wide, bytes, varTable);
break;
case Constants.FLOAD_3:
wide = ProcessInstruction_Util.processFLOAD(3,stack, wide, bytes, varTable);
break;
case Constants.FLOAD:
wide = ProcessInstruction_Util.processFLOADn(stack, wide, bytes, varTable);
break;
// FMUL - Multiply floats
// Stack: ..., value1, value2 -> result
case Constants.FMUL:
logInfo("FMUL, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.FLOAT);
break;
// ..., value1, value2 ..., result
case Constants.FREM:
logInfo("FREM, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.FLOAT);
break;
// ..., value [empty]
case Constants.FRETURN:
logInfo("FRETURN, stack size: " + stack.size());
stack.pop(stack.size());
break;
// FSTORE - Store float into local variable
// Stack: ..., value -> ...
case Constants.FSTORE_0:
wide = ProcessInstruction_Util.processFSTORE(0, stack, wide, bytes);
break;
case Constants.FSTORE_1:
wide = ProcessInstruction_Util.processFSTORE(1, stack, wide, bytes);
break;
case Constants.FSTORE_2:
wide = ProcessInstruction_Util.processFSTORE(2, stack, wide, bytes);
break;
case Constants.FSTORE_3:
wide = ProcessInstruction_Util.processFSTORE(3, stack, wide, bytes);
break;
case Constants.FSTORE:
wide = ProcessInstruction_Util.processFSTOREn(stack, wide, bytes);
break;
// FSUB - Substract floats
// Stack: ..., value1, value2 -> result
case Constants.FSUB:
logInfo("FSUB, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.FLOAT);
// GOTO - Branch always (to relative offset, not absolute address)
case Constants.GOTO:
index = ProcessInstruction_Util.getIndexShortIcecream(bytes);
logInfo("GOTO, stack size: " + stack.size() + " offset: " + index);
// GoTo, skip opcodes
bytes.skipBytes(index-bytes.getIndex());
break;
// GOTO_W - Branch always (to relative offset, not absolute address)
case Constants.GOTO_W:
logInfo("GOTO_W, stack size: " + stack.size());
int windex = ProcessInstruction_Util.getIndexIntIcecream(bytes);
logInfo("GOTO_W, stack size: " + stack.size() + " offset: " + windex);
// GoTo, skip opcodes
bytes.skipBytes(windex-bytes.getIndex());
break;
// I2B - Convert int to byte
// Stack: ..., value -> ..., result
case Constants.I2B:
logInfo("I2B, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.INT);
break;
case Constants.I2C:
logInfo("I2C, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.INT);
break;
case Constants.I2D:
logInfo("I2D, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.DOUBLE);
break;
case Constants.I2F:
logInfo("I2F, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.FLOAT);
break;
case Constants.I2L:
logInfo("I2L, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.LONG);
break;
case Constants.I2S:
logInfo("I2S, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.INT);
break;
case Constants.IADD:
logInfo("IADD, stack size: " + stack.size());
{
Type t1 = stack.pop();
Type t2 = stack.pop();
Type retType = null;
if (t2 instanceof FieldReferenceType) {
//ToDo: Propogate field reference
stack.push(ObjectType.INT);
} else {
stack.push(ObjectType.INT);
}
}
break;
//Stack: ..., arrayref, index -> ..., value
case Constants.IALOAD:
logInfo("IALOAD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
//Stack: ..., value1, value2 -> ..., result
case Constants.IAND:
logInfo("IAND, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
//Stack: ..., arrayref, index, value -> ...
case Constants.IASTORE:
logInfo("IASTORE, stack size: " + stack.size());
stack.pop(3);
break;
// ICONST - Push value between -1, ..., 5, other values
// cause an exception
// Stack: ... -> ...,
case Constants.ICONST_0:
case Constants.ICONST_1:
case Constants.ICONST_2:
case Constants.ICONST_3:
case Constants.ICONST_4:
case Constants.ICONST_5:
case Constants.ICONST_M1:
logInfo("ICONST {0,1,2,3,4,5}, stack size" + stack.size());
stack.push(ObjectType.INT);
break;
//Stack: ..., value1, value2 -> result
case Constants.IDIV:
logInfo("IDIV, stack size" + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
// IF_ACMPEQ - Branch if reference comparison succeeds
// Stack: ..., value1, value2 -> ...
case Constants.IF_ACMPEQ:
// IF_ACMPNE - Branch if reference comparison doesn't succeed
// Stack: ..., value1, value2 -> ...
case Constants.IF_ACMPNE:
// IF_ICMPEQ - Branch if int comparison succeeds
// Stack: ..., value1, value2 -> ...
case Constants.IF_ICMPEQ:
case Constants.IF_ICMPGE:
case Constants.IF_ICMPGT:
case Constants.IF_ICMPLE:
case Constants.IF_ICMPLT:
// IF_ICMPNE - Branch if int comparison doesn't succeed
// Stack: ..., value1, value2 -> ...
case Constants.IF_ICMPNE:
logInfo("IF<>, stack size: " + stack.size());
stack.pop(2);
index = ProcessInstruction_Util.getIndexShortIcecream(bytes);
logInfo("IF: " + stack.size() + " " + index);
branchState = new BranchState(stack.getClone(),
lockStack.getClone(),
index);
branchQueue.add(branchState);
break;
// IFEQ - Branch if int comparison with zero succeeds
// Stack: ..., value -> ...
case Constants.IFEQ:
case Constants.IFGE:
case Constants.IFGT:
case Constants.IFLE:
case Constants.IFLT:
case Constants.IFNE:
// IFNONNULL - Branch if reference is not null
// Stack: ..., reference -> ...
case Constants.IFNONNULL:
case Constants.IFNULL:
logInfo("IF<>, stack size: " + stack.size());
if(stack.size()==0) {
Log.logByteInfo("ERROR: Attempting to pop empty stack");
Log.logByteInfo(parentMethodInfo.getFullUniqueMethodName());
} else {
stack.pop();
}
index = ProcessInstruction_Util.getIndexShortIcecream(bytes);
logInfo("IF: " + stack.size() + " " + index);
branchState = new BranchState(stack.getClone(),
lockStack.getClone(),
index);
branchQueue.add(branchState);
break;
// IINC - Increment local variable by constant
case Constants.IINC:
logInfo("IINC");
if (wide) {
vindex = bytes.readShort();
constant = bytes.readShort();
wide = false;
} else {
vindex = bytes.readUnsignedByte();
constant = bytes.readByte();
}
break;
// ILOAD - Load int from local variable onto stack
// Stack: ... -> ..., result
case Constants.ILOAD_0:
wide = ProcessInstruction_Util.processILOAD(parentMethodInfo,0,stack, wide, bytes, varTable);
break;
case Constants.ILOAD_1:
wide = ProcessInstruction_Util.processILOAD(parentMethodInfo,1,stack, wide, bytes, varTable);
break;
case Constants.ILOAD_2:
wide = ProcessInstruction_Util.processILOAD(parentMethodInfo,2,stack, wide, bytes, varTable);
break;
case Constants.ILOAD_3:
wide = ProcessInstruction_Util.processILOAD(parentMethodInfo,3,stack, wide, bytes, varTable);
break;
case Constants.ILOAD:
wide = ProcessInstruction_Util.processILOADn(parentMethodInfo,stack, wide, bytes, varTable);
break;
// Stack: ..., value1, value2 -> result
case Constants.IMUL:
logInfo("IMUL, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
// Stack: ..., value -> ..., result
case Constants.INEG:
logInfo("INEG, stack size: " + stack.size());
stack.pop(1);
stack.push(ObjectType.INT);
break;
// INSTANCEOF - Determine if object is of given type
// Stack: ..., objectref -> ..., result
case Constants.INSTANCEOF:
logInfo("INSTANCEOF, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.INT);
index = bytes.readShort();
break;
//Stack: ..., value1, value2 -> ..., result
case Constants.IOR:
case Constants.IREM:
case Constants.ISHL:
case Constants.ISHR:
logInfo("IOR, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
//Stack: ..., value -> <empty>
case Constants.IRETURN:
logInfo("IRETURN, stack size: " + stack.size());
stack.pop(stack.size());
break;
// ISTORE - Store int from stack into local variable
// Stack: ..., value -> ...
case Constants.ISTORE_0:
wide = ProcessInstruction_Util.processISTORE(0, stack, wide, bytes);
break;
case Constants.ISTORE_1:
wide = ProcessInstruction_Util.processISTORE(1, stack, wide, bytes);
break;
case Constants.ISTORE_2:
wide = ProcessInstruction_Util.processISTORE(2, stack, wide, bytes);
break;
case Constants.ISTORE_3:
wide = ProcessInstruction_Util.processISTORE(3, stack, wide, bytes);
break;
case Constants.ISTORE:
wide = ProcessInstruction_Util.processISTOREn(stack, wide, bytes);
break;
//Stack: ..., value1, value2 -> result
case Constants.ISUB:
logInfo("ISUB, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
//Stack: ..., value1, value2 -> ..., result
case Constants.IUSHR:
logInfo("IUSHR, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
//Stack: ..., value1, value2 -> ..., result
case Constants.IXOR:
logInfo("IXOR, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
case Constants.JSR:
index = ProcessInstruction_Util.getIndexShortIcecream(bytes);
logInfo("JSR, stack size: " + stack.size() + " " + index);
stack.push(ReturnaddressType.NO_TARGET);
break;
case Constants.JSR_W:
windex = ProcessInstruction_Util.getIndexIntIcecream(bytes);
logInfo("JSRW, stack size: " + stack.size() + " " + windex);
stack.push(ReturnaddressType.NO_TARGET);
break;
// L2D - Convert long to double
// Stack: ..., value.word1, value.word2 -> ..., result.word1, result.word2
case Constants.L2D:
logInfo("L2D, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.DOUBLE);
break;
// L2F - Convert long to float
// Stack: ..., value.word1, value.word2 -> ..., result
case Constants.L2F:
logInfo("L2F, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.FLOAT);
break;
// L2I - Convert long to int
// Stack: ..., value.word1, value.word2 -> ..., result
case Constants.L2I:
logInfo("L2I, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.INT);
break;
//..., value1, value2 ..., result
case Constants.LADD:
logInfo("LADD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
//..., arrayref, index ..., value
case Constants.LALOAD:
logInfo("LALOAD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
// ..., value1, value2 ..., result
case Constants.LAND:
logInfo("LAND, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
// ..., arrayref, index, value ...
case Constants.LASTORE:
logInfo("LASTORE, stack size: " + stack.size());
stack.pop(3);
break;
// ..., value1, value2 ..., result
case Constants.LCMP:
logInfo("LCMP, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
case Constants.LCONST_0:
case Constants.LCONST_1:
logInfo("LCONST_<0,1>, stack size: " + stack.size());
stack.push(ObjectType.LONG);
break;
// LDC - Push item from constant pool.
// Stack: ... -> ..., item
case Constants.LDC:
vindex = bytes.readUnsignedByte();
logInfo("LDC, stack size: " + stack.size());
if(stack.size()>=stack.maxStack()) {
Log.logByteInfo("Attempting to push stack size beyond limit");
Log.logByteInfo(parentMethodInfo.getFullUniqueMethodName());
}
stack.push(Type.UNKNOWN); //int, float, or long
break;
// LDC_W - Push item from constant pool (wide index)
// Stack: ... -> ..., item.word1, item.word2
case Constants.LDC_W:
vindex = bytes.readShort();
logInfo("LDC_W, stack size: " + stack.size());
stack.push(Type.UNKNOWN); //int, float, or long
break;
// LDC2_W - Push long or double from constant pool
// Stack: ... -> ..., item.word1, item.word2
case Constants.LDC2_W:
vindex = bytes.readShort();
logInfo("LDC2_W, stack size: " + stack.size());
stack.push(Type.UNKNOWN); //long or double
break;
//..., value1, value2 ..., result
case Constants.LDIV:
logInfo("LDIV, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
// LLOAD - Load long from local variable
// Stack ... -> ..., result.word1, result.word
case Constants.LLOAD_0:
wide = ProcessInstruction_Util.processLLOAD(0,stack, wide, bytes, varTable);
break;
case Constants.LLOAD_1:
wide = ProcessInstruction_Util.processLLOAD(1,stack, wide, bytes, varTable);
break;
case Constants.LLOAD_2:
wide = ProcessInstruction_Util.processLLOAD(2,stack, wide, bytes, varTable);
break;
case Constants.LLOAD_3:
wide = ProcessInstruction_Util.processLLOAD(3,stack, wide, bytes, varTable);
break;
case Constants.LLOAD:
wide = ProcessInstruction_Util.processLLOADn(stack, wide, bytes, varTable);
break;
//..., value1, value2 ..., result
case Constants.LMUL:
logInfo("LMUL, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
case Constants.LNEG:
logInfo("LNEG, stack size: " + stack.size());
stack.pop(1);
stack.push(ObjectType.LONG);
break;
// LOOKUPSWITCH - Switch with unordered set of values
case Constants.LOOKUPSWITCH:
logInfo("LOOKUPSWITCH");
stack.pop();
int npairs = bytes.readInt();
offset = bytes.getIndex() - 8 - no_pad_bytes - 1;
jump_table = new int[npairs];
default_offset += offset;
// Print switch indices in first row (and default)
for (int i = 0; i < npairs; i++) {
int match = bytes.readInt();
jump_table[i] = offset + bytes.readInt();
}
break;
// ..., value1, value2 ..., result
case Constants.LOR:
logInfo("LOR, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
//..., value1, value2 ..., result
case Constants.LREM:
logInfo("LREM, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
//..., value [empty]
case Constants.LRETURN:
logInfo("LRETURN, stack size: " + stack.size());
stack.pop(stack.size());
break;
//..., value1, value2 ..., result
case Constants.LSHL:
logInfo("LSHL, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
//..., value1, value2 ..., result
case Constants.LSHR:
logInfo("LSHR, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
// LSTORE - Store long into local variable
// Stack: ..., value.word1, value.word2 -> ...
case Constants.LSTORE_0:
wide = ProcessInstruction_Util.processLSTORE(0, stack, wide, bytes);
break;
case Constants.LSTORE_1:
wide = ProcessInstruction_Util.processLSTORE(1, stack, wide, bytes);
break;
case Constants.LSTORE_2:
wide = ProcessInstruction_Util.processLSTORE(2, stack, wide, bytes);
break;
case Constants.LSTORE_3:
wide = ProcessInstruction_Util.processLSTORE(3, stack, wide, bytes);
break;
case Constants.LSTORE:
wide = ProcessInstruction_Util.processLSTOREn(stack, wide, bytes);
break;
//..., value1, value2 ..., result
case Constants.LSUB:
logInfo("LSUB, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
case Constants.LUSHR:
logInfo("LUSHR, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
case Constants.LXOR:
logInfo("LXOR, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
// MONITORENTER - Enter monitor for object
// Stack: ..., objectref -> ...
case Constants.MONITORENTER:
logLocking("MONITORENTER, stack size: " + stack.size());
ProcessInstruction_Lock.processMonitorEnter(stack,
handlerList,
parentMethodInfo,
lockStack,
invokedLineNumber);
break;
// MONITOREXIT - Exit monitor for object
// Stack: ..., objectref -> ...
case Constants.MONITOREXIT:
logLocking("MONITOREXIT, stack size: " + stack.size());
ProcessInstruction_Lock.processMonitorExit(stack,
handlerList,
parentMethodInfo,
lockStack);
break;
// Multidimensional array of references.
case Constants.MULTIANEWARRAY:
logInfo("MULTIANEWARRAY, stack size: " + stack.size());
index = bytes.readShort();
int dimensions = bytes.readByte();
stack.pop(dimensions);
stack.push(new ArrayType(Type.UNKNOWN, dimensions));
break;
// NEW - Create new object
// Stack: ... -> ..., objectref
case Constants.NEW:
logInfo("NEW, stack size: " + stack.size());
// get name of Java class
index = bytes.readShort();
ConstantClass cc = (ConstantClass)constant_pool.getConstant(index);
ConstantUtf8 c = (ConstantUtf8)constant_pool.getConstant(cc.getNameIndex());
String rawClassName = c.getBytes();
String fullClassName = Utility.compactClassName(rawClassName, false);
logInfo("NEW, stack size " + stack.size() + " " + index + " " + fullClassName);
// push reference to stack
ObjectType type = new ObjectType(fullClassName);
stack.push(type);
break;
// NEWARRAY - Create new array of basic type (int, short, ...)
// Stack: ..., count -> ..., arrayref
// type must be one of T_INT, T_SHORT, ...
case Constants.NEWARRAY:
logInfo("NEWARRAY");
index = bytes.readByte();
stack.pop();
t = new ArrayType(ObjectType.UNKNOWN,1);
stack.push(t);
break;
case Constants.NOP:
break;
// POP - Pop top operand stack word
// Stack: ..., word -> ...
case Constants.POP:
logInfo("POP, stack size: " + stack.size());
stack.pop();
break;
// POP2 - Pop two top operand stack words
// Stack: ..., word2, word1 -> ...
case Constants.POP2:
logInfo("POP2, stack size: " + stack.size());
try {
t = stack.peek();
// cat2
if (t == ObjectType.LONG || t == ObjectType.DOUBLE) {
stack.pop(1);
// cat1
} else {
stack.pop(2);
}
} catch (Exception e) {
logInfo("ERROR, POP2");
}
break;
// RET - Return from subroutine
// Stack: ... -> ...
case Constants.RET:
logInfo("RET, stack size: " + stack.size());
vindex = ProcessInstruction_Util.getVariableIndex(wide, bytes);
wide = false; // clear flag
break;
// RETURN - Return from void method
// Stack: ... -> <empty>
case Constants.RETURN:
logInfo("RETURN, stack size: " + stack.size());
stack.pop(stack.size());
break;
// SALOAD - Load short from array
// Stack: ..., arrayref, index -> ..., value
case Constants.SALOAD:
logInfo("SALOAD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
// SASTORE - Store into short array
// Stack: ..., arrayref, index, value -> ...
case Constants.SASTORE:
logInfo("SASTORE, stack size: " + stack.size());
stack.pop(3);
break;
// SIPUSH - Push short
// Stack: ... -> ..., value
case Constants.SIPUSH:
logInfo("SIPUSH, stack size: " + stack.size());
bytes.readByte();
bytes.readByte();
stack.push(ObjectType.INT);
break;
// SWAP - Swa top operand stack word
// Stack: ..., word2, word1 -> ..., word1, word2
case Constants.SWAP:
logInfo("SWAP, stack size: " + stack.size());
// noop
break;
// Remember wide byte which is used to form a 16-bit address in the
// following instruction. Relies on that the method is called again with
// the following opcode.
case Constants.WIDE:
logInfo("WIDE");
wide = true;
break;
// handled in helper method
case Constants.PUTSTATIC:
case Constants.PUTFIELD:
case Constants.GETSTATIC:
case Constants.GETFIELD:
ProcessInstruction_SetGetField.processField(
opcode,
stack,
constant_pool,bytes,
jClass,
parentMethodInfo,
invokedLineNumber,
lockStack.isSynchronized(),
handlerList);
break;
// INVOKESPECIAL - Invoke instance method; special handling for
// superclass, private and instance initialization method invocations
// Stack: ..., objectref, [arg1, [arg2 ...]] -> ...
case Constants.INVOKESPECIAL:
logInfo("(INVOKESPECIAL)");
case Constants.INVOKESTATIC:
logInfo("(INVOKESTATIC)");
case Constants.INVOKEVIRTUAL:
logInfo("(INVOKEVIRTUAL)");
case Constants.INVOKEINTERFACE:
logInfo("(INVOKEINTERFACE)");
logInfo("INVOKE, stack size: " + stack.size() + " lock stack size: " + lockStack.debugGetSize());
ProcessInstruction_MethodInvoke.processMethodInvoke(stack,
constant_pool,
jClass,
handlerList,
hashMapSynthetic,
opcode, bytes,
invokedLineNumber,
parentMethodInfo,
lockStack);
break;
default:
logInfo("DEFAULT: " + opcode);
if(true)
throw new Exception("Missing DEFAULT: " + opcode);
if (Constants.NO_OF_OPERANDS[opcode] > 0) {
for (int i = 0; i < Constants.TYPE_OF_OPERANDS[opcode].length; i++) {
switch (Constants.TYPE_OF_OPERANDS[opcode][i]) {
case Constants.T_BYTE:
break;
case Constants.T_SHORT: // Either branch or index
break;
case Constants.T_INT:
break;
default: // Never reached
System.err.println("Unreachable default case reached!");
}
}
}
}
}
}
| false | true | static void processInstruction(
short opcode,
HashMap<Integer,Boolean> visitedByteOffsets,
Queue<BranchState> branchQueue,
BranchState currBranch,
HashMap<Integer,Type> runtimeVariableTable,
JavaClass jClass,
ArrayList<IClassFileParseHandler> handlerList,
HashMap<String,java.lang.reflect.AccessibleObject> hashMapSynthetic,
Method parentMethod,
java.lang.reflect.AccessibleObject parentMethodR,
ByteReader bytes,
IMethodInfo parentMethodInfo)
throws Exception {
ConstantPool constant_pool = jClass.getConstantPool();
Code code = parentMethod.getCode();
boolean parentIsSynthetic = parentMethod.isSynthetic();
LineNumberTable lineTable = code.getLineNumberTable();
OperandStack stack = currBranch.getStack();
LockStack lockStack = currBranch.getLockInfo();
//ByteReader bytes = new ByteReader(code.getCode());
//bytes.mark(bytes.available());
//bytes.reset();
//bytes.skipBytes(currBranch.getIndex());
int currOffset = bytes.getIndex();
//ToDo: get this from BCEL
boolean isStaticBlock = parentMethod.getName().equals(ByteCodeConstants.STATICBLOCK_IDENTIFIER);
//logInfo("opcode: " + opcode + " ALOAD_1: " + Constants.ALOAD_1);
String name, signature;
String className = null;
int default_offset = 0, low, high;
int index, class_index, vindex, constant;
int[] jump_table;
int no_pad_bytes = 0, offset;
Type t;
BranchState branchState;
// varTable may be null in some situations
LocalVariableTable varTable = code.getLocalVariableTable();
int line_number_ind = bytes.getIndex();
int invokedLineNumber;
if (lineTable != null) {
invokedLineNumber = lineTable.getSourceLine(line_number_ind);
} else {
invokedLineNumber = org.checkthread.main.Constants.NO_LINE_NUMBER;
}
Log.logByteInfo("Byte Offset: " + bytes.getIndex() + " Stack size: " + stack.size());
/*
* Special case: Skip (0-3) padding bytes, i.e., the following bytes are
* 4-byte-aligned
*/
if ((opcode == Constants.TABLESWITCH)
|| (opcode == Constants.LOOKUPSWITCH)) {
int remainder = bytes.getIndex() % 4;
no_pad_bytes = (remainder == 0) ? 0 : 4 - remainder;
for (int i = 0; i < no_pad_bytes; i++) {
bytes.readByte();
}
// Both cases have a field default_offset in common
default_offset = bytes.readInt();
}
switch (opcode) {
// TABLESWITCH - Switch within given range of values, i.e., low..high
case Constants.TABLESWITCH:
logInfo("TABLESWITCH");
stack.pop();
low = bytes.readInt();
high = bytes.readInt();
offset = bytes.getIndex() - 12 - no_pad_bytes - 1;
default_offset += offset;
// Print switch indices in first row (and default)
jump_table = new int[high - low + 1];
for (int i = 0; i < jump_table.length; i++) {
jump_table[i] = offset + bytes.readInt();
}
break;
// AALOAD - Load reference from array
// Stack: ..., arrayref, index -> value
case Constants.AALOAD:
logInfo("AALOAD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.NULL);
break;
// AASTORE - Store into reference array
// Stack: ..., arrayref, index, value -> ...
case Constants.AASTORE:
logInfo("AASTORE, stack size: " + stack.size());
stack.pop(3);
break;
// ACONST_NULL - Push null reference
// Stack: ... -> ..., null
case Constants.ACONST_NULL:
logInfo("ACONST_NULL, stack size: " + stack.size());
stack.push(ObjectType.NULL);
break;
// ALOAD - Load reference from local variable
// Stack: ... -> ..., objectref
case Constants.ALOAD_0:
wide = ProcessInstruction_Util.processALOAD(0,stack, wide, bytes, varTable, runtimeVariableTable);
break;
case Constants.ALOAD_1:
wide = ProcessInstruction_Util.processALOAD(1,stack, wide, bytes, varTable, runtimeVariableTable);
break;
case Constants.ALOAD_2:
wide = ProcessInstruction_Util.processALOAD(2,stack, wide, bytes, varTable, runtimeVariableTable);
break;
case Constants.ALOAD_3:
wide = ProcessInstruction_Util.processALOAD(3,stack, wide, bytes, varTable, runtimeVariableTable);
break;
case Constants.ALOAD:
wide = ProcessInstruction_Util.processALOADn(stack, wide, bytes, varTable, runtimeVariableTable);
break;
// ANEWARRAY - Create new array of references
// Stack: ..., count -> ..., arrayref
case Constants.ANEWARRAY: {
logInfo("ANEWARRAY, stack size: " + stack.size());
bytes.readShort();
stack.pop();
t = new ArrayType(ObjectType.NULL,1);
stack.push(t);
break;
}
// ARETURN - Return reference from method
// Stack: ..., objectref -> <empty>
case Constants.ARETURN:
logInfo("ARETURN, stack size: " + stack.size());
stack.pop(stack.size());
break;
// ARRAYLENGTH - Get length of array
// Stack: ..., arrayref -> ..., length
case Constants.ARRAYLENGTH:
logInfo("ARRAYLENGTH, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.INT);
break;
// ASTORE - Store reference into local variable
// Stack ..., objectref -> ...
case Constants.ASTORE_0:
wide = ProcessInstruction_Util.processASTORE(0,stack, wide, bytes, runtimeVariableTable);
break;
case Constants.ASTORE_1:
wide = ProcessInstruction_Util.processASTORE(1,stack, wide, bytes, runtimeVariableTable);
break;
case Constants.ASTORE_2:
wide = ProcessInstruction_Util.processASTORE(2,stack, wide, bytes, runtimeVariableTable);
break;
case Constants.ASTORE_3:
wide = ProcessInstruction_Util.processASTORE(3,stack, wide, bytes, runtimeVariableTable);
break;
case Constants.ASTORE:
wide = ProcessInstruction_Util.processASTOREn(stack, wide, bytes, runtimeVariableTable);
break;
// ATHROW - Throw exception
// Stack: ..., objectref -> objectref
case Constants.ATHROW:
logInfo("ATHROW, stack size: " + stack.size());
stack.pop(stack.size());
//stack.push(ObjectType.NULL);
break;
// BALOAD - Load byte or boolean from array
// Stack: ..., arrayref, index -> ..., value
case Constants.BALOAD:
logInfo("BALOAD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
// BASTORE - Store into byte or boolean array
// Stack: ..., arrayref, index, value -> ...
case Constants.BASTORE:
logInfo("BASTORE, stack size: " + stack.size());
stack.pop(3);
break;
// BIPUSH - Push byte on stack
// Stack: ... -> ..., value
case Constants.BIPUSH:
logInfo("BIPUSH, stack size: " + stack.size());
bytes.readByte();
stack.push(ObjectType.INT);
break;
// CALOAD - Load char from array
// Stack: ..., arrayref, index -> ..., value
case Constants.CALOAD:
logInfo("CALOAD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
// CASTORE - Store into char array
// Stack: ..., arrayref, index, value -> ...
case Constants.CASTORE:
logInfo("CASTORE, stack size: " + stack.size());
stack.pop(3);
break;
// CHECKCAST - Check whether object is of given type
// Stack: ..., objectref -> ..., objectref
case Constants.CHECKCAST:
logInfo("CHECKCAST, stack size: " + stack.size());
index = bytes.readShort();
break;
// D2F - Convert double to float
// Stack: ..., value.word1, value.word2 -> ..., result
case Constants.D2F:
logInfo("D2F, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.FLOAT);
break;
// D2I - Convert double to int
// Stack: ..., value.word1, value.word2 -> ..., result
case Constants.D2I:
logInfo("D2I, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.INT);
break;
// D2L - Convert double to long
// Stack: ..., value.word1, value.word2 -> ..., result.word1, result.word2
case Constants.D2L:
logInfo("D2L, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.LONG);
break;
// DADD - Add doubles
// Stack: ..., value1.word1, value1.word2, value2.word1, value2.word2 ->
// ..., result.word1, result1.word2
case Constants.DADD:
logInfo("DADD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.DOUBLE);
break;
// DALOAD - Load double from array
// Stack: ..., arrayref, index -> ..., result.word1, result.word2
case Constants.DALOAD:
logInfo("DALOAD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.DOUBLE);
break;
// DASTORE - Store into double array
// Stack: ..., arrayref, index, value.word1, value.word2 -> ...
case Constants.DASTORE:
logInfo("DASTORE, stack size: " + stack.size());
stack.pop(3);
break;
// DCMPG - Compare doubles: value1 > value2
// Stack: ..., value1.word1, value1.word2, value2.word1, value2.word2 ->
// ..., result
case Constants.DCMPG:
logInfo("DCMPG, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
case Constants.DCMPL:
logInfo("DCMPL, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
// DCONST - Push 0.0 or 1.0, other values cause an exception
// Stack: ... -> ...,
case Constants.DCONST_0:
logInfo("DCONST_0, stack size: " + stack.size());
stack.push(ObjectType.DOUBLE);
break;
case Constants.DCONST_1:
logInfo("DCONST_1, stack size: " + stack.size());
stack.push(ObjectType.DOUBLE);
break;
// ..., value1, value2 ..., result
case Constants.DDIV:
logInfo("DDIV, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.DOUBLE);
break;
// DLOAD - Load double from local variable
// Stack ... -> ..., result.word1, result.word2
case Constants.DLOAD_0:
wide = ProcessInstruction_Util.processDLOAD(0, stack, wide, bytes, varTable);
break;
case Constants.DLOAD_1:
wide = ProcessInstruction_Util.processDLOAD(1, stack, wide, bytes, varTable);
break;
case Constants.DLOAD_2:
wide = ProcessInstruction_Util.processDLOAD(2, stack, wide, bytes, varTable);
break;
case Constants.DLOAD_3:
wide = ProcessInstruction_Util.processDLOAD(3, stack, wide, bytes, varTable);
break;
case Constants.DLOAD:
wide = ProcessInstruction_Util.processDLOADn(stack, wide, bytes, varTable);
break;
// ..., value1, value2 ..., result
case Constants.DMUL:
logInfo("DMUL, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.DOUBLE);
break;
// ..., value ..., result
case Constants.DNEG:
logInfo("DNEG, stack size: " + stack.size());
stack.pop(1);
stack.push(ObjectType.DOUBLE);
break;
// ..., value1, value2 ..., result
case Constants.DREM:
logInfo("DREM, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.DOUBLE);
break;
// ..., value [empty]
case Constants.DRETURN:
logInfo("DRETURN, stack size: " + stack.size());
stack.pop(stack.size());
break;
// DSTORE - Store double into local variable
// Stack: ..., value.word1, value.word2 -> ...
case Constants.DSTORE_0:
wide = ProcessInstruction_Util.processDSTORE(0, stack, wide, bytes);
break;
case Constants.DSTORE_1:
wide = ProcessInstruction_Util.processDSTORE(1, stack, wide, bytes);
break;
case Constants.DSTORE_2:
wide = ProcessInstruction_Util.processDSTORE(2, stack, wide, bytes);
break;
case Constants.DSTORE_3:
wide = ProcessInstruction_Util.processDSTORE(3, stack, wide, bytes);
break;
case Constants.DSTORE:
wide = ProcessInstruction_Util.processDSTOREn(stack, wide, bytes);
break;
// ..., value1, value2 ..., result
case Constants.DSUB:
logInfo("DSUB, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.DOUBLE);
break;
// DUP - Duplicate top operand stack word
// Stack: ..., word -> ..., word, word
case Constants.DUP: {
logInfo("DUP, stack size: " + stack.size());
if(stack.size()>=stack.maxStack()) {
Log.severe("Stack filled up: " + parentMethodInfo.getFullUniqueMethodName());
}
stack.push(stack.peek());
break;
}
// ..., value2, value1 ..., value1, value2, value1
case Constants.DUP_X1:
logInfo("DUP_X1, stack size: " + stack.size());
stack.push(stack.peek());
break;
// Form 1:
// ..., value3, value2, value1 ..., value1, value3, value2, value1
// where value1, value2, and value3 are all values of a category 1 computational type (�3.11.1).
//
// Form 2:
// ..., value2, value1 ..., value1, value2, value1
// where value1 is a value of a category 1 computational type and value2 is a value of a category 2 computational type (�3.11.1).
case Constants.DUP_X2:
logInfo("DUP_X2, stack size: " + stack.size());
t = stack.peek();
// category 2
if(t == ObjectType.DOUBLE || t == ObjectType.LONG) {
stack.push(stack.peek());
// category 1
} else {
stack.push(stack.peek());
}
// Form 1:
// ..., value2, value1 ..., value2, value1, value2, value1
// where both value1 and value2 are values of a category 1 computational type (�3.11.1).
// Form 2:
// ..., value ..., value, value
// where value is a value of a category 2 computational type (�3.11.1).
case Constants.DUP2:
logInfo("DUP2, stack size: " + stack.size());
t = stack.peek();
// category 2
if(t == ObjectType.DOUBLE || t == ObjectType.LONG) {
stack.push(stack.peek(2));
stack.push(stack.peek(3));
// category 1
} else {
stack.push(stack.peek());
}
break;
// Form 1:
// ..., value3, value2, value1 ..., value2, value1, value3, value2, value1
// where value1, value2, and value3 are all values of a category 1 computational type (�3.11.1).
// Form 2:
// ..., value2, value1 ..., value1, value2, value1
// where value1 is a value of a category 2 computational type and value2 is a value of a category 1 computational type (�3.11.1).
case Constants.DUP2_X1:
logInfo("DUP2_X1, stack size: " + stack.size());
t = stack.peek();
// category 2
if(t == ObjectType.DOUBLE || t == ObjectType.LONG) {
stack.push(stack.peek());
// category 1
} else {
stack.push(stack.peek());
stack.push(stack.peek());
}
break;
// DUP_X2 - Duplicate top operand stack word and put three down
// Stack: ..., word3, word2, word1 -> ..., word1, word3, word2, word1
case Constants.DUP2_X2:
logInfo("DUP2_X2, stack size: " + stack.size());
stack.push(stack.peek());
break;
// Float operations
case Constants.F2D:
logInfo("F2D, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.DOUBLE);
break;
case Constants.F2I:
logInfo("F2I, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.INT);
break;
case Constants.F2L:
logInfo("F2L, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.LONG);
break;
case Constants.FADD:
logInfo("FADD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.FLOAT);
break;
case Constants.FALOAD:
logInfo("FALOAD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.FLOAT);
break;
case Constants.FASTORE:
logInfo("FASTORE, stack size: " + stack.size());
stack.pop(3);
break;
case Constants.FCMPG:
logInfo("FCMPG, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
case Constants.FCMPL:
logInfo("FCMPL, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
case Constants.FCONST_0:
logInfo("FCONST_0, stack size: " + stack.size());
stack.push(ObjectType.FLOAT);
break;
case Constants.FCONST_1:
logInfo("FCONST_1, stack size: " + stack.size());
stack.push(ObjectType.FLOAT);
break;
case Constants.FDIV:
logInfo("FDIV, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.FLOAT);
break;
// FLOAD - Load float from local variable
// Stack ... -> ..., result
case Constants.FLOAD_0:
wide = ProcessInstruction_Util.processFLOAD(0,stack, wide, bytes, varTable);
break;
case Constants.FLOAD_1:
wide = ProcessInstruction_Util.processFLOAD(1,stack, wide, bytes, varTable);
break;
case Constants.FLOAD_2:
wide = ProcessInstruction_Util.processFLOAD(2,stack, wide, bytes, varTable);
break;
case Constants.FLOAD_3:
wide = ProcessInstruction_Util.processFLOAD(3,stack, wide, bytes, varTable);
break;
case Constants.FLOAD:
wide = ProcessInstruction_Util.processFLOADn(stack, wide, bytes, varTable);
break;
// FMUL - Multiply floats
// Stack: ..., value1, value2 -> result
case Constants.FMUL:
logInfo("FMUL, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.FLOAT);
break;
// ..., value1, value2 ..., result
case Constants.FREM:
logInfo("FREM, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.FLOAT);
break;
// ..., value [empty]
case Constants.FRETURN:
logInfo("FRETURN, stack size: " + stack.size());
stack.pop(stack.size());
break;
// FSTORE - Store float into local variable
// Stack: ..., value -> ...
case Constants.FSTORE_0:
wide = ProcessInstruction_Util.processFSTORE(0, stack, wide, bytes);
break;
case Constants.FSTORE_1:
wide = ProcessInstruction_Util.processFSTORE(1, stack, wide, bytes);
break;
case Constants.FSTORE_2:
wide = ProcessInstruction_Util.processFSTORE(2, stack, wide, bytes);
break;
case Constants.FSTORE_3:
wide = ProcessInstruction_Util.processFSTORE(3, stack, wide, bytes);
break;
case Constants.FSTORE:
wide = ProcessInstruction_Util.processFSTOREn(stack, wide, bytes);
break;
// FSUB - Substract floats
// Stack: ..., value1, value2 -> result
case Constants.FSUB:
logInfo("FSUB, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.FLOAT);
// GOTO - Branch always (to relative offset, not absolute address)
case Constants.GOTO:
index = ProcessInstruction_Util.getIndexShortIcecream(bytes);
logInfo("GOTO, stack size: " + stack.size() + " offset: " + index);
// GoTo, skip opcodes
bytes.skipBytes(index-bytes.getIndex());
break;
// GOTO_W - Branch always (to relative offset, not absolute address)
case Constants.GOTO_W:
logInfo("GOTO_W, stack size: " + stack.size());
int windex = ProcessInstruction_Util.getIndexIntIcecream(bytes);
logInfo("GOTO_W, stack size: " + stack.size() + " offset: " + windex);
// GoTo, skip opcodes
bytes.skipBytes(windex-bytes.getIndex());
break;
// I2B - Convert int to byte
// Stack: ..., value -> ..., result
case Constants.I2B:
logInfo("I2B, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.INT);
break;
case Constants.I2C:
logInfo("I2C, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.INT);
break;
case Constants.I2D:
logInfo("I2D, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.DOUBLE);
break;
case Constants.I2F:
logInfo("I2F, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.FLOAT);
break;
case Constants.I2L:
logInfo("I2L, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.LONG);
break;
case Constants.I2S:
logInfo("I2S, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.INT);
break;
case Constants.IADD:
logInfo("IADD, stack size: " + stack.size());
{
Type t1 = stack.pop();
Type t2 = stack.pop();
Type retType = null;
if (t2 instanceof FieldReferenceType) {
//ToDo: Propogate field reference
stack.push(ObjectType.INT);
} else {
stack.push(ObjectType.INT);
}
}
break;
//Stack: ..., arrayref, index -> ..., value
case Constants.IALOAD:
logInfo("IALOAD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
//Stack: ..., value1, value2 -> ..., result
case Constants.IAND:
logInfo("IAND, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
//Stack: ..., arrayref, index, value -> ...
case Constants.IASTORE:
logInfo("IASTORE, stack size: " + stack.size());
stack.pop(3);
break;
// ICONST - Push value between -1, ..., 5, other values
// cause an exception
// Stack: ... -> ...,
case Constants.ICONST_0:
case Constants.ICONST_1:
case Constants.ICONST_2:
case Constants.ICONST_3:
case Constants.ICONST_4:
case Constants.ICONST_5:
case Constants.ICONST_M1:
logInfo("ICONST {0,1,2,3,4,5}, stack size" + stack.size());
stack.push(ObjectType.INT);
break;
//Stack: ..., value1, value2 -> result
case Constants.IDIV:
logInfo("IDIV, stack size" + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
// IF_ACMPEQ - Branch if reference comparison succeeds
// Stack: ..., value1, value2 -> ...
case Constants.IF_ACMPEQ:
// IF_ACMPNE - Branch if reference comparison doesn't succeed
// Stack: ..., value1, value2 -> ...
case Constants.IF_ACMPNE:
// IF_ICMPEQ - Branch if int comparison succeeds
// Stack: ..., value1, value2 -> ...
case Constants.IF_ICMPEQ:
case Constants.IF_ICMPGE:
case Constants.IF_ICMPGT:
case Constants.IF_ICMPLE:
case Constants.IF_ICMPLT:
// IF_ICMPNE - Branch if int comparison doesn't succeed
// Stack: ..., value1, value2 -> ...
case Constants.IF_ICMPNE:
logInfo("IF<>, stack size: " + stack.size());
stack.pop(2);
index = ProcessInstruction_Util.getIndexShortIcecream(bytes);
logInfo("IF: " + stack.size() + " " + index);
branchState = new BranchState(stack.getClone(),
lockStack.getClone(),
index);
branchQueue.add(branchState);
break;
// IFEQ - Branch if int comparison with zero succeeds
// Stack: ..., value -> ...
case Constants.IFEQ:
case Constants.IFGE:
case Constants.IFGT:
case Constants.IFLE:
case Constants.IFLT:
case Constants.IFNE:
// IFNONNULL - Branch if reference is not null
// Stack: ..., reference -> ...
case Constants.IFNONNULL:
case Constants.IFNULL:
logInfo("IF<>, stack size: " + stack.size());
if(stack.size()==0) {
Log.logByteInfo("ERROR: Attempting to pop empty stack");
Log.logByteInfo(parentMethodInfo.getFullUniqueMethodName());
} else {
stack.pop();
}
index = ProcessInstruction_Util.getIndexShortIcecream(bytes);
logInfo("IF: " + stack.size() + " " + index);
branchState = new BranchState(stack.getClone(),
lockStack.getClone(),
index);
branchQueue.add(branchState);
break;
// IINC - Increment local variable by constant
case Constants.IINC:
logInfo("IINC");
if (wide) {
vindex = bytes.readShort();
constant = bytes.readShort();
wide = false;
} else {
vindex = bytes.readUnsignedByte();
constant = bytes.readByte();
}
break;
// ILOAD - Load int from local variable onto stack
// Stack: ... -> ..., result
case Constants.ILOAD_0:
wide = ProcessInstruction_Util.processILOAD(parentMethodInfo,0,stack, wide, bytes, varTable);
break;
case Constants.ILOAD_1:
wide = ProcessInstruction_Util.processILOAD(parentMethodInfo,1,stack, wide, bytes, varTable);
break;
case Constants.ILOAD_2:
wide = ProcessInstruction_Util.processILOAD(parentMethodInfo,2,stack, wide, bytes, varTable);
break;
case Constants.ILOAD_3:
wide = ProcessInstruction_Util.processILOAD(parentMethodInfo,3,stack, wide, bytes, varTable);
break;
case Constants.ILOAD:
wide = ProcessInstruction_Util.processILOADn(parentMethodInfo,stack, wide, bytes, varTable);
break;
// Stack: ..., value1, value2 -> result
case Constants.IMUL:
logInfo("IMUL, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
// Stack: ..., value -> ..., result
case Constants.INEG:
logInfo("INEG, stack size: " + stack.size());
stack.pop(1);
stack.push(ObjectType.INT);
break;
// INSTANCEOF - Determine if object is of given type
// Stack: ..., objectref -> ..., result
case Constants.INSTANCEOF:
logInfo("INSTANCEOF, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.INT);
index = bytes.readShort();
break;
//Stack: ..., value1, value2 -> ..., result
case Constants.IOR:
case Constants.IREM:
case Constants.ISHL:
case Constants.ISHR:
logInfo("IOR, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
//Stack: ..., value -> <empty>
case Constants.IRETURN:
logInfo("IRETURN, stack size: " + stack.size());
stack.pop(stack.size());
break;
// ISTORE - Store int from stack into local variable
// Stack: ..., value -> ...
case Constants.ISTORE_0:
wide = ProcessInstruction_Util.processISTORE(0, stack, wide, bytes);
break;
case Constants.ISTORE_1:
wide = ProcessInstruction_Util.processISTORE(1, stack, wide, bytes);
break;
case Constants.ISTORE_2:
wide = ProcessInstruction_Util.processISTORE(2, stack, wide, bytes);
break;
case Constants.ISTORE_3:
wide = ProcessInstruction_Util.processISTORE(3, stack, wide, bytes);
break;
case Constants.ISTORE:
wide = ProcessInstruction_Util.processISTOREn(stack, wide, bytes);
break;
//Stack: ..., value1, value2 -> result
case Constants.ISUB:
logInfo("ISUB, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
//Stack: ..., value1, value2 -> ..., result
case Constants.IUSHR:
logInfo("IUSHR, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
//Stack: ..., value1, value2 -> ..., result
case Constants.IXOR:
logInfo("IXOR, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
case Constants.JSR:
index = ProcessInstruction_Util.getIndexShortIcecream(bytes);
logInfo("JSR, stack size: " + stack.size() + " " + index);
stack.push(ReturnaddressType.NO_TARGET);
break;
case Constants.JSR_W:
windex = ProcessInstruction_Util.getIndexIntIcecream(bytes);
logInfo("JSRW, stack size: " + stack.size() + " " + windex);
stack.push(ReturnaddressType.NO_TARGET);
break;
// L2D - Convert long to double
// Stack: ..., value.word1, value.word2 -> ..., result.word1, result.word2
case Constants.L2D:
logInfo("L2D, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.DOUBLE);
break;
// L2F - Convert long to float
// Stack: ..., value.word1, value.word2 -> ..., result
case Constants.L2F:
logInfo("L2F, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.FLOAT);
break;
// L2I - Convert long to int
// Stack: ..., value.word1, value.word2 -> ..., result
case Constants.L2I:
logInfo("L2I, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.INT);
break;
//..., value1, value2 ..., result
case Constants.LADD:
logInfo("LADD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
//..., arrayref, index ..., value
case Constants.LALOAD:
logInfo("LALOAD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
// ..., value1, value2 ..., result
case Constants.LAND:
logInfo("LAND, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
// ..., arrayref, index, value ...
case Constants.LASTORE:
logInfo("LASTORE, stack size: " + stack.size());
stack.pop(3);
break;
// ..., value1, value2 ..., result
case Constants.LCMP:
logInfo("LCMP, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
case Constants.LCONST_0:
case Constants.LCONST_1:
logInfo("LCONST_<0,1>, stack size: " + stack.size());
stack.push(ObjectType.LONG);
break;
// LDC - Push item from constant pool.
// Stack: ... -> ..., item
case Constants.LDC:
vindex = bytes.readUnsignedByte();
logInfo("LDC, stack size: " + stack.size());
if(stack.size()>=stack.maxStack()) {
Log.logByteInfo("Attempting to push stack size beyond limit");
Log.logByteInfo(parentMethodInfo.getFullUniqueMethodName());
}
stack.push(Type.UNKNOWN); //int, float, or long
break;
// LDC_W - Push item from constant pool (wide index)
// Stack: ... -> ..., item.word1, item.word2
case Constants.LDC_W:
vindex = bytes.readShort();
logInfo("LDC_W, stack size: " + stack.size());
stack.push(Type.UNKNOWN); //int, float, or long
break;
// LDC2_W - Push long or double from constant pool
// Stack: ... -> ..., item.word1, item.word2
case Constants.LDC2_W:
vindex = bytes.readShort();
logInfo("LDC2_W, stack size: " + stack.size());
stack.push(Type.UNKNOWN); //long or double
break;
//..., value1, value2 ..., result
case Constants.LDIV:
logInfo("LDIV, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
// LLOAD - Load long from local variable
// Stack ... -> ..., result.word1, result.word
case Constants.LLOAD_0:
wide = ProcessInstruction_Util.processLLOAD(0,stack, wide, bytes, varTable);
break;
case Constants.LLOAD_1:
wide = ProcessInstruction_Util.processLLOAD(1,stack, wide, bytes, varTable);
break;
case Constants.LLOAD_2:
wide = ProcessInstruction_Util.processLLOAD(2,stack, wide, bytes, varTable);
break;
case Constants.LLOAD_3:
wide = ProcessInstruction_Util.processLLOAD(3,stack, wide, bytes, varTable);
break;
case Constants.LLOAD:
wide = ProcessInstruction_Util.processLLOADn(stack, wide, bytes, varTable);
break;
//..., value1, value2 ..., result
case Constants.LMUL:
logInfo("LMUL, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
case Constants.LNEG:
logInfo("LNEG, stack size: " + stack.size());
stack.pop(1);
stack.push(ObjectType.LONG);
break;
// LOOKUPSWITCH - Switch with unordered set of values
case Constants.LOOKUPSWITCH:
logInfo("LOOKUPSWITCH");
stack.pop();
int npairs = bytes.readInt();
offset = bytes.getIndex() - 8 - no_pad_bytes - 1;
jump_table = new int[npairs];
default_offset += offset;
// Print switch indices in first row (and default)
for (int i = 0; i < npairs; i++) {
int match = bytes.readInt();
jump_table[i] = offset + bytes.readInt();
}
break;
// ..., value1, value2 ..., result
case Constants.LOR:
logInfo("LOR, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
//..., value1, value2 ..., result
case Constants.LREM:
logInfo("LREM, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
//..., value [empty]
case Constants.LRETURN:
logInfo("LRETURN, stack size: " + stack.size());
stack.pop(stack.size());
break;
//..., value1, value2 ..., result
case Constants.LSHL:
logInfo("LSHL, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
//..., value1, value2 ..., result
case Constants.LSHR:
logInfo("LSHR, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
// LSTORE - Store long into local variable
// Stack: ..., value.word1, value.word2 -> ...
case Constants.LSTORE_0:
wide = ProcessInstruction_Util.processLSTORE(0, stack, wide, bytes);
break;
case Constants.LSTORE_1:
wide = ProcessInstruction_Util.processLSTORE(1, stack, wide, bytes);
break;
case Constants.LSTORE_2:
wide = ProcessInstruction_Util.processLSTORE(2, stack, wide, bytes);
break;
case Constants.LSTORE_3:
wide = ProcessInstruction_Util.processLSTORE(3, stack, wide, bytes);
break;
case Constants.LSTORE:
wide = ProcessInstruction_Util.processLSTOREn(stack, wide, bytes);
break;
//..., value1, value2 ..., result
case Constants.LSUB:
logInfo("LSUB, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
case Constants.LUSHR:
logInfo("LUSHR, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
case Constants.LXOR:
logInfo("LXOR, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
// MONITORENTER - Enter monitor for object
// Stack: ..., objectref -> ...
case Constants.MONITORENTER:
logLocking("MONITORENTER, stack size: " + stack.size());
ProcessInstruction_Lock.processMonitorEnter(stack,
handlerList,
parentMethodInfo,
lockStack,
invokedLineNumber);
break;
// MONITOREXIT - Exit monitor for object
// Stack: ..., objectref -> ...
case Constants.MONITOREXIT:
logLocking("MONITOREXIT, stack size: " + stack.size());
ProcessInstruction_Lock.processMonitorExit(stack,
handlerList,
parentMethodInfo,
lockStack);
break;
// Multidimensional array of references.
case Constants.MULTIANEWARRAY:
logInfo("MULTIANEWARRAY, stack size: " + stack.size());
index = bytes.readShort();
int dimensions = bytes.readByte();
stack.pop(dimensions);
stack.push(new ArrayType(Type.UNKNOWN, dimensions));
break;
// NEW - Create new object
// Stack: ... -> ..., objectref
case Constants.NEW:
logInfo("NEW, stack size: " + stack.size());
// get name of Java class
index = bytes.readShort();
ConstantClass cc = (ConstantClass)constant_pool.getConstant(index);
ConstantUtf8 c = (ConstantUtf8)constant_pool.getConstant(cc.getNameIndex());
String rawClassName = c.getBytes();
String fullClassName = Utility.compactClassName(rawClassName, false);
logInfo("NEW, stack size " + stack.size() + " " + index + " " + fullClassName);
// push reference to stack
ObjectType type = new ObjectType(fullClassName);
stack.push(type);
break;
// NEWARRAY - Create new array of basic type (int, short, ...)
// Stack: ..., count -> ..., arrayref
// type must be one of T_INT, T_SHORT, ...
case Constants.NEWARRAY:
logInfo("NEWARRAY");
index = bytes.readByte();
stack.pop();
t = new ArrayType(ObjectType.UNKNOWN,1);
stack.push(t);
break;
case Constants.NOP:
break;
// POP - Pop top operand stack word
// Stack: ..., word -> ...
case Constants.POP:
logInfo("POP, stack size: " + stack.size());
stack.pop();
break;
// POP2 - Pop two top operand stack words
// Stack: ..., word2, word1 -> ...
case Constants.POP2:
logInfo("POP2, stack size: " + stack.size());
try {
t = stack.peek();
// cat2
if (t == ObjectType.LONG || t == ObjectType.DOUBLE) {
stack.pop(1);
// cat1
} else {
stack.pop(2);
}
} catch (Exception e) {
logInfo("ERROR, POP2");
}
break;
// RET - Return from subroutine
// Stack: ... -> ...
case Constants.RET:
logInfo("RET, stack size: " + stack.size());
vindex = ProcessInstruction_Util.getVariableIndex(wide, bytes);
wide = false; // clear flag
break;
// RETURN - Return from void method
// Stack: ... -> <empty>
case Constants.RETURN:
logInfo("RETURN, stack size: " + stack.size());
stack.pop(stack.size());
break;
// SALOAD - Load short from array
// Stack: ..., arrayref, index -> ..., value
case Constants.SALOAD:
logInfo("SALOAD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
// SASTORE - Store into short array
// Stack: ..., arrayref, index, value -> ...
case Constants.SASTORE:
logInfo("SASTORE, stack size: " + stack.size());
stack.pop(3);
break;
// SIPUSH - Push short
// Stack: ... -> ..., value
case Constants.SIPUSH:
logInfo("SIPUSH, stack size: " + stack.size());
bytes.readByte();
bytes.readByte();
stack.push(ObjectType.INT);
break;
// SWAP - Swa top operand stack word
// Stack: ..., word2, word1 -> ..., word1, word2
case Constants.SWAP:
logInfo("SWAP, stack size: " + stack.size());
// noop
break;
// Remember wide byte which is used to form a 16-bit address in the
// following instruction. Relies on that the method is called again with
// the following opcode.
case Constants.WIDE:
logInfo("WIDE");
wide = true;
break;
// handled in helper method
case Constants.PUTSTATIC:
case Constants.PUTFIELD:
case Constants.GETSTATIC:
case Constants.GETFIELD:
ProcessInstruction_SetGetField.processField(
opcode,
stack,
constant_pool,bytes,
jClass,
parentMethodInfo,
invokedLineNumber,
lockStack.isSynchronized(),
handlerList);
break;
// INVOKESPECIAL - Invoke instance method; special handling for
// superclass, private and instance initialization method invocations
// Stack: ..., objectref, [arg1, [arg2 ...]] -> ...
case Constants.INVOKESPECIAL:
logInfo("(INVOKESPECIAL)");
case Constants.INVOKESTATIC:
logInfo("(INVOKESTATIC)");
case Constants.INVOKEVIRTUAL:
logInfo("(INVOKEVIRTUAL)");
case Constants.INVOKEINTERFACE:
logInfo("(INVOKEINTERFACE)");
logInfo("INVOKE, stack size: " + stack.size() + " lock stack size: " + lockStack.debugGetSize());
ProcessInstruction_MethodInvoke.processMethodInvoke(stack,
constant_pool,
jClass,
handlerList,
hashMapSynthetic,
opcode, bytes,
invokedLineNumber,
parentMethodInfo,
lockStack);
break;
default:
logInfo("DEFAULT: " + opcode);
if(true)
throw new Exception("Missing DEFAULT: " + opcode);
if (Constants.NO_OF_OPERANDS[opcode] > 0) {
for (int i = 0; i < Constants.TYPE_OF_OPERANDS[opcode].length; i++) {
switch (Constants.TYPE_OF_OPERANDS[opcode][i]) {
case Constants.T_BYTE:
break;
case Constants.T_SHORT: // Either branch or index
break;
case Constants.T_INT:
break;
default: // Never reached
System.err.println("Unreachable default case reached!");
}
}
}
}
}
| static void processInstruction(
short opcode,
HashMap<Integer,Boolean> visitedByteOffsets,
Queue<BranchState> branchQueue,
BranchState currBranch,
HashMap<Integer,Type> runtimeVariableTable,
JavaClass jClass,
ArrayList<IClassFileParseHandler> handlerList,
HashMap<String,java.lang.reflect.AccessibleObject> hashMapSynthetic,
Method parentMethod,
java.lang.reflect.AccessibleObject parentMethodR,
ByteReader bytes,
IMethodInfo parentMethodInfo)
throws Exception {
ConstantPool constant_pool = jClass.getConstantPool();
Code code = parentMethod.getCode();
boolean parentIsSynthetic = parentMethod.isSynthetic();
LineNumberTable lineTable = code.getLineNumberTable();
OperandStack stack = currBranch.getStack();
LockStack lockStack = currBranch.getLockInfo();
//ByteReader bytes = new ByteReader(code.getCode());
//bytes.mark(bytes.available());
//bytes.reset();
//bytes.skipBytes(currBranch.getIndex());
int currOffset = bytes.getIndex();
//ToDo: get this from BCEL
boolean isStaticBlock = parentMethod.getName().equals(ByteCodeConstants.STATICBLOCK_IDENTIFIER);
//logInfo("opcode: " + opcode + " ALOAD_1: " + Constants.ALOAD_1);
String name, signature;
String className = null;
int default_offset = 0, low, high;
int index, class_index, vindex, constant;
int[] jump_table;
int no_pad_bytes = 0, offset;
Type t;
BranchState branchState;
// varTable may be null in some situations
LocalVariableTable varTable = code.getLocalVariableTable();
int line_number_ind = bytes.getIndex();
int invokedLineNumber;
if (lineTable != null) {
invokedLineNumber = lineTable.getSourceLine(line_number_ind);
} else {
invokedLineNumber = org.checkthread.main.Constants.NO_LINE_NUMBER;
}
Log.logByteInfo("Byte Offset: " + bytes.getIndex() + " Stack size: " + stack.size());
/*
* Special case: Skip (0-3) padding bytes, i.e., the following bytes are
* 4-byte-aligned
*/
if ((opcode == Constants.TABLESWITCH)
|| (opcode == Constants.LOOKUPSWITCH)) {
int remainder = bytes.getIndex() % 4;
no_pad_bytes = (remainder == 0) ? 0 : 4 - remainder;
for (int i = 0; i < no_pad_bytes; i++) {
bytes.readByte();
}
// Both cases have a field default_offset in common
default_offset = bytes.readInt();
}
switch (opcode) {
// TABLESWITCH - Switch within given range of values, i.e., low..high
case Constants.TABLESWITCH:
logInfo("TABLESWITCH");
stack.pop();
low = bytes.readInt();
high = bytes.readInt();
offset = bytes.getIndex() - 12 - no_pad_bytes - 1;
default_offset += offset;
// Print switch indices in first row (and default)
jump_table = new int[high - low + 1];
for (int i = 0; i < jump_table.length; i++) {
jump_table[i] = offset + bytes.readInt();
}
break;
// AALOAD - Load reference from array
// Stack: ..., arrayref, index -> value
case Constants.AALOAD:
logInfo("AALOAD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.NULL);
break;
// AASTORE - Store into reference array
// Stack: ..., arrayref, index, value -> ...
case Constants.AASTORE:
logInfo("AASTORE, stack size: " + stack.size());
stack.pop(3);
break;
// ACONST_NULL - Push null reference
// Stack: ... -> ..., null
case Constants.ACONST_NULL:
logInfo("ACONST_NULL, stack size: " + stack.size());
stack.push(ObjectType.NULL);
break;
// ALOAD - Load reference from local variable
// Stack: ... -> ..., objectref
case Constants.ALOAD_0:
wide = ProcessInstruction_Util.processALOAD(0,stack, wide, bytes, varTable, runtimeVariableTable);
break;
case Constants.ALOAD_1:
wide = ProcessInstruction_Util.processALOAD(1,stack, wide, bytes, varTable, runtimeVariableTable);
break;
case Constants.ALOAD_2:
wide = ProcessInstruction_Util.processALOAD(2,stack, wide, bytes, varTable, runtimeVariableTable);
break;
case Constants.ALOAD_3:
wide = ProcessInstruction_Util.processALOAD(3,stack, wide, bytes, varTable, runtimeVariableTable);
break;
case Constants.ALOAD:
wide = ProcessInstruction_Util.processALOADn(stack, wide, bytes, varTable, runtimeVariableTable);
break;
// ANEWARRAY - Create new array of references
// Stack: ..., count -> ..., arrayref
case Constants.ANEWARRAY: {
logInfo("ANEWARRAY, stack size: " + stack.size());
bytes.readShort();
stack.pop();
t = new ArrayType(ObjectType.NULL,1);
stack.push(t);
break;
}
// ARETURN - Return reference from method
// Stack: ..., objectref -> <empty>
case Constants.ARETURN:
logInfo("ARETURN, stack size: " + stack.size());
stack.pop(stack.size());
break;
// ARRAYLENGTH - Get length of array
// Stack: ..., arrayref -> ..., length
case Constants.ARRAYLENGTH:
logInfo("ARRAYLENGTH, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.INT);
break;
// ASTORE - Store reference into local variable
// Stack ..., objectref -> ...
case Constants.ASTORE_0:
wide = ProcessInstruction_Util.processASTORE(0,stack, wide, bytes, runtimeVariableTable);
break;
case Constants.ASTORE_1:
wide = ProcessInstruction_Util.processASTORE(1,stack, wide, bytes, runtimeVariableTable);
break;
case Constants.ASTORE_2:
wide = ProcessInstruction_Util.processASTORE(2,stack, wide, bytes, runtimeVariableTable);
break;
case Constants.ASTORE_3:
wide = ProcessInstruction_Util.processASTORE(3,stack, wide, bytes, runtimeVariableTable);
break;
case Constants.ASTORE:
wide = ProcessInstruction_Util.processASTOREn(stack, wide, bytes, runtimeVariableTable);
break;
// ATHROW - Throw exception
// Stack: ..., objectref -> objectref
case Constants.ATHROW:
logInfo("ATHROW, stack size: " + stack.size());
stack.pop(stack.size());
//stack.push(ObjectType.NULL);
break;
// BALOAD - Load byte or boolean from array
// Stack: ..., arrayref, index -> ..., value
case Constants.BALOAD:
logInfo("BALOAD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
// BASTORE - Store into byte or boolean array
// Stack: ..., arrayref, index, value -> ...
case Constants.BASTORE:
logInfo("BASTORE, stack size: " + stack.size());
stack.pop(3);
break;
// BIPUSH - Push byte on stack
// Stack: ... -> ..., value
case Constants.BIPUSH:
logInfo("BIPUSH, stack size: " + stack.size());
bytes.readByte();
stack.push(ObjectType.INT);
break;
// CALOAD - Load char from array
// Stack: ..., arrayref, index -> ..., value
case Constants.CALOAD:
logInfo("CALOAD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
// CASTORE - Store into char array
// Stack: ..., arrayref, index, value -> ...
case Constants.CASTORE:
logInfo("CASTORE, stack size: " + stack.size());
stack.pop(3);
break;
// CHECKCAST - Check whether object is of given type
// Stack: ..., objectref -> ..., objectref
case Constants.CHECKCAST:
logInfo("CHECKCAST, stack size: " + stack.size());
index = bytes.readShort();
break;
// D2F - Convert double to float
// Stack: ..., value.word1, value.word2 -> ..., result
case Constants.D2F:
logInfo("D2F, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.FLOAT);
break;
// D2I - Convert double to int
// Stack: ..., value.word1, value.word2 -> ..., result
case Constants.D2I:
logInfo("D2I, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.INT);
break;
// D2L - Convert double to long
// Stack: ..., value.word1, value.word2 -> ..., result.word1, result.word2
case Constants.D2L:
logInfo("D2L, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.LONG);
break;
// DADD - Add doubles
// Stack: ..., value1.word1, value1.word2, value2.word1, value2.word2 ->
// ..., result.word1, result1.word2
case Constants.DADD:
logInfo("DADD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.DOUBLE);
break;
// DALOAD - Load double from array
// Stack: ..., arrayref, index -> ..., result.word1, result.word2
case Constants.DALOAD:
logInfo("DALOAD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.DOUBLE);
break;
// DASTORE - Store into double array
// Stack: ..., arrayref, index, value.word1, value.word2 -> ...
case Constants.DASTORE:
logInfo("DASTORE, stack size: " + stack.size());
stack.pop(3);
break;
// DCMPG - Compare doubles: value1 > value2
// Stack: ..., value1.word1, value1.word2, value2.word1, value2.word2 ->
// ..., result
case Constants.DCMPG:
logInfo("DCMPG, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
case Constants.DCMPL:
logInfo("DCMPL, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
// DCONST - Push 0.0 or 1.0, other values cause an exception
// Stack: ... -> ...,
case Constants.DCONST_0:
logInfo("DCONST_0, stack size: " + stack.size());
stack.push(ObjectType.DOUBLE);
break;
case Constants.DCONST_1:
logInfo("DCONST_1, stack size: " + stack.size());
stack.push(ObjectType.DOUBLE);
break;
// ..., value1, value2 ..., result
case Constants.DDIV:
logInfo("DDIV, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.DOUBLE);
break;
// DLOAD - Load double from local variable
// Stack ... -> ..., result.word1, result.word2
case Constants.DLOAD_0:
wide = ProcessInstruction_Util.processDLOAD(0, stack, wide, bytes, varTable);
break;
case Constants.DLOAD_1:
wide = ProcessInstruction_Util.processDLOAD(1, stack, wide, bytes, varTable);
break;
case Constants.DLOAD_2:
wide = ProcessInstruction_Util.processDLOAD(2, stack, wide, bytes, varTable);
break;
case Constants.DLOAD_3:
wide = ProcessInstruction_Util.processDLOAD(3, stack, wide, bytes, varTable);
break;
case Constants.DLOAD:
wide = ProcessInstruction_Util.processDLOADn(stack, wide, bytes, varTable);
break;
// ..., value1, value2 ..., result
case Constants.DMUL:
logInfo("DMUL, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.DOUBLE);
break;
// ..., value ..., result
case Constants.DNEG:
logInfo("DNEG, stack size: " + stack.size());
stack.pop(1);
stack.push(ObjectType.DOUBLE);
break;
// ..., value1, value2 ..., result
case Constants.DREM:
logInfo("DREM, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.DOUBLE);
break;
// ..., value [empty]
case Constants.DRETURN:
logInfo("DRETURN, stack size: " + stack.size());
stack.pop(stack.size());
break;
// DSTORE - Store double into local variable
// Stack: ..., value.word1, value.word2 -> ...
case Constants.DSTORE_0:
wide = ProcessInstruction_Util.processDSTORE(0, stack, wide, bytes);
break;
case Constants.DSTORE_1:
wide = ProcessInstruction_Util.processDSTORE(1, stack, wide, bytes);
break;
case Constants.DSTORE_2:
wide = ProcessInstruction_Util.processDSTORE(2, stack, wide, bytes);
break;
case Constants.DSTORE_3:
wide = ProcessInstruction_Util.processDSTORE(3, stack, wide, bytes);
break;
case Constants.DSTORE:
wide = ProcessInstruction_Util.processDSTOREn(stack, wide, bytes);
break;
// ..., value1, value2 ..., result
case Constants.DSUB:
logInfo("DSUB, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.DOUBLE);
break;
// DUP - Duplicate top operand stack word
// Stack: ..., word -> ..., word, word
case Constants.DUP: {
logInfo("DUP, stack size: " + stack.size());
if(stack.size()>=stack.maxStack()) {
Log.severe("Stack filled up: " + parentMethodInfo.getFullUniqueMethodName());
}
stack.push(stack.peek());
break;
}
// ..., value2, value1 ..., value1, value2, value1
case Constants.DUP_X1:
logInfo("DUP_X1, stack size: " + stack.size());
stack.push(stack.peek());
break;
// Form 1:
// ..., value3, value2, value1 ..., value1, value3, value2, value1
// where value1, value2, and value3 are all values of a category 1 computational type.
//
// Form 2:
// ..., value2, value1 ..., value1, value2, value1
// where value1 is a value of a category 1 computational type and value2 is a value of a category 2 computational type.
case Constants.DUP_X2:
logInfo("DUP_X2, stack size: " + stack.size());
t = stack.peek();
// category 2
if(t == ObjectType.DOUBLE || t == ObjectType.LONG) {
stack.push(stack.peek());
// category 1
} else {
stack.push(stack.peek());
}
// Form 1:
// ..., value2, value1 ..., value2, value1, value2, value1
// where both value1 and value2 are values of a category 1 computational type.
// Form 2:
// ..., value ..., value, value
// where value is a value of a category 2 computational type
case Constants.DUP2:
logInfo("DUP2, stack size: " + stack.size());
t = stack.peek();
// category 2
if(t == ObjectType.DOUBLE || t == ObjectType.LONG) {
stack.push(stack.peek(2));
stack.push(stack.peek(3));
// category 1
} else {
stack.push(stack.peek());
}
break;
// Form 1:
// ..., value3, value2, value1 ..., value2, value1, value3, value2, value1
// where value1, value2, and value3 are all values of a category 1 computational type.
// Form 2:
// ..., value2, value1 ..., value1, value2, value1
// where value1 is a value of a category 2 computational type and value2 is a value of a category 1 computational type.
case Constants.DUP2_X1:
logInfo("DUP2_X1, stack size: " + stack.size());
t = stack.peek();
// category 2
if(t == ObjectType.DOUBLE || t == ObjectType.LONG) {
stack.push(stack.peek());
// category 1
} else {
stack.push(stack.peek());
stack.push(stack.peek());
}
break;
// DUP_X2 - Duplicate top operand stack word and put three down
// Stack: ..., word3, word2, word1 -> ..., word1, word3, word2, word1
case Constants.DUP2_X2:
logInfo("DUP2_X2, stack size: " + stack.size());
stack.push(stack.peek());
break;
// Float operations
case Constants.F2D:
logInfo("F2D, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.DOUBLE);
break;
case Constants.F2I:
logInfo("F2I, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.INT);
break;
case Constants.F2L:
logInfo("F2L, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.LONG);
break;
case Constants.FADD:
logInfo("FADD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.FLOAT);
break;
case Constants.FALOAD:
logInfo("FALOAD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.FLOAT);
break;
case Constants.FASTORE:
logInfo("FASTORE, stack size: " + stack.size());
stack.pop(3);
break;
case Constants.FCMPG:
logInfo("FCMPG, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
case Constants.FCMPL:
logInfo("FCMPL, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
case Constants.FCONST_0:
logInfo("FCONST_0, stack size: " + stack.size());
stack.push(ObjectType.FLOAT);
break;
case Constants.FCONST_1:
logInfo("FCONST_1, stack size: " + stack.size());
stack.push(ObjectType.FLOAT);
break;
case Constants.FDIV:
logInfo("FDIV, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.FLOAT);
break;
// FLOAD - Load float from local variable
// Stack ... -> ..., result
case Constants.FLOAD_0:
wide = ProcessInstruction_Util.processFLOAD(0,stack, wide, bytes, varTable);
break;
case Constants.FLOAD_1:
wide = ProcessInstruction_Util.processFLOAD(1,stack, wide, bytes, varTable);
break;
case Constants.FLOAD_2:
wide = ProcessInstruction_Util.processFLOAD(2,stack, wide, bytes, varTable);
break;
case Constants.FLOAD_3:
wide = ProcessInstruction_Util.processFLOAD(3,stack, wide, bytes, varTable);
break;
case Constants.FLOAD:
wide = ProcessInstruction_Util.processFLOADn(stack, wide, bytes, varTable);
break;
// FMUL - Multiply floats
// Stack: ..., value1, value2 -> result
case Constants.FMUL:
logInfo("FMUL, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.FLOAT);
break;
// ..., value1, value2 ..., result
case Constants.FREM:
logInfo("FREM, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.FLOAT);
break;
// ..., value [empty]
case Constants.FRETURN:
logInfo("FRETURN, stack size: " + stack.size());
stack.pop(stack.size());
break;
// FSTORE - Store float into local variable
// Stack: ..., value -> ...
case Constants.FSTORE_0:
wide = ProcessInstruction_Util.processFSTORE(0, stack, wide, bytes);
break;
case Constants.FSTORE_1:
wide = ProcessInstruction_Util.processFSTORE(1, stack, wide, bytes);
break;
case Constants.FSTORE_2:
wide = ProcessInstruction_Util.processFSTORE(2, stack, wide, bytes);
break;
case Constants.FSTORE_3:
wide = ProcessInstruction_Util.processFSTORE(3, stack, wide, bytes);
break;
case Constants.FSTORE:
wide = ProcessInstruction_Util.processFSTOREn(stack, wide, bytes);
break;
// FSUB - Substract floats
// Stack: ..., value1, value2 -> result
case Constants.FSUB:
logInfo("FSUB, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.FLOAT);
// GOTO - Branch always (to relative offset, not absolute address)
case Constants.GOTO:
index = ProcessInstruction_Util.getIndexShortIcecream(bytes);
logInfo("GOTO, stack size: " + stack.size() + " offset: " + index);
// GoTo, skip opcodes
bytes.skipBytes(index-bytes.getIndex());
break;
// GOTO_W - Branch always (to relative offset, not absolute address)
case Constants.GOTO_W:
logInfo("GOTO_W, stack size: " + stack.size());
int windex = ProcessInstruction_Util.getIndexIntIcecream(bytes);
logInfo("GOTO_W, stack size: " + stack.size() + " offset: " + windex);
// GoTo, skip opcodes
bytes.skipBytes(windex-bytes.getIndex());
break;
// I2B - Convert int to byte
// Stack: ..., value -> ..., result
case Constants.I2B:
logInfo("I2B, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.INT);
break;
case Constants.I2C:
logInfo("I2C, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.INT);
break;
case Constants.I2D:
logInfo("I2D, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.DOUBLE);
break;
case Constants.I2F:
logInfo("I2F, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.FLOAT);
break;
case Constants.I2L:
logInfo("I2L, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.LONG);
break;
case Constants.I2S:
logInfo("I2S, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.INT);
break;
case Constants.IADD:
logInfo("IADD, stack size: " + stack.size());
{
Type t1 = stack.pop();
Type t2 = stack.pop();
Type retType = null;
if (t2 instanceof FieldReferenceType) {
//ToDo: Propogate field reference
stack.push(ObjectType.INT);
} else {
stack.push(ObjectType.INT);
}
}
break;
//Stack: ..., arrayref, index -> ..., value
case Constants.IALOAD:
logInfo("IALOAD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
//Stack: ..., value1, value2 -> ..., result
case Constants.IAND:
logInfo("IAND, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
//Stack: ..., arrayref, index, value -> ...
case Constants.IASTORE:
logInfo("IASTORE, stack size: " + stack.size());
stack.pop(3);
break;
// ICONST - Push value between -1, ..., 5, other values
// cause an exception
// Stack: ... -> ...,
case Constants.ICONST_0:
case Constants.ICONST_1:
case Constants.ICONST_2:
case Constants.ICONST_3:
case Constants.ICONST_4:
case Constants.ICONST_5:
case Constants.ICONST_M1:
logInfo("ICONST {0,1,2,3,4,5}, stack size" + stack.size());
stack.push(ObjectType.INT);
break;
//Stack: ..., value1, value2 -> result
case Constants.IDIV:
logInfo("IDIV, stack size" + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
// IF_ACMPEQ - Branch if reference comparison succeeds
// Stack: ..., value1, value2 -> ...
case Constants.IF_ACMPEQ:
// IF_ACMPNE - Branch if reference comparison doesn't succeed
// Stack: ..., value1, value2 -> ...
case Constants.IF_ACMPNE:
// IF_ICMPEQ - Branch if int comparison succeeds
// Stack: ..., value1, value2 -> ...
case Constants.IF_ICMPEQ:
case Constants.IF_ICMPGE:
case Constants.IF_ICMPGT:
case Constants.IF_ICMPLE:
case Constants.IF_ICMPLT:
// IF_ICMPNE - Branch if int comparison doesn't succeed
// Stack: ..., value1, value2 -> ...
case Constants.IF_ICMPNE:
logInfo("IF<>, stack size: " + stack.size());
stack.pop(2);
index = ProcessInstruction_Util.getIndexShortIcecream(bytes);
logInfo("IF: " + stack.size() + " " + index);
branchState = new BranchState(stack.getClone(),
lockStack.getClone(),
index);
branchQueue.add(branchState);
break;
// IFEQ - Branch if int comparison with zero succeeds
// Stack: ..., value -> ...
case Constants.IFEQ:
case Constants.IFGE:
case Constants.IFGT:
case Constants.IFLE:
case Constants.IFLT:
case Constants.IFNE:
// IFNONNULL - Branch if reference is not null
// Stack: ..., reference -> ...
case Constants.IFNONNULL:
case Constants.IFNULL:
logInfo("IF<>, stack size: " + stack.size());
if(stack.size()==0) {
Log.logByteInfo("ERROR: Attempting to pop empty stack");
Log.logByteInfo(parentMethodInfo.getFullUniqueMethodName());
} else {
stack.pop();
}
index = ProcessInstruction_Util.getIndexShortIcecream(bytes);
logInfo("IF: " + stack.size() + " " + index);
branchState = new BranchState(stack.getClone(),
lockStack.getClone(),
index);
branchQueue.add(branchState);
break;
// IINC - Increment local variable by constant
case Constants.IINC:
logInfo("IINC");
if (wide) {
vindex = bytes.readShort();
constant = bytes.readShort();
wide = false;
} else {
vindex = bytes.readUnsignedByte();
constant = bytes.readByte();
}
break;
// ILOAD - Load int from local variable onto stack
// Stack: ... -> ..., result
case Constants.ILOAD_0:
wide = ProcessInstruction_Util.processILOAD(parentMethodInfo,0,stack, wide, bytes, varTable);
break;
case Constants.ILOAD_1:
wide = ProcessInstruction_Util.processILOAD(parentMethodInfo,1,stack, wide, bytes, varTable);
break;
case Constants.ILOAD_2:
wide = ProcessInstruction_Util.processILOAD(parentMethodInfo,2,stack, wide, bytes, varTable);
break;
case Constants.ILOAD_3:
wide = ProcessInstruction_Util.processILOAD(parentMethodInfo,3,stack, wide, bytes, varTable);
break;
case Constants.ILOAD:
wide = ProcessInstruction_Util.processILOADn(parentMethodInfo,stack, wide, bytes, varTable);
break;
// Stack: ..., value1, value2 -> result
case Constants.IMUL:
logInfo("IMUL, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
// Stack: ..., value -> ..., result
case Constants.INEG:
logInfo("INEG, stack size: " + stack.size());
stack.pop(1);
stack.push(ObjectType.INT);
break;
// INSTANCEOF - Determine if object is of given type
// Stack: ..., objectref -> ..., result
case Constants.INSTANCEOF:
logInfo("INSTANCEOF, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.INT);
index = bytes.readShort();
break;
//Stack: ..., value1, value2 -> ..., result
case Constants.IOR:
case Constants.IREM:
case Constants.ISHL:
case Constants.ISHR:
logInfo("IOR, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
//Stack: ..., value -> <empty>
case Constants.IRETURN:
logInfo("IRETURN, stack size: " + stack.size());
stack.pop(stack.size());
break;
// ISTORE - Store int from stack into local variable
// Stack: ..., value -> ...
case Constants.ISTORE_0:
wide = ProcessInstruction_Util.processISTORE(0, stack, wide, bytes);
break;
case Constants.ISTORE_1:
wide = ProcessInstruction_Util.processISTORE(1, stack, wide, bytes);
break;
case Constants.ISTORE_2:
wide = ProcessInstruction_Util.processISTORE(2, stack, wide, bytes);
break;
case Constants.ISTORE_3:
wide = ProcessInstruction_Util.processISTORE(3, stack, wide, bytes);
break;
case Constants.ISTORE:
wide = ProcessInstruction_Util.processISTOREn(stack, wide, bytes);
break;
//Stack: ..., value1, value2 -> result
case Constants.ISUB:
logInfo("ISUB, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
//Stack: ..., value1, value2 -> ..., result
case Constants.IUSHR:
logInfo("IUSHR, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
//Stack: ..., value1, value2 -> ..., result
case Constants.IXOR:
logInfo("IXOR, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
case Constants.JSR:
index = ProcessInstruction_Util.getIndexShortIcecream(bytes);
logInfo("JSR, stack size: " + stack.size() + " " + index);
stack.push(ReturnaddressType.NO_TARGET);
break;
case Constants.JSR_W:
windex = ProcessInstruction_Util.getIndexIntIcecream(bytes);
logInfo("JSRW, stack size: " + stack.size() + " " + windex);
stack.push(ReturnaddressType.NO_TARGET);
break;
// L2D - Convert long to double
// Stack: ..., value.word1, value.word2 -> ..., result.word1, result.word2
case Constants.L2D:
logInfo("L2D, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.DOUBLE);
break;
// L2F - Convert long to float
// Stack: ..., value.word1, value.word2 -> ..., result
case Constants.L2F:
logInfo("L2F, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.FLOAT);
break;
// L2I - Convert long to int
// Stack: ..., value.word1, value.word2 -> ..., result
case Constants.L2I:
logInfo("L2I, stack size: " + stack.size());
stack.pop();
stack.push(ObjectType.INT);
break;
//..., value1, value2 ..., result
case Constants.LADD:
logInfo("LADD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
//..., arrayref, index ..., value
case Constants.LALOAD:
logInfo("LALOAD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
// ..., value1, value2 ..., result
case Constants.LAND:
logInfo("LAND, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
// ..., arrayref, index, value ...
case Constants.LASTORE:
logInfo("LASTORE, stack size: " + stack.size());
stack.pop(3);
break;
// ..., value1, value2 ..., result
case Constants.LCMP:
logInfo("LCMP, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
case Constants.LCONST_0:
case Constants.LCONST_1:
logInfo("LCONST_<0,1>, stack size: " + stack.size());
stack.push(ObjectType.LONG);
break;
// LDC - Push item from constant pool.
// Stack: ... -> ..., item
case Constants.LDC:
vindex = bytes.readUnsignedByte();
logInfo("LDC, stack size: " + stack.size());
if(stack.size()>=stack.maxStack()) {
Log.logByteInfo("Attempting to push stack size beyond limit");
Log.logByteInfo(parentMethodInfo.getFullUniqueMethodName());
}
stack.push(Type.UNKNOWN); //int, float, or long
break;
// LDC_W - Push item from constant pool (wide index)
// Stack: ... -> ..., item.word1, item.word2
case Constants.LDC_W:
vindex = bytes.readShort();
logInfo("LDC_W, stack size: " + stack.size());
stack.push(Type.UNKNOWN); //int, float, or long
break;
// LDC2_W - Push long or double from constant pool
// Stack: ... -> ..., item.word1, item.word2
case Constants.LDC2_W:
vindex = bytes.readShort();
logInfo("LDC2_W, stack size: " + stack.size());
stack.push(Type.UNKNOWN); //long or double
break;
//..., value1, value2 ..., result
case Constants.LDIV:
logInfo("LDIV, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
// LLOAD - Load long from local variable
// Stack ... -> ..., result.word1, result.word
case Constants.LLOAD_0:
wide = ProcessInstruction_Util.processLLOAD(0,stack, wide, bytes, varTable);
break;
case Constants.LLOAD_1:
wide = ProcessInstruction_Util.processLLOAD(1,stack, wide, bytes, varTable);
break;
case Constants.LLOAD_2:
wide = ProcessInstruction_Util.processLLOAD(2,stack, wide, bytes, varTable);
break;
case Constants.LLOAD_3:
wide = ProcessInstruction_Util.processLLOAD(3,stack, wide, bytes, varTable);
break;
case Constants.LLOAD:
wide = ProcessInstruction_Util.processLLOADn(stack, wide, bytes, varTable);
break;
//..., value1, value2 ..., result
case Constants.LMUL:
logInfo("LMUL, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
case Constants.LNEG:
logInfo("LNEG, stack size: " + stack.size());
stack.pop(1);
stack.push(ObjectType.LONG);
break;
// LOOKUPSWITCH - Switch with unordered set of values
case Constants.LOOKUPSWITCH:
logInfo("LOOKUPSWITCH");
stack.pop();
int npairs = bytes.readInt();
offset = bytes.getIndex() - 8 - no_pad_bytes - 1;
jump_table = new int[npairs];
default_offset += offset;
// Print switch indices in first row (and default)
for (int i = 0; i < npairs; i++) {
int match = bytes.readInt();
jump_table[i] = offset + bytes.readInt();
}
break;
// ..., value1, value2 ..., result
case Constants.LOR:
logInfo("LOR, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
//..., value1, value2 ..., result
case Constants.LREM:
logInfo("LREM, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
//..., value [empty]
case Constants.LRETURN:
logInfo("LRETURN, stack size: " + stack.size());
stack.pop(stack.size());
break;
//..., value1, value2 ..., result
case Constants.LSHL:
logInfo("LSHL, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
//..., value1, value2 ..., result
case Constants.LSHR:
logInfo("LSHR, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
// LSTORE - Store long into local variable
// Stack: ..., value.word1, value.word2 -> ...
case Constants.LSTORE_0:
wide = ProcessInstruction_Util.processLSTORE(0, stack, wide, bytes);
break;
case Constants.LSTORE_1:
wide = ProcessInstruction_Util.processLSTORE(1, stack, wide, bytes);
break;
case Constants.LSTORE_2:
wide = ProcessInstruction_Util.processLSTORE(2, stack, wide, bytes);
break;
case Constants.LSTORE_3:
wide = ProcessInstruction_Util.processLSTORE(3, stack, wide, bytes);
break;
case Constants.LSTORE:
wide = ProcessInstruction_Util.processLSTOREn(stack, wide, bytes);
break;
//..., value1, value2 ..., result
case Constants.LSUB:
logInfo("LSUB, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
case Constants.LUSHR:
logInfo("LUSHR, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
case Constants.LXOR:
logInfo("LXOR, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.LONG);
break;
// MONITORENTER - Enter monitor for object
// Stack: ..., objectref -> ...
case Constants.MONITORENTER:
logLocking("MONITORENTER, stack size: " + stack.size());
ProcessInstruction_Lock.processMonitorEnter(stack,
handlerList,
parentMethodInfo,
lockStack,
invokedLineNumber);
break;
// MONITOREXIT - Exit monitor for object
// Stack: ..., objectref -> ...
case Constants.MONITOREXIT:
logLocking("MONITOREXIT, stack size: " + stack.size());
ProcessInstruction_Lock.processMonitorExit(stack,
handlerList,
parentMethodInfo,
lockStack);
break;
// Multidimensional array of references.
case Constants.MULTIANEWARRAY:
logInfo("MULTIANEWARRAY, stack size: " + stack.size());
index = bytes.readShort();
int dimensions = bytes.readByte();
stack.pop(dimensions);
stack.push(new ArrayType(Type.UNKNOWN, dimensions));
break;
// NEW - Create new object
// Stack: ... -> ..., objectref
case Constants.NEW:
logInfo("NEW, stack size: " + stack.size());
// get name of Java class
index = bytes.readShort();
ConstantClass cc = (ConstantClass)constant_pool.getConstant(index);
ConstantUtf8 c = (ConstantUtf8)constant_pool.getConstant(cc.getNameIndex());
String rawClassName = c.getBytes();
String fullClassName = Utility.compactClassName(rawClassName, false);
logInfo("NEW, stack size " + stack.size() + " " + index + " " + fullClassName);
// push reference to stack
ObjectType type = new ObjectType(fullClassName);
stack.push(type);
break;
// NEWARRAY - Create new array of basic type (int, short, ...)
// Stack: ..., count -> ..., arrayref
// type must be one of T_INT, T_SHORT, ...
case Constants.NEWARRAY:
logInfo("NEWARRAY");
index = bytes.readByte();
stack.pop();
t = new ArrayType(ObjectType.UNKNOWN,1);
stack.push(t);
break;
case Constants.NOP:
break;
// POP - Pop top operand stack word
// Stack: ..., word -> ...
case Constants.POP:
logInfo("POP, stack size: " + stack.size());
stack.pop();
break;
// POP2 - Pop two top operand stack words
// Stack: ..., word2, word1 -> ...
case Constants.POP2:
logInfo("POP2, stack size: " + stack.size());
try {
t = stack.peek();
// cat2
if (t == ObjectType.LONG || t == ObjectType.DOUBLE) {
stack.pop(1);
// cat1
} else {
stack.pop(2);
}
} catch (Exception e) {
logInfo("ERROR, POP2");
}
break;
// RET - Return from subroutine
// Stack: ... -> ...
case Constants.RET:
logInfo("RET, stack size: " + stack.size());
vindex = ProcessInstruction_Util.getVariableIndex(wide, bytes);
wide = false; // clear flag
break;
// RETURN - Return from void method
// Stack: ... -> <empty>
case Constants.RETURN:
logInfo("RETURN, stack size: " + stack.size());
stack.pop(stack.size());
break;
// SALOAD - Load short from array
// Stack: ..., arrayref, index -> ..., value
case Constants.SALOAD:
logInfo("SALOAD, stack size: " + stack.size());
stack.pop(2);
stack.push(ObjectType.INT);
break;
// SASTORE - Store into short array
// Stack: ..., arrayref, index, value -> ...
case Constants.SASTORE:
logInfo("SASTORE, stack size: " + stack.size());
stack.pop(3);
break;
// SIPUSH - Push short
// Stack: ... -> ..., value
case Constants.SIPUSH:
logInfo("SIPUSH, stack size: " + stack.size());
bytes.readByte();
bytes.readByte();
stack.push(ObjectType.INT);
break;
// SWAP - Swa top operand stack word
// Stack: ..., word2, word1 -> ..., word1, word2
case Constants.SWAP:
logInfo("SWAP, stack size: " + stack.size());
// noop
break;
// Remember wide byte which is used to form a 16-bit address in the
// following instruction. Relies on that the method is called again with
// the following opcode.
case Constants.WIDE:
logInfo("WIDE");
wide = true;
break;
// handled in helper method
case Constants.PUTSTATIC:
case Constants.PUTFIELD:
case Constants.GETSTATIC:
case Constants.GETFIELD:
ProcessInstruction_SetGetField.processField(
opcode,
stack,
constant_pool,bytes,
jClass,
parentMethodInfo,
invokedLineNumber,
lockStack.isSynchronized(),
handlerList);
break;
// INVOKESPECIAL - Invoke instance method; special handling for
// superclass, private and instance initialization method invocations
// Stack: ..., objectref, [arg1, [arg2 ...]] -> ...
case Constants.INVOKESPECIAL:
logInfo("(INVOKESPECIAL)");
case Constants.INVOKESTATIC:
logInfo("(INVOKESTATIC)");
case Constants.INVOKEVIRTUAL:
logInfo("(INVOKEVIRTUAL)");
case Constants.INVOKEINTERFACE:
logInfo("(INVOKEINTERFACE)");
logInfo("INVOKE, stack size: " + stack.size() + " lock stack size: " + lockStack.debugGetSize());
ProcessInstruction_MethodInvoke.processMethodInvoke(stack,
constant_pool,
jClass,
handlerList,
hashMapSynthetic,
opcode, bytes,
invokedLineNumber,
parentMethodInfo,
lockStack);
break;
default:
logInfo("DEFAULT: " + opcode);
if(true)
throw new Exception("Missing DEFAULT: " + opcode);
if (Constants.NO_OF_OPERANDS[opcode] > 0) {
for (int i = 0; i < Constants.TYPE_OF_OPERANDS[opcode].length; i++) {
switch (Constants.TYPE_OF_OPERANDS[opcode][i]) {
case Constants.T_BYTE:
break;
case Constants.T_SHORT: // Either branch or index
break;
case Constants.T_INT:
break;
default: // Never reached
System.err.println("Unreachable default case reached!");
}
}
}
}
}
|
diff --git a/ee3_common/com/pahimar/ee3/core/handlers/EntityLivingHandler.java b/ee3_common/com/pahimar/ee3/core/handlers/EntityLivingHandler.java
index 3c333750..dce6c0df 100644
--- a/ee3_common/com/pahimar/ee3/core/handlers/EntityLivingHandler.java
+++ b/ee3_common/com/pahimar/ee3/core/handlers/EntityLivingHandler.java
@@ -1,42 +1,42 @@
package com.pahimar.ee3.core.handlers;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.projectile.EntityArrow;
import net.minecraftforge.event.ForgeSubscribe;
import net.minecraftforge.event.entity.living.LivingDeathEvent;
import net.minecraftforge.event.entity.living.LivingEvent.LivingUpdateEvent;
import com.pahimar.ee3.core.helper.ItemDropHelper;
/**
* Equivalent-Exchange-3
*
* EntityLivingHandler
*
* @author pahimar
* @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html)
*
*/
public class EntityLivingHandler {
@ForgeSubscribe
public void onEntityLivingUpdate(LivingUpdateEvent event) {
}
@ForgeSubscribe
public void onEntityLivingDeath(LivingDeathEvent event) {
if (event.source.getDamageType().equals("player")) {
ItemDropHelper.dropMiniumShard((EntityPlayer) event.source.getSourceOfDamage(), event.entityLiving);
}
if (event.source.getSourceOfDamage() instanceof EntityArrow) {
if (((EntityArrow) event.source.getSourceOfDamage()).shootingEntity != null) {
if (((EntityArrow) event.source.getSourceOfDamage()).shootingEntity instanceof EntityPlayer) {
- ItemDropHelper.dropMiniumShard((EntityPlayer) event.source.getSourceOfDamage(), event.entityLiving);
+ ItemDropHelper.dropMiniumShard((EntityPlayer) ((EntityArrow)event.source.getSourceOfDamage()).shootingEntity, event.entityLiving);
}
}
}
}
}
| true | true | public void onEntityLivingDeath(LivingDeathEvent event) {
if (event.source.getDamageType().equals("player")) {
ItemDropHelper.dropMiniumShard((EntityPlayer) event.source.getSourceOfDamage(), event.entityLiving);
}
if (event.source.getSourceOfDamage() instanceof EntityArrow) {
if (((EntityArrow) event.source.getSourceOfDamage()).shootingEntity != null) {
if (((EntityArrow) event.source.getSourceOfDamage()).shootingEntity instanceof EntityPlayer) {
ItemDropHelper.dropMiniumShard((EntityPlayer) event.source.getSourceOfDamage(), event.entityLiving);
}
}
}
}
| public void onEntityLivingDeath(LivingDeathEvent event) {
if (event.source.getDamageType().equals("player")) {
ItemDropHelper.dropMiniumShard((EntityPlayer) event.source.getSourceOfDamage(), event.entityLiving);
}
if (event.source.getSourceOfDamage() instanceof EntityArrow) {
if (((EntityArrow) event.source.getSourceOfDamage()).shootingEntity != null) {
if (((EntityArrow) event.source.getSourceOfDamage()).shootingEntity instanceof EntityPlayer) {
ItemDropHelper.dropMiniumShard((EntityPlayer) ((EntityArrow)event.source.getSourceOfDamage()).shootingEntity, event.entityLiving);
}
}
}
}
|
diff --git a/Temp/src/OR/SimplexProblem.java b/Temp/src/OR/SimplexProblem.java
index db385a0..8e2193f 100644
--- a/Temp/src/OR/SimplexProblem.java
+++ b/Temp/src/OR/SimplexProblem.java
@@ -1,85 +1,85 @@
package OR;
/**
*
*
*/
public class SimplexProblem {
Matrix A;
Double[] C;
Double[] b;
ProblemType Type;
public enum ProblemType {
Max,
Min
}
/**
* a constructor for internal uses only
*/
private SimplexProblem() {
}
public SimplexProblem(ProblemType type,double[][] A,Double[] C , Double[] b) {
// we consider that all conditions are <= .... simple simplex
this.Type = type;
//creating Matrix[m,n+m]; slack for every condition
int m = A.length;
int n = A[0].length ;
Matrix mA = new Matrix(m, n + m);
// filling Matrix A
mA.setMatrix(0,m-1,0,n-1, new Matrix(A));
//extends the matrix by an identity matrix of slacks
mA.setMatrix(0,m-1,n,n+m-1, Matrix.identity(m, m));
this.A = mA;
this.C = new Double[n+m];
for (int i=0;i<n;i++)
this.C[i] = C[i];
for (int i=n;i<n+m;i++)
this.C[i] = new Double(0);
this.b = b;
//Heeeeeeeeeeeeeeeeeeeeeeeeerrreeeeeeeeeeeeee
//table = new SimplexTable(A, C.getArray()[0], b.transpose().getArray()[0], isMax());
}
/**
* method for creating Simplex Problem by Entering the Basic Form
*/
public static SimplexProblem fromBasicFrom() {
return new SimplexProblem();
}
private boolean isMax() {
return (Type == ProblemType.Max) ? true : false;
}
public SolutionList solveByTableSimplex() {
SimplexTable table = new SimplexTable(A, C ,b ,isMax());
SolutionList solution = table.getSolution();
while (!table.isItBestSolution()) {
int solutionType = table.updateTable();
if (solutionType == -2) {
solution = table.getSolution();
}
else if(solutionType == -1) {
break;
}
else {
solution = table.getSolution();
}
}
if(table.isItBestSolution()) {
int ZeroNonBasicNumber = table.getIndexOfNonBasicVariableZero();
for (int i = 0; i < ZeroNonBasicNumber; i++) {
table.updateTable(table.getIndexOfNonBasicVariableZero());
- table.addNewSolution(solution);
+ solution.add(table.getSolution().get(0));
solution.setInfinity();
}
}
return solution;
}
}
| true | true | public SolutionList solveByTableSimplex() {
SimplexTable table = new SimplexTable(A, C ,b ,isMax());
SolutionList solution = table.getSolution();
while (!table.isItBestSolution()) {
int solutionType = table.updateTable();
if (solutionType == -2) {
solution = table.getSolution();
}
else if(solutionType == -1) {
break;
}
else {
solution = table.getSolution();
}
}
if(table.isItBestSolution()) {
int ZeroNonBasicNumber = table.getIndexOfNonBasicVariableZero();
for (int i = 0; i < ZeroNonBasicNumber; i++) {
table.updateTable(table.getIndexOfNonBasicVariableZero());
table.addNewSolution(solution);
solution.setInfinity();
}
}
return solution;
}
| public SolutionList solveByTableSimplex() {
SimplexTable table = new SimplexTable(A, C ,b ,isMax());
SolutionList solution = table.getSolution();
while (!table.isItBestSolution()) {
int solutionType = table.updateTable();
if (solutionType == -2) {
solution = table.getSolution();
}
else if(solutionType == -1) {
break;
}
else {
solution = table.getSolution();
}
}
if(table.isItBestSolution()) {
int ZeroNonBasicNumber = table.getIndexOfNonBasicVariableZero();
for (int i = 0; i < ZeroNonBasicNumber; i++) {
table.updateTable(table.getIndexOfNonBasicVariableZero());
solution.add(table.getSolution().get(0));
solution.setInfinity();
}
}
return solution;
}
|
diff --git a/Project/src/projectrts/model/entities/abilities/MoveAbility.java b/Project/src/projectrts/model/entities/abilities/MoveAbility.java
index 60ad1cf..f1851f3 100644
--- a/Project/src/projectrts/model/entities/abilities/MoveAbility.java
+++ b/Project/src/projectrts/model/entities/abilities/MoveAbility.java
@@ -1,129 +1,130 @@
package projectrts.model.entities.abilities;
import javax.vecmath.Vector2d;
import projectrts.model.constants.P;
import projectrts.model.entities.AbstractAbility;
import projectrts.model.entities.PlayerControlledEntity;
import projectrts.model.pathfinding.AStar;
import projectrts.model.pathfinding.AStarNode;
import projectrts.model.pathfinding.AStarPath;
import projectrts.model.pathfinding.World;
import projectrts.model.utils.ModelUtils;
import projectrts.model.utils.Position;
/**
* An ability for moving
* @author Filip Brynfors, modified by Bjorn Persson Mattsson
*
*/
public class MoveAbility extends AbstractAbility {
private PlayerControlledEntity entity;
private Position targetPosition;
private World world;
private AStar aStar;
private AStarPath path;
private boolean pathRefresh = true;
static {
AbilityFactory.INSTANCE.registerAbility(MoveAbility.class.getSimpleName(), new MoveAbility());
}
/**
* When subclassing, invoke this to initialize the ability.
*/
protected void initialize() {
this.aStar = AStar.getInstance();
this.world = World.getInstance();
}
@Override
public String getName() {
return "Move";
}
@Override
public void useAbility(PlayerControlledEntity entity, Position pos){
this.entity = entity;
this.targetPosition = pos;
// Want to refresh path as soon as a click is made
this.pathRefresh = true;
setActive(true);
setFinished(false);
}
@Override
public void update(float tpf) {
if(isActive() && !isFinished()){
entity.setPosition(determineNextStep(tpf, entity, targetPosition));
if (path.nrOfNodesLeft() == 0)
{
setFinished(true);
}
}
}
/**
* Returns the position of the next step using A* algorithm.
* @param stepLength Length of the step the entity can take this update.
* @param entity The entity that's moving.
* @param targetPos The position that the entity will move towards.
* @return Position of next step.
*/
private Position determineNextStep(float tpf, PlayerControlledEntity entity, Position targetPos)
{
double stepLength = tpf*entity.getSpeed();
if (path == null || path.nrOfNodesLeft() < 1 || pathRefresh )
{
pathRefresh = false;
path = aStar.calculatePath(entity.getPosition(), targetPos, entity.getEntityID());
+ world.setNodesOccupied(world.getNodeAt(entity.getPosition()), entity.getSize(), 0);
}
Position outputPos = entity.getPosition();
while (stepLength > 0) // repeat until the whole step is taken (or no nodes are left in the path)
{
if (path.nrOfNodesLeft() < 1)
{
break;
}
AStarNode nextNode = path.getNextNode();
double distanceToNextNode = ModelUtils.INSTANCE.getDistance(outputPos, nextNode.getPosition());
if (distanceToNextNode > stepLength)
{
Vector2d direction = Position.getVectorBetween(outputPos, nextNode.getPosition());
direction.normalize();
outputPos = outputPos.add(stepLength, direction);
stepLength = 0;
}
else //if (distanceToNextNode <= stepLength)
{
stepLength -= distanceToNextNode;
outputPos = nextNode.getPosition().copy();
path = aStar.calculatePath(outputPos, targetPos, entity.getEntityID());
if (path.nrOfNodesLeft() > 0)
{
world.setNodesOccupied(nextNode.getNode(),
entity.getSize(), 0);
world.setNodesOccupied(path.getNextNode().getNode(),
entity.getSize(), entity.getEntityID());
}
}
}
return outputPos;
}
@Override
public AbstractAbility createAbility() {
MoveAbility newAbility = new MoveAbility();
newAbility.initialize();
return newAbility;
}
}
| true | true | private Position determineNextStep(float tpf, PlayerControlledEntity entity, Position targetPos)
{
double stepLength = tpf*entity.getSpeed();
if (path == null || path.nrOfNodesLeft() < 1 || pathRefresh )
{
pathRefresh = false;
path = aStar.calculatePath(entity.getPosition(), targetPos, entity.getEntityID());
}
Position outputPos = entity.getPosition();
while (stepLength > 0) // repeat until the whole step is taken (or no nodes are left in the path)
{
if (path.nrOfNodesLeft() < 1)
{
break;
}
AStarNode nextNode = path.getNextNode();
double distanceToNextNode = ModelUtils.INSTANCE.getDistance(outputPos, nextNode.getPosition());
if (distanceToNextNode > stepLength)
{
Vector2d direction = Position.getVectorBetween(outputPos, nextNode.getPosition());
direction.normalize();
outputPos = outputPos.add(stepLength, direction);
stepLength = 0;
}
else //if (distanceToNextNode <= stepLength)
{
stepLength -= distanceToNextNode;
outputPos = nextNode.getPosition().copy();
path = aStar.calculatePath(outputPos, targetPos, entity.getEntityID());
if (path.nrOfNodesLeft() > 0)
{
world.setNodesOccupied(nextNode.getNode(),
entity.getSize(), 0);
world.setNodesOccupied(path.getNextNode().getNode(),
entity.getSize(), entity.getEntityID());
}
}
}
return outputPos;
}
| private Position determineNextStep(float tpf, PlayerControlledEntity entity, Position targetPos)
{
double stepLength = tpf*entity.getSpeed();
if (path == null || path.nrOfNodesLeft() < 1 || pathRefresh )
{
pathRefresh = false;
path = aStar.calculatePath(entity.getPosition(), targetPos, entity.getEntityID());
world.setNodesOccupied(world.getNodeAt(entity.getPosition()), entity.getSize(), 0);
}
Position outputPos = entity.getPosition();
while (stepLength > 0) // repeat until the whole step is taken (or no nodes are left in the path)
{
if (path.nrOfNodesLeft() < 1)
{
break;
}
AStarNode nextNode = path.getNextNode();
double distanceToNextNode = ModelUtils.INSTANCE.getDistance(outputPos, nextNode.getPosition());
if (distanceToNextNode > stepLength)
{
Vector2d direction = Position.getVectorBetween(outputPos, nextNode.getPosition());
direction.normalize();
outputPos = outputPos.add(stepLength, direction);
stepLength = 0;
}
else //if (distanceToNextNode <= stepLength)
{
stepLength -= distanceToNextNode;
outputPos = nextNode.getPosition().copy();
path = aStar.calculatePath(outputPos, targetPos, entity.getEntityID());
if (path.nrOfNodesLeft() > 0)
{
world.setNodesOccupied(nextNode.getNode(),
entity.getSize(), 0);
world.setNodesOccupied(path.getNextNode().getNode(),
entity.getSize(), entity.getEntityID());
}
}
}
return outputPos;
}
|
diff --git a/src/main/java/com/mikeprimm/bukkit/AngryWolves/AngryWolves.java b/src/main/java/com/mikeprimm/bukkit/AngryWolves/AngryWolves.java
index abeefa8..77f4d59 100644
--- a/src/main/java/com/mikeprimm/bukkit/AngryWolves/AngryWolves.java
+++ b/src/main/java/com/mikeprimm/bukkit/AngryWolves/AngryWolves.java
@@ -1,1119 +1,1119 @@
package com.mikeprimm.bukkit.AngryWolves;
import java.util.HashMap;
import java.util.ArrayList;
import java.util.logging.Logger;
import org.bukkit.entity.CreatureType;
import org.bukkit.entity.Player;
import org.bukkit.entity.Wolf;
import org.bukkit.entity.LivingEntity;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Priority;
import org.bukkit.util.config.Configuration;
import org.bukkit.util.config.ConfigurationNode;
import org.bukkit.Location;
import org.bukkit.World;
import java.io.File;
import java.io.FileWriter;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.List;
import java.util.Random;
import java.util.Collections;
/**
* AngryWolves plugin - watch wolf spawns and make some of them angry by default
*
* @author MikePrimm
*/
public class AngryWolves extends JavaPlugin {
public static Logger log = Logger.getLogger("Minecraft");
private final AngryWolvesEntityListener entityListener = new AngryWolvesEntityListener(this);
private final HashMap<Player, Boolean> debugees = new HashMap<Player, Boolean>();
public boolean verbose = false;
private int poplimit = ANGRYWOLF_POPLIMIT;
private double hellhound_dmgscale = HELLHOUND_DMGSCALE;
private int hellhound_health = HELLHOUND_HEALTH;
private int angrywolf_health = ANGRYWOLF_HEALTH;
/* Deprecated parms */
public static final String CONFIG_ANGERRATE_DEFAULT = "angerrate";
public static final String CONFIG_ASALTMOB_DEFAULT = "asaltmob";
/* New parameters */
public static final String CONFIG_SPAWNMSG_DEFAULT = "spawnmsg";
public static final String CONFIG_SPAWN_ANGERRATE = "spawn-anger-rate";
public static final String CONFIG_MOBTOWOLF_RATE = "mob-to-wolf-rate";
public static final String CONFIG_MOBTOWILDWOLF_RATE = "mob-to-wildwolf-rate";
public static final String CONFIG_FULLMOON_MOBTOWOLF_RATE = "fullmoon-mob-to-wolf-rate";
public static final String CONFIG_CREEPERTOWOLF_RATE = "creeper-to-wolf-rate";
public static final String CONFIG_ZOMBIETOWOLF_RATE = "zombie-to-wolf-rate";
public static final String CONFIG_PIGZOMBIETOWOLF_RATE = "pigzombie-to-wolf-rate";
public static final String CONFIG_SPIDERTOWOLF_RATE = "spider-to-wolf-rate";
public static final String CONFIG_SKELETONTOWOLF_RATE = "skeleton-to-wolf-rate";
public static final String CONFIG_DAYSPERMOON = "days-between-fullmoons";
public static final String CONFIG_ANGERRATE_MOON = "anger-rate-fullmoon";
public static final String CONFIG_FULLMOONMSG = "fullmoonmsg";
public static final String CONFIG_WOLFINSHEEP_RATE = "wolf-in-sheep-rate";
public static final String CONFIG_WOLFINSHEEP_MSG = "wolf-in-sheep-msg";
public static final String CONFIG_WOLFFRIEND = "wolf-friends";
public static final String CONFIG_SPAWNMSGRADIUS = "spawnmsgradius";
public static final String CONFIG_MOBTOWOLF_IGNORE_TERRAIN = "mobtowolf-ignore-terrain";
public static final String CONFIG_WOLFLOOT = "wolf-loot";
public static final String CONFIG_WOLFLOOT_RATE = "wolf-loot-rate";
public static final String CONFIG_WOLFXP = "wolf-xp";
public static final String CONFIG_ANGRYWOLFLOOT = "angry-wolf-loot";
public static final String CONFIG_ANGRYWOLFLOOT_RATE = "angry-wolf-loot-rate";
public static final String CONFIG_ANGRYWOLFXP = "angry-wolf-xp";
public static final String CONFIG_HELLHOUNDLOOT = "hellhound-loot";
public static final String CONFIG_HELLHOUNDLOOT_RATE = "hellhound-loot-rate";
public static final String CONFIG_HELLHOUNDXP = "hellhound-xp";
public static final String CONFIG_HELLHOUND_RATE = "hellhound-rate";
public static final String CONFIG_FULLMOON_STAY_ANGRY_RATE = "fullmoon-stay-angry-rate";
public static final String CONFIG_ANYGYWOLF_POPLIMIT = "angrywolf-pop-limit";
public static final String CONFIG_HELLHOUND_DAMAGESCALE = "hellhound-damagescale";
public static final String CONFIG_HELLHOUND_HEALTH = "hellhound-health";
public static final String CONFIG_ANGRYWOLF_HEALTH = "angrywolf-health";
public static final String CONFIG_HELLHOUND_FIREBALL_RATE = "hellhound-fireball-rate";
public static final String CONFIG_HELLHOUND_FIREBALL_RANGE = "hellhound-fireball-range";
public static final String CONFIG_HELLHOUND_FIREBALL_INCENDIARY = "hellhound-fireball-incendiary";
public static final String CONFIG_PUPS_ON_SHEEP_KILL_RATE = "pup-on-sheep-kill-rate";
public static final int SPAWN_ANGERRATE_DEFAULT = 0;
public static final int MOBTOWOLF_RATE_DEFAULT = 10;
public static final int DAYSPERMOON_DEFAULT = 28;
public static final int ANGERRATE_MOON_DEFAULT = 0;
public static final int WOLFINSHEEP_RATE = 0;
public static final int SPAWNMSGRADIUS_DEFAULT = 0; /* Unlimited */
public static final int HELLHOUND_RATE_DEFAULT = 10;
public static final int FULLMOON_STAYANGRYRATE_DEFAULT = 0;
public static final int MOBTOWOLF_RATE_MOON_DEFAULT = -1; /* Use MOBTOWOLF_RATE */
public static final int ANGRYWOLF_POPLIMIT = 200;
public static final double HELLHOUND_DMGSCALE = 0.5;
public static final int HELLHOUND_HEALTH = 20;
public static final int ANGRYWOLF_HEALTH = 8;
public static final String WOLF_FRIEND_PERM = "angrywolves.wolf-friend";
/* Common configuration attributes - all tiers */
public static abstract class BaseConfig {
String spawnmsg;
Integer mobtowolf_rate;
Integer mobtowildwolf_rate;
Integer fullmoon_mobtowolf_rate;
Integer creepertowolf_rate;
Integer zombietowolf_rate;
Integer pigzombietowolf_rate;
Integer skeletontowolf_rate;
Integer spidertowolf_rate;
Integer hellhound_rate;
Integer angerrate;
Integer angerrate_moon;
Integer stayangryrate_moon;
Integer wolfinsheep_rate;
Integer spawnmsgradius;
String wolfinsheep_msg;
String fullmoonmsg;
Boolean wolffriend;
Boolean ignore_terrain;
Integer wolfloot_rate;
List<Integer> wolfloot;
Integer wolfxp;
Integer angrywolfloot_rate;
List<Integer> angrywolfloot;
Integer angrywolfxp;
Integer hellhoundloot_rate;
List<Integer> hellhoundloot;
Integer hellhoundxp;
Integer hellhound_fireball_rate;
Integer hellhound_fireball_range;
Boolean hellhound_fireball_incendiary;
Integer pup_on_kill_rate;
abstract BaseConfig getParent();
public String getSpawnMsg() {
if(spawnmsg != null) {
return spawnmsg;
}
BaseConfig p = getParent();
if(p != null)
return p.getSpawnMsg();
else
return "";
}
/**
* Resolve mob-type specific rate, if any
* @param t - mob type
* @return rate, or null if not found
*/
private Integer getMobSpecWolfRate(CreatureType t) {
Integer r = null;
switch(t) {
case SKELETON:
r = skeletontowolf_rate;
break;
case ZOMBIE:
r = zombietowolf_rate;
break;
case PIG_ZOMBIE:
r = pigzombietowolf_rate;
break;
case SPIDER:
r = spidertowolf_rate;
break;
case CREEPER:
r = creepertowolf_rate;
break;
}
if(r == null) { /* Not defined here? check parents */
BaseConfig p = getParent();
if(p != null) {
r = p.getMobSpecWolfRate(t);
}
}
return r;
}
public int getMobToWolfRate(CreatureType mob, boolean is_fullmoon) {
int rate = 0;
Integer r = getMobSpecWolfRate(mob); /* See if specific rate defined */
if(r == null) { /* No? Check for general rate */
if(is_fullmoon) {
rate = mobToWolfRateMoon();
if(rate < 0)
rate = mobToWolfRate();
}
else {
rate = mobToWolfRate();
}
}
else {
rate = r.intValue();
}
return rate;
}
private int mobToWolfRate() {
if(mobtowolf_rate != null) {
return mobtowolf_rate.intValue();
}
BaseConfig p = getParent();
if(p != null)
return p.mobToWolfRate();
else
return MOBTOWOLF_RATE_DEFAULT;
}
public int mobToWildWolfRate() {
if(mobtowildwolf_rate != null) {
return mobtowildwolf_rate.intValue();
}
BaseConfig p = getParent();
if(p != null)
return p.mobToWildWolfRate();
else
return 0;
}
private int mobToWolfRateMoon() {
if(fullmoon_mobtowolf_rate != null) {
return fullmoon_mobtowolf_rate.intValue();
}
BaseConfig p = getParent();
if(p != null)
return p.mobToWolfRateMoon();
else
return MOBTOWOLF_RATE_MOON_DEFAULT;
}
public int getSpawnAngerRate() {
if(angerrate != null) {
return angerrate.intValue();
}
BaseConfig p = getParent();
if(p != null)
return p.getSpawnAngerRate();
else
return SPAWN_ANGERRATE_DEFAULT;
}
public int getPupOnSheepKillRate() {
if(pup_on_kill_rate != null) {
return pup_on_kill_rate.intValue();
}
BaseConfig p = getParent();
if(p != null)
return p.getPupOnSheepKillRate();
else
return 0;
}
public int getSpawnAngerRateMoon() {
if(angerrate_moon != null) {
return angerrate_moon.intValue();
}
BaseConfig p = getParent();
if(p != null)
return p.getSpawnAngerRateMoon();
else
return ANGERRATE_MOON_DEFAULT;
}
public int getStayAngryRateMoon() {
if(stayangryrate_moon != null) {
return stayangryrate_moon.intValue();
}
BaseConfig p = getParent();
if(p != null)
return p.getStayAngryRateMoon();
else
return FULLMOON_STAYANGRYRATE_DEFAULT;
}
public int getWolfInSheepRate() {
if(wolfinsheep_rate != null) {
return wolfinsheep_rate.intValue();
}
BaseConfig p = getParent();
if(p != null)
return p.getWolfInSheepRate();
else
return WOLFINSHEEP_RATE;
}
public int getHellhoundRate() {
if(hellhound_rate != null) {
return hellhound_rate.intValue();
}
BaseConfig p = getParent();
if(p != null)
return p.getHellhoundRate();
else
return HELLHOUND_RATE_DEFAULT;
}
public String getWolfInSheepMsg() {
if(wolfinsheep_msg != null) {
return wolfinsheep_msg;
}
BaseConfig p = getParent();
if(p != null)
return p.getWolfInSheepMsg();
else
return "";
}
public String getFullMoonMsg() {
if(fullmoonmsg != null)
return fullmoonmsg;
BaseConfig p = getParent();
if(p != null)
return p.getFullMoonMsg();
else
return "";
}
public boolean getWolfFriendActive() {
if(wolffriend != null)
return wolffriend.booleanValue();
BaseConfig p = getParent();
if(p != null)
return p.getWolfFriendActive();
else
return false;
}
public int getHellhoundFireballRate() {
if(hellhound_fireball_rate != null)
return hellhound_fireball_rate.intValue();
BaseConfig p = getParent();
if(p != null)
return p.getHellhoundFireballRate();
else
return 0;
}
public int getHellhoundFireballRange() {
if(hellhound_fireball_range != null)
return hellhound_fireball_range.intValue();
BaseConfig p = getParent();
if(p != null)
return p.getHellhoundFireballRange();
else
return 10;
}
public boolean getHellhoundFireballIncendiary() {
if(hellhound_fireball_incendiary != null)
return hellhound_fireball_incendiary.booleanValue();
BaseConfig p = getParent();
if(p != null)
return p.getHellhoundFireballIncendiary();
else
return false;
}
public boolean getMobToWolfTerrainIgnore() {
if(ignore_terrain != null)
return ignore_terrain.booleanValue();
BaseConfig p = getParent();
if(p != null)
return p.getMobToWolfTerrainIgnore();
else
return false;
}
public int getSpawnMsgRadius() {
if(spawnmsgradius != null) {
return spawnmsgradius.intValue();
}
BaseConfig p = getParent();
if(p != null)
return p.getSpawnMsgRadius();
else
return SPAWNMSGRADIUS_DEFAULT;
}
public int getWolfLootRate() {
if(wolfloot_rate != null) {
return wolfloot_rate.intValue();
}
BaseConfig p = getParent();
if(p != null)
return p.getWolfLootRate();
else
return 0;
}
public int getWolfXP() {
if(wolfxp != null) {
return wolfxp.intValue();
}
BaseConfig p = getParent();
if(p != null)
return p.getWolfXP();
else
return 0;
}
public List<Integer> getWolfLoot() {
if(wolfloot != null) {
return wolfloot;
}
BaseConfig p = getParent();
if(p != null)
return p.getWolfLoot();
else
return Collections.singletonList(Integer.valueOf(334));
}
public int getAngryWolfLootRate() {
if(angrywolfloot_rate != null) {
return angrywolfloot_rate.intValue();
}
BaseConfig p = getParent();
if(p != null)
return p.getAngryWolfLootRate();
else
return 0;
}
public int getAngryWolfXP() {
if(angrywolfxp != null) {
return angrywolfxp.intValue();
}
BaseConfig p = getParent();
if(p != null)
return p.getAngryWolfXP();
else
return 0;
}
public List<Integer> getAngryWolfLoot() {
if(angrywolfloot != null) {
return angrywolfloot;
}
BaseConfig p = getParent();
if(p != null)
return p.getAngryWolfLoot();
else
return Collections.singletonList(Integer.valueOf(334));
}
public int getHellHoundLootRate() {
if(hellhoundloot_rate != null) {
return hellhoundloot_rate.intValue();
}
BaseConfig p = getParent();
if(p != null)
return p.getHellHoundLootRate();
else
return -1; /* Use wolf rate */
}
public int getHellHoundXP() {
if(hellhoundxp != null) {
return hellhoundxp.intValue();
}
BaseConfig p = getParent();
if(p != null)
return p.getHellHoundXP();
else
return -1; /* Use wolf rate */
}
public List<Integer> getHellHoundLoot() {
if(hellhoundloot != null) {
return hellhoundloot;
}
BaseConfig p = getParent();
if(p != null)
return p.getHellHoundLoot();
else
return null; /* Use wolf loot */
}
void loadConfiguration(ConfigurationNode n) {
if(n.getProperty(CONFIG_SPAWN_ANGERRATE) != null) {
int spawn_ang = n.getInt(CONFIG_SPAWN_ANGERRATE, 0);
if(spawn_ang < 0) spawn_ang = 0;
if(spawn_ang > 100) spawn_ang = 100;
angerrate = Integer.valueOf(spawn_ang);
}
String m = n.getString(CONFIG_SPAWNMSG_DEFAULT);
if((m != null) && (m.length() > 0)) {
spawnmsg = m;
}
if(n.getProperty(CONFIG_MOBTOWOLF_RATE) != null) {
int mobtowolf = n.getInt(CONFIG_MOBTOWOLF_RATE, 0);
mobtowolf_rate = Integer.valueOf(mobtowolf);
}
if(n.getProperty(CONFIG_MOBTOWILDWOLF_RATE) != null) {
int mobtowolf = n.getInt(CONFIG_MOBTOWILDWOLF_RATE, 0);
mobtowildwolf_rate = Integer.valueOf(mobtowolf);
}
if(n.getProperty(CONFIG_FULLMOON_MOBTOWOLF_RATE) != null) {
int mobtowolf = n.getInt(CONFIG_FULLMOON_MOBTOWOLF_RATE, -1);
fullmoon_mobtowolf_rate = Integer.valueOf(mobtowolf);
}
if(n.getProperty(CONFIG_HELLHOUND_RATE) != null) {
int puprate = n.getInt(CONFIG_PUPS_ON_SHEEP_KILL_RATE, 0);
pup_on_kill_rate = Integer.valueOf(puprate);
}
if(n.getProperty(CONFIG_HELLHOUND_RATE) != null) {
int hellhoundrate = n.getInt(CONFIG_HELLHOUND_RATE, 0);
hellhound_rate = Integer.valueOf(hellhoundrate);
}
if(n.getProperty(CONFIG_CREEPERTOWOLF_RATE) != null) {
int mobrate = n.getInt(CONFIG_CREEPERTOWOLF_RATE, 0);
creepertowolf_rate = Integer.valueOf(mobrate);
}
if(n.getProperty(CONFIG_SKELETONTOWOLF_RATE) != null) {
int mobrate = n.getInt(CONFIG_SKELETONTOWOLF_RATE, 0);
skeletontowolf_rate = Integer.valueOf(mobrate);
}
if(n.getProperty(CONFIG_SPIDERTOWOLF_RATE) != null) {
int mobrate = n.getInt(CONFIG_SPIDERTOWOLF_RATE, 0);
spidertowolf_rate = Integer.valueOf(mobrate);
}
if(n.getProperty(CONFIG_ZOMBIETOWOLF_RATE) != null) {
int mobrate = n.getInt(CONFIG_ZOMBIETOWOLF_RATE, 0);
zombietowolf_rate = Integer.valueOf(mobrate);
}
if(n.getProperty(CONFIG_PIGZOMBIETOWOLF_RATE) != null) {
int mobrate = n.getInt(CONFIG_PIGZOMBIETOWOLF_RATE, 0);
pigzombietowolf_rate = Integer.valueOf(mobrate);
}
if(n.getProperty(CONFIG_SPAWNMSGRADIUS) != null) {
int smrad = n.getInt(CONFIG_SPAWNMSGRADIUS, 0);
spawnmsgradius = Integer.valueOf(smrad);
}
if(n.getProperty(CONFIG_ANGERRATE_MOON) != null) {
int spawn_ang = n.getInt(CONFIG_ANGERRATE_MOON, 0);
if(spawn_ang < 0) spawn_ang = 0;
if(spawn_ang > 100) spawn_ang = 100;
angerrate_moon = Integer.valueOf(spawn_ang);
}
if(n.getProperty(CONFIG_FULLMOON_STAY_ANGRY_RATE) != null) {
int stayangry = n.getInt(CONFIG_FULLMOON_STAY_ANGRY_RATE, FULLMOON_STAYANGRYRATE_DEFAULT);
if(stayangry < 0) stayangry = 0;
if(stayangry > 100) stayangry = 100;
stayangryrate_moon = Integer.valueOf(stayangry);
}
if(n.getProperty(CONFIG_WOLFINSHEEP_RATE) != null) {
wolfinsheep_rate = n.getInt(CONFIG_WOLFINSHEEP_RATE, 0);
}
m = n.getString(CONFIG_WOLFINSHEEP_MSG);
if((m != null) && (m.length() > 0)) {
wolfinsheep_msg = m;
}
m = n.getString(CONFIG_FULLMOONMSG);
if((m != null) && (m.length() > 0)) {
fullmoonmsg = m;
}
if(n.getProperty(CONFIG_WOLFFRIEND) != null) {
wolffriend = n.getBoolean(CONFIG_WOLFFRIEND, false);
}
if(n.getProperty(CONFIG_HELLHOUND_FIREBALL_RATE) != null) {
hellhound_fireball_rate = n.getInt(CONFIG_HELLHOUND_FIREBALL_RATE, 0);
}
if(n.getProperty(CONFIG_HELLHOUND_FIREBALL_RANGE) != null) {
hellhound_fireball_range = n.getInt(CONFIG_HELLHOUND_FIREBALL_RANGE, 10);
}
if(n.getProperty(CONFIG_HELLHOUND_FIREBALL_INCENDIARY) != null) {
hellhound_fireball_incendiary = n.getBoolean(CONFIG_HELLHOUND_FIREBALL_INCENDIARY, false);
}
if(n.getProperty(CONFIG_MOBTOWOLF_IGNORE_TERRAIN) != null) {
ignore_terrain = n.getBoolean(CONFIG_MOBTOWOLF_IGNORE_TERRAIN, false);
}
if(n.getProperty(CONFIG_WOLFLOOT_RATE) != null) {
wolfloot_rate = n.getInt(CONFIG_WOLFLOOT_RATE, 0);
}
if(n.getProperty(CONFIG_WOLFLOOT) != null) {
wolfloot = n.getIntList(CONFIG_WOLFLOOT, Collections.singletonList(Integer.valueOf(334)));
}
if(n.getProperty(CONFIG_WOLFXP) != null) {
wolfxp = n.getInt(CONFIG_WOLFXP, 0);
}
if(n.getProperty(CONFIG_ANGRYWOLFLOOT_RATE) != null) {
angrywolfloot_rate = n.getInt(CONFIG_ANGRYWOLFLOOT_RATE, -1);
}
if(n.getProperty(CONFIG_ANGRYWOLFLOOT) != null) {
angrywolfloot = n.getIntList(CONFIG_ANGRYWOLFLOOT, null);
}
if(n.getProperty(CONFIG_ANGRYWOLFXP) != null) {
angrywolfxp = n.getInt(CONFIG_ANGRYWOLFXP, 0);
}
if(n.getProperty(CONFIG_HELLHOUNDLOOT_RATE) != null) {
hellhoundloot_rate = n.getInt(CONFIG_HELLHOUNDLOOT_RATE, -1);
}
if(n.getProperty(CONFIG_HELLHOUNDLOOT) != null) {
hellhoundloot = n.getIntList(CONFIG_HELLHOUNDLOOT, null);
}
if(n.getProperty(CONFIG_HELLHOUNDXP) != null) {
hellhoundxp = n.getInt(CONFIG_HELLHOUNDXP, 0);
}
}
public String toString() {
return "spawnmsg=" + this.getSpawnMsg() +
", spawnmsgradius=" + this.getSpawnMsgRadius() +
", spawnrate=" + this.getSpawnAngerRate() +
", wolfinsheeprate=" + this.getWolfInSheepRate() +
", wolfinsheepmsg=" + this.getWolfInSheepMsg() +
", angerratemoon=" + this.getSpawnAngerRateMoon() +
", fullmoonmsg=" + getFullMoonMsg() +
", wolffriend=" + getWolfFriendActive();
}
};
/* World-level configuration attributes */
public static class WorldConfig extends BaseConfig {
/* World-specific configuration attributes */
Integer days_per_moon;
WorldConfig par;
WorldConfig(WorldConfig p) {
par = p;
}
BaseConfig getParent() { return par; }
public int getDaysPerMoon() {
if(days_per_moon != null) {
return days_per_moon.intValue();
}
if(par != null)
return par.getDaysPerMoon();
else
return DAYSPERMOON_DEFAULT;
}
void loadConfiguration(ConfigurationNode n) {
super.loadConfiguration(n); /* Load base attributes */
if(n.getProperty(CONFIG_DAYSPERMOON) != null) {
int dpm = n.getInt(CONFIG_DAYSPERMOON, 0);
days_per_moon = Integer.valueOf(dpm);
}
}
public String toString() {
return "dayspermoon=" + getDaysPerMoon() +
", " + super.toString();
}
};
/* World state records - include config and operating state */
private static class PerWorldState extends WorldConfig {
boolean moon_is_full;
int daycounter;
long last_time;
List<AreaConfig> areas;
PerWorldState() {
super(def_config);
}
};
/* Area level configuration attributes */
public static class AreaConfig extends BaseConfig {
String areaname;
double x[];
double z[];
/* Derived coords - bounding box, for fast dismissal during intersect test */
double x_low, x_high;
double z_low, z_high;
WorldConfig par;
BaseConfig getParent() { return par; }
AreaConfig(String n, WorldConfig p) {
par = p;
areaname = n;
}
void loadConfiguration(ConfigurationNode n) {
super.loadConfiguration(n); /* Load base attributes */
/* Get coordinate list */
List<ConfigurationNode> cl = n.getNodeList("coords", null);
if(cl != null) {
int len = cl.size(); /* Get number of elements in list */
x = new double[len];
z = new double[len];
int i = 0;
for(ConfigurationNode coord : cl) { /* Loop through coords */
x[i] = coord.getDouble("x", 0.0);
z[i] = coord.getDouble("z", 0.0); /* Read coordinates into array */
if(i > 0) { /* Compute bounding box */
if(x[i] < x_low) x_low = x[i];
if(x[i] > x_high) x_high = x[i];
if(z[i] < z_low) z_low = z[i];
if(z[i] > z_high) z_high = z[i];
}
else {
x_low = x_high = x[i];
z_low = z_high = z[i];
}
i++;
}
}
}
/* Test if given coordinates are inside our area - assumes world already checked */
public boolean isInArea(double xval, double yval, double zval) {
/* Do bounding box test first - fastest dismiss */
if((xval < x_low) || (xval > x_high) || (zval < z_low) || (zval > z_high)) {
return false;
}
/* Now, if we have 3 or more points, test if within the polygon too */
if(x.length > 2) {
/* Winding test - count edges looking towards -z */
int i, j;
boolean odd = false;
for(i = 0, j = x.length-1; i < x.length; j = i++) {
/* If x within range of next line segment, and z is to left of intersec at x=xval, hit */
if( ((x[i] > xval) != (x[j] > xval)) &&
(zval < (z[j]-z[i]) * (xval-x[i]) / (x[j] - x[i]) + z[i]) )
odd = !odd;
}
return odd; /* If odd, we're inside */
}
else /* If 2 points, bounding box is enough */
return true;
}
public String toString() {
return "name=" + areaname +
", xlow=" + x_low + ", xhigh=" + x_high + ", zlow=" + z_low + ", zhigh=" + z_high +
", " + super.toString();
}
};
private static HashMap<String, PerWorldState> per_world = new HashMap<String, PerWorldState>();
private static WorldConfig def_config; /* Base world configuration */
private boolean block_spawn_anger = false; /* Used for anger-free spawn */
private Random rnd = new Random(System.currentTimeMillis());
private static PerWorldState getState(String w) {
PerWorldState pws = per_world.get(w);
if(pws == null) {
pws = new PerWorldState();
per_world.put(w, pws);
}
return pws;
}
public boolean isFullMoon(World w) {
PerWorldState pws = getState(w.getName());
return pws.moon_is_full;
}
/**
* Find configuration record, by world and coordinates
* @param loc - location
* @return first matching config record
*/
public BaseConfig findByLocation(Location loc) {
PerWorldState pws = getState(loc.getWorld().getName());
if(pws.areas != null) { /* Any areas? */
double x = loc.getX(), y = loc.getY(), z = loc.getZ();
for(AreaConfig ac : pws.areas) {
/* If location is within area's rectangle */
if(ac.isInArea(x, y, z)) {
return ac;
}
}
}
return pws;
}
/**
* Find configuration record by world
* @param w - world
* @return first matching config record
*/
public WorldConfig findByWorld(World w) {
return getState(w.getName());
}
boolean isNormalSpawn() {
return block_spawn_anger;
}
private class CheckForMoon implements Runnable {
public void run() {
if(verbose) log.info("Check full moon");
List<World> w = getServer().getWorlds();
for(World world : w) {
PerWorldState pws = getState(world.getName());
int dpm = pws.getDaysPerMoon(); /* Get lunar period */
if(dpm <= 0) { /* Disabled? */
pws.moon_is_full = false; /* Not us */
}
else {
long t = world.getTime(); /* Get time of day */
if(t < pws.last_time) { /* Day ended? */
pws.daycounter++;
}
pws.last_time = t;
long dom = pws.daycounter % dpm; /* Compute day of "month" */
if((dom == (dpm-1)) && ((t % 24000) > 12500)) {
if(pws.moon_is_full == false) {
pws.moon_is_full = true;
if(verbose) log.info("Starting full moon in " + world.getName());
/* And handle event */
List<Player> pl = world.getPlayers();
for(Player p : pl) {
AngryWolves.BaseConfig pc = findByLocation(p.getLocation());
String msg = pc.getFullMoonMsg();
/* Send the message to the player, if there is one */
if((msg != null) && (msg.length() > 0)) {
p.sendMessage(msg);
}
}
/* And make the wolves angry */
List<LivingEntity> lst = world.getLivingEntities();
for(LivingEntity le : lst) {
if(le instanceof Wolf) {
Wolf wolf = (Wolf)le;
/* If not angry and not tame, make angry */
if((wolf.isAngry() == false) && (isTame(wolf) == false)) {
/* Check situation at wolf's location */
AngryWolves.BaseConfig wc = findByLocation(wolf.getLocation());
if(rnd.nextInt(100) < wc.getSpawnAngerRateMoon()) {
wolf.setAngry(true);
if(verbose) log.info("Made wolf angry (full moon)");
}
}
}
}
}
}
else if(pws.moon_is_full) { /* Was full, but over now */
pws.moon_is_full = false;
if(verbose) log.info("Full moon ended in " + world.getName());
/* And make the wolves happy */
List<LivingEntity> lst = world.getLivingEntities();
for(LivingEntity le : lst) {
if(le instanceof Wolf) {
Wolf wolf = (Wolf)le;
/* If angry and not a hellhound, make not angry */
if(wolf.isAngry() && (!AngryWolvesEntityListener.isHellHound(wolf))) {
/* If wolf's location is where moon anger happens, clear anger */
BaseConfig loc = findByLocation(wolf.getLocation());
if(loc.getSpawnAngerRateMoon() > 0) {
if(rnd.nextInt(100) >= loc.getStayAngryRateMoon()) {
wolf.setAngry(false);
wolf.setTarget(null);
if(verbose) log.info("Made angry wolf calm (end-of-moon)");
}
}
}
}
}
}
}
}
}
}
/* On disable, stop doing our function */
public void onDisable() {
/* Since our registered listeners are disabled by default, we don't need to do anything */
}
public void onEnable() {
/* Initialize our permissions */
AngryWolvesPermissions.initialize(getServer());
/* Read in our configuration */
readConfig();
// Register our events
PluginManager pm = getServer().getPluginManager();
pm.registerEvent(Event.Type.CREATURE_SPAWN, entityListener, Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_DAMAGE, entityListener, Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_TARGET, entityListener, Priority.Normal, this);
pm.registerEvent(Event.Type.ENTITY_DEATH, entityListener, Priority.Normal, this);
PluginDescriptionFile pdfFile = this.getDescription();
log.info("[AngryWolves] version " + pdfFile.getVersion() + " is enabled" );
/* Start job to watch for sunset/sunrise (every 30 seconds or so) */
getServer().getScheduler().scheduleSyncRepeatingTask(this, new CheckForMoon(), 0, 20*30);
}
private void readConfig() {
File configdir = getDataFolder(); /* Get our data folder */
if(configdir.exists() == false) { /* Not yet defined? */
configdir.mkdirs(); /* Create it */
}
File configfile = new File(configdir, "AngryWolves.yml"); /* Our YML file */
Configuration cfg = new Configuration(configfile);
if(configfile.exists() == false) { /* Not defined yet? */
PrintWriter fos = null;
try {
fos = new PrintWriter(new FileWriter(configfile));
fos.println("# Configuration file for AngryWolves);");
fos.println("# spawn-anger-rate is percentage of normal wolf spawns that spawn angry");
fos.println("# If undefined, spawn-anger-rate defaults to 0");
fos.println(CONFIG_SPAWN_ANGERRATE + ": 5");
fos.println("# hellhound-rate is percentage of angry wolfs that are hellhounds (flaming-fireproof-wolves)");
fos.println("# If undefined, hellhound-rate defaults to 10. In Nether, 100% of angry wolves are hellhounds.");
fos.println(CONFIG_HELLHOUND_RATE + ": 10");
fos.println("# mob-to-wolf-rate is the TENTHS of a percent of monster spawns that are replaced with angry wolves");
fos.println("# spider-to-wolf-rate is the TENTHS of a percent of spider spawns that are replaced with angry wolves");
fos.println("# zombie-to-wolf-rate is the TENTHS of a percent of zombie spawns that are replaced with angry wolves");
fos.println("# skeleton-to-wolf-rate is the TENTHS of a percent of skeleton spawns that are replaced with angry wolves");
fos.println("# creeper-to-wolf-rate is the TENTHS of a percent of creeper spawns that are replaced with angry wolves");
fos.println("# pig-zombie-to-wolf-rate is the TENTHS of a percent of pig-zombie spawns that are replaced with angry wolves");
fos.println("# note: if monster type specific rate is defined, it supercedes the mob-to-wolf-rate for that monster type");
fos.println("# If undefined, mob-to-wolf-rate defaults to 10, others are null");
fos.println(CONFIG_MOBTOWOLF_RATE + ": 10");
fos.println("# " + CONFIG_SPIDERTOWOLF_RATE + ": 20");
fos.println("# " + CONFIG_ZOMBIETOWOLF_RATE + ": 0");
fos.println("# " + CONFIG_SKELETONTOWOLF_RATE + ": 5");
fos.println("# " + CONFIG_CREEPERTOWOLF_RATE + ": 1000");
fos.println("# " + CONFIG_PIGZOMBIETOWOLF_RATE + ": 20");
fos.println("# mob-to-spawn-based spawns are normally limited to spawns occuring in valid biomes for wolves, as well as over valid wolf spawn terrain (grass)");
fos.println("# " + CONFIG_MOBTOWOLF_IGNORE_TERRAIN + " can be set to 'true' to disable biome and terrain restrictions");
fos.println("# " + CONFIG_MOBTOWOLF_IGNORE_TERRAIN + ": true");
fos.println("# (Optional) Make non-angry (wild) wolf spawns from mob spawns, at given rate (in TENTHS of a percent) - make wolves more common");
fos.println(CONFIG_MOBTOWILDWOLF_RATE + ": 10");
fos.println("# (Optional) Spawn wolf pup when wolf kills sheep (rate in percent)");
fos.println("# " + CONFIG_PUPS_ON_SHEEP_KILL_RATE + ": 10");
fos.println("# If defined, can also have a 'full moon night' one out of every days-per-moon");
fos.println("# During this, anger-rate-fullmoon percent of non-tame wolves go angry");
fos.println("# At the end of the full moon, fullmoon-stay-angry-rate percent of angry wolves stay angry");
fos.println(CONFIG_DAYSPERMOON + ": 28");
fos.println(CONFIG_ANGERRATE_MOON +": 25");
fos.println(CONFIG_FULLMOONMSG + ": The wolves are baying at the full moon ...");
fos.println(CONFIG_FULLMOON_STAY_ANGRY_RATE + ": 0");
fos.println("# Optional - mob-to-wolf-rate to apply during full moon (if set - otherwise, same rate used)");
fos.println("# " + CONFIG_FULLMOON_MOBTOWOLF_RATE + ": 50");
fos.println("# Optional spawn message");
fos.println("# spawnmsg: There's a bad moon on the rise...");
fos.println("# Also, optional spawn message radius - limits message to only players within given number of blocks of spawn");
- fos.println("# spawnmsgradius: 50");
+ fos.println("# " + CONFIG_SPAWNMSGRADIUS + ": 50");
fos.println("# Wolf-in-sheeps-clothing rate : in 10ths of a percent");
fos.println(CONFIG_WOLFINSHEEP_RATE + ": 0");
fos.println(CONFIG_WOLFINSHEEP_MSG + ": Oh, no! A wolf in sheep's clothing!");
fos.println("# Optional - enable 'wolf-friends' : players with the 'angrywolves.wolf-friend' privilege will not be targetted by angry wolves!");
- fos.println("# wolf-friends: true");
+ fos.println("# " + CONFIG_WOLFFRIEND + ": true");
fos.println("# Optional - enable wolf loot - wolf-loot-rate is percent change of drop, wolf-loot is list of item ids to select from (1 randomly picked), wolf-xp is experience orbs dropped");
fos.println("# " + CONFIG_WOLFLOOT_RATE + ": 20");
fos.println("# " + CONFIG_WOLFLOOT + ": [ 334, 352, 319 ]");
fos.println("# " + CONFIG_WOLFXP + ": 5");
fos.println("# Optional - enable different loot for angry wolves (if not defined, wolf loot settings are used)");
fos.println("# " + CONFIG_ANGRYWOLFLOOT_RATE + ": 70");
fos.println("# " + CONFIG_ANGRYWOLFLOOT + ": [ 334, 352, 319 ]");
fos.println("# " + CONFIG_ANGRYWOLFXP + ": 5");
fos.println("# Optional - enable different loot for hellhounds (if not defined, wolf loot settings are used)");
fos.println("# " + CONFIG_HELLHOUNDLOOT_RATE + ": 90");
fos.println("# " + CONFIG_HELLHOUNDLOOT + ": [ 334, 352, 319 ]");
fos.println("# " + CONFIG_HELLHOUNDXP + ": 10");
fos.println("# Population limit for Angry Wolves and Hellhounds (combined for server)");
- fos.println("anygrywolf-pop-limit: 200");
+ fos.println(CONFIG_ANYGYWOLF_POPLIMIT + ": 200");
fos.println("# Angry Wolf initial health - normal wild wolves are 8, tamed wolves are 20");
- fos.println("angrywolf-health: 8");
+ fos.println(CONFIG_ANGRYWOLF_HEALTH + ": 8");
fos.println("# Hellhound initial health - normal wild wolves are 8, tamed wolves are 20");
- fos.println("hellhound-health: 10");
+ fos.println(CONFIG_HELLHOUND_HEALTH + ": 10");
fos.println("# Hellhound damage scale - multiplier for general damage to hellhounds (less that 1.0 reduces damage done to them)");
- fos.println("hellhound-damagescale: 0.5");
+ fos.println(CONFIG_HELLHOUND_DAMAGESCALE + ": 0.5");
fos.println("# (optional) have hellhounds shoot fireballs! Control range, rate (seconds between shots), and whether they cause fires");
- fos.println("#hellhound-fireball-range: 10");
- fos.println("#hellhound-fireball-rate: 3");
+ fos.println("# " + CONFIG_HELLHOUND_FIREBALL_RANGE + ": 10");
+ fos.println("# " + CONFIG_HELLHOUND_FIREBALL_RATE + ": 3");
fos.println("#hellhound-fireball-incendiary: false");
fos.println("# For multi-world specific rates, fill in rate under section for each world");
fos.println("worlds:");
fos.println("# - name: world");
fos.println("# " + CONFIG_SPAWN_ANGERRATE + ": 10");
fos.println("# " + CONFIG_MOBTOWOLF_RATE + ": 0");
fos.println("# " + CONFIG_DAYSPERMOON + ": 0");
fos.println("# - name: transylvania");
fos.println("# " + CONFIG_SPAWN_ANGERRATE + ": 90");
fos.println("# " + CONFIG_MOBTOWOLF_RATE + ": 100");
fos.println("# spawnmsg: Something evil has entered the world...");
fos.println("# Optional - for special settings limited to an area on one world");
fos.println("# 'coords' define the area, as a list of two or more coordinate values (each of which has an x and z attribute).");
fos.println("areas:");
fos.println("# - name: Area51");
fos.println("# worldname: world");
fos.println("# coords:");
fos.println("# - x: 200");
fos.println("# z: 40");
fos.println("# - x: 60");
fos.println("# z: 100");
fos.println("# " + CONFIG_SPAWN_ANGERRATE + ": 100");
fos.println("# " + CONFIG_MOBTOWOLF_RATE + ": 100");
fos.close();
} catch (IOException iox) {
log.severe("ERROR writing default configuration for AngryWolves");
return;
}
}
cfg.load(); /* Load it */
boolean dirty = false;
/* Load default world-level configuration */
def_config = new WorldConfig(null); /* Make base default object */
def_config.loadConfiguration(cfg);
//log.info("defconfig: " + def_config);
verbose = cfg.getBoolean("verbose", false);
poplimit = cfg.getInt(CONFIG_ANYGYWOLF_POPLIMIT, ANGRYWOLF_POPLIMIT);
hellhound_dmgscale = cfg.getDouble(CONFIG_HELLHOUND_DAMAGESCALE, HELLHOUND_DMGSCALE);
if(hellhound_dmgscale < 0) hellhound_dmgscale = 0.0;
hellhound_health = cfg.getInt(CONFIG_HELLHOUND_HEALTH, HELLHOUND_HEALTH);
if(hellhound_health < 1) hellhound_health = 1;
angrywolf_health = cfg.getInt(CONFIG_ANGRYWOLF_HEALTH, ANGRYWOLF_HEALTH);
if(angrywolf_health < 1) angrywolf_health = 1;
/* Now, process world-specific overrides */
List<ConfigurationNode> w = cfg.getNodeList("worlds", null);
if(w != null) {
for(ConfigurationNode world : w) {
String wname = world.getString("name"); /* Get name */
if(wname == null)
continue;
/* Load/initialize per world state/config */
PerWorldState pws = getState(wname);
pws.par = def_config; /* Our parent is global default */
/* Now load settings */
pws.loadConfiguration(world);
//log.info("world " + wname + ": " + pws);
}
}
/* Now, process area-specific overrides */
w = cfg.getNodeList("areas", null);
if(w != null) {
for(ConfigurationNode area : w) {
String aname = area.getString("name"); /* Get name */
if(aname == null)
continue;
String wname = area.getString("worldname"); /* Get world name */
if(wname == null)
continue;
PerWorldState pws = getState(wname); /* Look up world state */
/* Now, make our area state */
AreaConfig ac = new AreaConfig(aname, pws);
if(pws.areas == null) pws.areas = new ArrayList<AreaConfig>();
pws.areas.add(ac); /* Add us to our world */
/* Now load settings */
ac.loadConfiguration(area);
//log.info("area " + aname + "/" + wname + ": " + ac);
}
}
if(dirty) { /* If updated, save it */
cfg.save();
}
}
public boolean isTame(Wolf w) {
return w.isTamed();
}
public boolean isDebugging(final Player player) {
if (debugees.containsKey(player)) {
return debugees.get(player);
} else {
return false;
}
}
public int getPopulationLimit() {
return poplimit;
}
public double getHellhoundDamageScale() {
return hellhound_dmgscale;
}
public int getHellhoundHealth() {
return hellhound_health;
}
public int getAngryWolfHealth() {
return angrywolf_health;
}
/**
* Public API - used to invoke world.spawnCreature for a wolf while preventing it from being angered
*/
public LivingEntity spawnNormalWolf(World world, Location loc) {
boolean last = block_spawn_anger;
block_spawn_anger = true;
LivingEntity e = world.spawnCreature(loc, CreatureType.WOLF);
block_spawn_anger = last;
return e;
}
public void setDebugging(final Player player, final boolean value) {
debugees.put(player, value);
}
}
| false | true | private void readConfig() {
File configdir = getDataFolder(); /* Get our data folder */
if(configdir.exists() == false) { /* Not yet defined? */
configdir.mkdirs(); /* Create it */
}
File configfile = new File(configdir, "AngryWolves.yml"); /* Our YML file */
Configuration cfg = new Configuration(configfile);
if(configfile.exists() == false) { /* Not defined yet? */
PrintWriter fos = null;
try {
fos = new PrintWriter(new FileWriter(configfile));
fos.println("# Configuration file for AngryWolves);");
fos.println("# spawn-anger-rate is percentage of normal wolf spawns that spawn angry");
fos.println("# If undefined, spawn-anger-rate defaults to 0");
fos.println(CONFIG_SPAWN_ANGERRATE + ": 5");
fos.println("# hellhound-rate is percentage of angry wolfs that are hellhounds (flaming-fireproof-wolves)");
fos.println("# If undefined, hellhound-rate defaults to 10. In Nether, 100% of angry wolves are hellhounds.");
fos.println(CONFIG_HELLHOUND_RATE + ": 10");
fos.println("# mob-to-wolf-rate is the TENTHS of a percent of monster spawns that are replaced with angry wolves");
fos.println("# spider-to-wolf-rate is the TENTHS of a percent of spider spawns that are replaced with angry wolves");
fos.println("# zombie-to-wolf-rate is the TENTHS of a percent of zombie spawns that are replaced with angry wolves");
fos.println("# skeleton-to-wolf-rate is the TENTHS of a percent of skeleton spawns that are replaced with angry wolves");
fos.println("# creeper-to-wolf-rate is the TENTHS of a percent of creeper spawns that are replaced with angry wolves");
fos.println("# pig-zombie-to-wolf-rate is the TENTHS of a percent of pig-zombie spawns that are replaced with angry wolves");
fos.println("# note: if monster type specific rate is defined, it supercedes the mob-to-wolf-rate for that monster type");
fos.println("# If undefined, mob-to-wolf-rate defaults to 10, others are null");
fos.println(CONFIG_MOBTOWOLF_RATE + ": 10");
fos.println("# " + CONFIG_SPIDERTOWOLF_RATE + ": 20");
fos.println("# " + CONFIG_ZOMBIETOWOLF_RATE + ": 0");
fos.println("# " + CONFIG_SKELETONTOWOLF_RATE + ": 5");
fos.println("# " + CONFIG_CREEPERTOWOLF_RATE + ": 1000");
fos.println("# " + CONFIG_PIGZOMBIETOWOLF_RATE + ": 20");
fos.println("# mob-to-spawn-based spawns are normally limited to spawns occuring in valid biomes for wolves, as well as over valid wolf spawn terrain (grass)");
fos.println("# " + CONFIG_MOBTOWOLF_IGNORE_TERRAIN + " can be set to 'true' to disable biome and terrain restrictions");
fos.println("# " + CONFIG_MOBTOWOLF_IGNORE_TERRAIN + ": true");
fos.println("# (Optional) Make non-angry (wild) wolf spawns from mob spawns, at given rate (in TENTHS of a percent) - make wolves more common");
fos.println(CONFIG_MOBTOWILDWOLF_RATE + ": 10");
fos.println("# (Optional) Spawn wolf pup when wolf kills sheep (rate in percent)");
fos.println("# " + CONFIG_PUPS_ON_SHEEP_KILL_RATE + ": 10");
fos.println("# If defined, can also have a 'full moon night' one out of every days-per-moon");
fos.println("# During this, anger-rate-fullmoon percent of non-tame wolves go angry");
fos.println("# At the end of the full moon, fullmoon-stay-angry-rate percent of angry wolves stay angry");
fos.println(CONFIG_DAYSPERMOON + ": 28");
fos.println(CONFIG_ANGERRATE_MOON +": 25");
fos.println(CONFIG_FULLMOONMSG + ": The wolves are baying at the full moon ...");
fos.println(CONFIG_FULLMOON_STAY_ANGRY_RATE + ": 0");
fos.println("# Optional - mob-to-wolf-rate to apply during full moon (if set - otherwise, same rate used)");
fos.println("# " + CONFIG_FULLMOON_MOBTOWOLF_RATE + ": 50");
fos.println("# Optional spawn message");
fos.println("# spawnmsg: There's a bad moon on the rise...");
fos.println("# Also, optional spawn message radius - limits message to only players within given number of blocks of spawn");
fos.println("# spawnmsgradius: 50");
fos.println("# Wolf-in-sheeps-clothing rate : in 10ths of a percent");
fos.println(CONFIG_WOLFINSHEEP_RATE + ": 0");
fos.println(CONFIG_WOLFINSHEEP_MSG + ": Oh, no! A wolf in sheep's clothing!");
fos.println("# Optional - enable 'wolf-friends' : players with the 'angrywolves.wolf-friend' privilege will not be targetted by angry wolves!");
fos.println("# wolf-friends: true");
fos.println("# Optional - enable wolf loot - wolf-loot-rate is percent change of drop, wolf-loot is list of item ids to select from (1 randomly picked), wolf-xp is experience orbs dropped");
fos.println("# " + CONFIG_WOLFLOOT_RATE + ": 20");
fos.println("# " + CONFIG_WOLFLOOT + ": [ 334, 352, 319 ]");
fos.println("# " + CONFIG_WOLFXP + ": 5");
fos.println("# Optional - enable different loot for angry wolves (if not defined, wolf loot settings are used)");
fos.println("# " + CONFIG_ANGRYWOLFLOOT_RATE + ": 70");
fos.println("# " + CONFIG_ANGRYWOLFLOOT + ": [ 334, 352, 319 ]");
fos.println("# " + CONFIG_ANGRYWOLFXP + ": 5");
fos.println("# Optional - enable different loot for hellhounds (if not defined, wolf loot settings are used)");
fos.println("# " + CONFIG_HELLHOUNDLOOT_RATE + ": 90");
fos.println("# " + CONFIG_HELLHOUNDLOOT + ": [ 334, 352, 319 ]");
fos.println("# " + CONFIG_HELLHOUNDXP + ": 10");
fos.println("# Population limit for Angry Wolves and Hellhounds (combined for server)");
fos.println("anygrywolf-pop-limit: 200");
fos.println("# Angry Wolf initial health - normal wild wolves are 8, tamed wolves are 20");
fos.println("angrywolf-health: 8");
fos.println("# Hellhound initial health - normal wild wolves are 8, tamed wolves are 20");
fos.println("hellhound-health: 10");
fos.println("# Hellhound damage scale - multiplier for general damage to hellhounds (less that 1.0 reduces damage done to them)");
fos.println("hellhound-damagescale: 0.5");
fos.println("# (optional) have hellhounds shoot fireballs! Control range, rate (seconds between shots), and whether they cause fires");
fos.println("#hellhound-fireball-range: 10");
fos.println("#hellhound-fireball-rate: 3");
fos.println("#hellhound-fireball-incendiary: false");
fos.println("# For multi-world specific rates, fill in rate under section for each world");
fos.println("worlds:");
fos.println("# - name: world");
fos.println("# " + CONFIG_SPAWN_ANGERRATE + ": 10");
fos.println("# " + CONFIG_MOBTOWOLF_RATE + ": 0");
fos.println("# " + CONFIG_DAYSPERMOON + ": 0");
fos.println("# - name: transylvania");
fos.println("# " + CONFIG_SPAWN_ANGERRATE + ": 90");
fos.println("# " + CONFIG_MOBTOWOLF_RATE + ": 100");
fos.println("# spawnmsg: Something evil has entered the world...");
fos.println("# Optional - for special settings limited to an area on one world");
fos.println("# 'coords' define the area, as a list of two or more coordinate values (each of which has an x and z attribute).");
fos.println("areas:");
fos.println("# - name: Area51");
fos.println("# worldname: world");
fos.println("# coords:");
fos.println("# - x: 200");
fos.println("# z: 40");
fos.println("# - x: 60");
fos.println("# z: 100");
fos.println("# " + CONFIG_SPAWN_ANGERRATE + ": 100");
fos.println("# " + CONFIG_MOBTOWOLF_RATE + ": 100");
fos.close();
} catch (IOException iox) {
log.severe("ERROR writing default configuration for AngryWolves");
return;
}
}
cfg.load(); /* Load it */
boolean dirty = false;
/* Load default world-level configuration */
def_config = new WorldConfig(null); /* Make base default object */
def_config.loadConfiguration(cfg);
//log.info("defconfig: " + def_config);
verbose = cfg.getBoolean("verbose", false);
poplimit = cfg.getInt(CONFIG_ANYGYWOLF_POPLIMIT, ANGRYWOLF_POPLIMIT);
hellhound_dmgscale = cfg.getDouble(CONFIG_HELLHOUND_DAMAGESCALE, HELLHOUND_DMGSCALE);
if(hellhound_dmgscale < 0) hellhound_dmgscale = 0.0;
hellhound_health = cfg.getInt(CONFIG_HELLHOUND_HEALTH, HELLHOUND_HEALTH);
if(hellhound_health < 1) hellhound_health = 1;
angrywolf_health = cfg.getInt(CONFIG_ANGRYWOLF_HEALTH, ANGRYWOLF_HEALTH);
if(angrywolf_health < 1) angrywolf_health = 1;
/* Now, process world-specific overrides */
List<ConfigurationNode> w = cfg.getNodeList("worlds", null);
if(w != null) {
for(ConfigurationNode world : w) {
String wname = world.getString("name"); /* Get name */
if(wname == null)
continue;
/* Load/initialize per world state/config */
PerWorldState pws = getState(wname);
pws.par = def_config; /* Our parent is global default */
/* Now load settings */
pws.loadConfiguration(world);
//log.info("world " + wname + ": " + pws);
}
}
/* Now, process area-specific overrides */
w = cfg.getNodeList("areas", null);
if(w != null) {
for(ConfigurationNode area : w) {
String aname = area.getString("name"); /* Get name */
if(aname == null)
continue;
String wname = area.getString("worldname"); /* Get world name */
if(wname == null)
continue;
PerWorldState pws = getState(wname); /* Look up world state */
/* Now, make our area state */
AreaConfig ac = new AreaConfig(aname, pws);
if(pws.areas == null) pws.areas = new ArrayList<AreaConfig>();
pws.areas.add(ac); /* Add us to our world */
/* Now load settings */
ac.loadConfiguration(area);
//log.info("area " + aname + "/" + wname + ": " + ac);
}
}
if(dirty) { /* If updated, save it */
cfg.save();
}
}
| private void readConfig() {
File configdir = getDataFolder(); /* Get our data folder */
if(configdir.exists() == false) { /* Not yet defined? */
configdir.mkdirs(); /* Create it */
}
File configfile = new File(configdir, "AngryWolves.yml"); /* Our YML file */
Configuration cfg = new Configuration(configfile);
if(configfile.exists() == false) { /* Not defined yet? */
PrintWriter fos = null;
try {
fos = new PrintWriter(new FileWriter(configfile));
fos.println("# Configuration file for AngryWolves);");
fos.println("# spawn-anger-rate is percentage of normal wolf spawns that spawn angry");
fos.println("# If undefined, spawn-anger-rate defaults to 0");
fos.println(CONFIG_SPAWN_ANGERRATE + ": 5");
fos.println("# hellhound-rate is percentage of angry wolfs that are hellhounds (flaming-fireproof-wolves)");
fos.println("# If undefined, hellhound-rate defaults to 10. In Nether, 100% of angry wolves are hellhounds.");
fos.println(CONFIG_HELLHOUND_RATE + ": 10");
fos.println("# mob-to-wolf-rate is the TENTHS of a percent of monster spawns that are replaced with angry wolves");
fos.println("# spider-to-wolf-rate is the TENTHS of a percent of spider spawns that are replaced with angry wolves");
fos.println("# zombie-to-wolf-rate is the TENTHS of a percent of zombie spawns that are replaced with angry wolves");
fos.println("# skeleton-to-wolf-rate is the TENTHS of a percent of skeleton spawns that are replaced with angry wolves");
fos.println("# creeper-to-wolf-rate is the TENTHS of a percent of creeper spawns that are replaced with angry wolves");
fos.println("# pig-zombie-to-wolf-rate is the TENTHS of a percent of pig-zombie spawns that are replaced with angry wolves");
fos.println("# note: if monster type specific rate is defined, it supercedes the mob-to-wolf-rate for that monster type");
fos.println("# If undefined, mob-to-wolf-rate defaults to 10, others are null");
fos.println(CONFIG_MOBTOWOLF_RATE + ": 10");
fos.println("# " + CONFIG_SPIDERTOWOLF_RATE + ": 20");
fos.println("# " + CONFIG_ZOMBIETOWOLF_RATE + ": 0");
fos.println("# " + CONFIG_SKELETONTOWOLF_RATE + ": 5");
fos.println("# " + CONFIG_CREEPERTOWOLF_RATE + ": 1000");
fos.println("# " + CONFIG_PIGZOMBIETOWOLF_RATE + ": 20");
fos.println("# mob-to-spawn-based spawns are normally limited to spawns occuring in valid biomes for wolves, as well as over valid wolf spawn terrain (grass)");
fos.println("# " + CONFIG_MOBTOWOLF_IGNORE_TERRAIN + " can be set to 'true' to disable biome and terrain restrictions");
fos.println("# " + CONFIG_MOBTOWOLF_IGNORE_TERRAIN + ": true");
fos.println("# (Optional) Make non-angry (wild) wolf spawns from mob spawns, at given rate (in TENTHS of a percent) - make wolves more common");
fos.println(CONFIG_MOBTOWILDWOLF_RATE + ": 10");
fos.println("# (Optional) Spawn wolf pup when wolf kills sheep (rate in percent)");
fos.println("# " + CONFIG_PUPS_ON_SHEEP_KILL_RATE + ": 10");
fos.println("# If defined, can also have a 'full moon night' one out of every days-per-moon");
fos.println("# During this, anger-rate-fullmoon percent of non-tame wolves go angry");
fos.println("# At the end of the full moon, fullmoon-stay-angry-rate percent of angry wolves stay angry");
fos.println(CONFIG_DAYSPERMOON + ": 28");
fos.println(CONFIG_ANGERRATE_MOON +": 25");
fos.println(CONFIG_FULLMOONMSG + ": The wolves are baying at the full moon ...");
fos.println(CONFIG_FULLMOON_STAY_ANGRY_RATE + ": 0");
fos.println("# Optional - mob-to-wolf-rate to apply during full moon (if set - otherwise, same rate used)");
fos.println("# " + CONFIG_FULLMOON_MOBTOWOLF_RATE + ": 50");
fos.println("# Optional spawn message");
fos.println("# spawnmsg: There's a bad moon on the rise...");
fos.println("# Also, optional spawn message radius - limits message to only players within given number of blocks of spawn");
fos.println("# " + CONFIG_SPAWNMSGRADIUS + ": 50");
fos.println("# Wolf-in-sheeps-clothing rate : in 10ths of a percent");
fos.println(CONFIG_WOLFINSHEEP_RATE + ": 0");
fos.println(CONFIG_WOLFINSHEEP_MSG + ": Oh, no! A wolf in sheep's clothing!");
fos.println("# Optional - enable 'wolf-friends' : players with the 'angrywolves.wolf-friend' privilege will not be targetted by angry wolves!");
fos.println("# " + CONFIG_WOLFFRIEND + ": true");
fos.println("# Optional - enable wolf loot - wolf-loot-rate is percent change of drop, wolf-loot is list of item ids to select from (1 randomly picked), wolf-xp is experience orbs dropped");
fos.println("# " + CONFIG_WOLFLOOT_RATE + ": 20");
fos.println("# " + CONFIG_WOLFLOOT + ": [ 334, 352, 319 ]");
fos.println("# " + CONFIG_WOLFXP + ": 5");
fos.println("# Optional - enable different loot for angry wolves (if not defined, wolf loot settings are used)");
fos.println("# " + CONFIG_ANGRYWOLFLOOT_RATE + ": 70");
fos.println("# " + CONFIG_ANGRYWOLFLOOT + ": [ 334, 352, 319 ]");
fos.println("# " + CONFIG_ANGRYWOLFXP + ": 5");
fos.println("# Optional - enable different loot for hellhounds (if not defined, wolf loot settings are used)");
fos.println("# " + CONFIG_HELLHOUNDLOOT_RATE + ": 90");
fos.println("# " + CONFIG_HELLHOUNDLOOT + ": [ 334, 352, 319 ]");
fos.println("# " + CONFIG_HELLHOUNDXP + ": 10");
fos.println("# Population limit for Angry Wolves and Hellhounds (combined for server)");
fos.println(CONFIG_ANYGYWOLF_POPLIMIT + ": 200");
fos.println("# Angry Wolf initial health - normal wild wolves are 8, tamed wolves are 20");
fos.println(CONFIG_ANGRYWOLF_HEALTH + ": 8");
fos.println("# Hellhound initial health - normal wild wolves are 8, tamed wolves are 20");
fos.println(CONFIG_HELLHOUND_HEALTH + ": 10");
fos.println("# Hellhound damage scale - multiplier for general damage to hellhounds (less that 1.0 reduces damage done to them)");
fos.println(CONFIG_HELLHOUND_DAMAGESCALE + ": 0.5");
fos.println("# (optional) have hellhounds shoot fireballs! Control range, rate (seconds between shots), and whether they cause fires");
fos.println("# " + CONFIG_HELLHOUND_FIREBALL_RANGE + ": 10");
fos.println("# " + CONFIG_HELLHOUND_FIREBALL_RATE + ": 3");
fos.println("#hellhound-fireball-incendiary: false");
fos.println("# For multi-world specific rates, fill in rate under section for each world");
fos.println("worlds:");
fos.println("# - name: world");
fos.println("# " + CONFIG_SPAWN_ANGERRATE + ": 10");
fos.println("# " + CONFIG_MOBTOWOLF_RATE + ": 0");
fos.println("# " + CONFIG_DAYSPERMOON + ": 0");
fos.println("# - name: transylvania");
fos.println("# " + CONFIG_SPAWN_ANGERRATE + ": 90");
fos.println("# " + CONFIG_MOBTOWOLF_RATE + ": 100");
fos.println("# spawnmsg: Something evil has entered the world...");
fos.println("# Optional - for special settings limited to an area on one world");
fos.println("# 'coords' define the area, as a list of two or more coordinate values (each of which has an x and z attribute).");
fos.println("areas:");
fos.println("# - name: Area51");
fos.println("# worldname: world");
fos.println("# coords:");
fos.println("# - x: 200");
fos.println("# z: 40");
fos.println("# - x: 60");
fos.println("# z: 100");
fos.println("# " + CONFIG_SPAWN_ANGERRATE + ": 100");
fos.println("# " + CONFIG_MOBTOWOLF_RATE + ": 100");
fos.close();
} catch (IOException iox) {
log.severe("ERROR writing default configuration for AngryWolves");
return;
}
}
cfg.load(); /* Load it */
boolean dirty = false;
/* Load default world-level configuration */
def_config = new WorldConfig(null); /* Make base default object */
def_config.loadConfiguration(cfg);
//log.info("defconfig: " + def_config);
verbose = cfg.getBoolean("verbose", false);
poplimit = cfg.getInt(CONFIG_ANYGYWOLF_POPLIMIT, ANGRYWOLF_POPLIMIT);
hellhound_dmgscale = cfg.getDouble(CONFIG_HELLHOUND_DAMAGESCALE, HELLHOUND_DMGSCALE);
if(hellhound_dmgscale < 0) hellhound_dmgscale = 0.0;
hellhound_health = cfg.getInt(CONFIG_HELLHOUND_HEALTH, HELLHOUND_HEALTH);
if(hellhound_health < 1) hellhound_health = 1;
angrywolf_health = cfg.getInt(CONFIG_ANGRYWOLF_HEALTH, ANGRYWOLF_HEALTH);
if(angrywolf_health < 1) angrywolf_health = 1;
/* Now, process world-specific overrides */
List<ConfigurationNode> w = cfg.getNodeList("worlds", null);
if(w != null) {
for(ConfigurationNode world : w) {
String wname = world.getString("name"); /* Get name */
if(wname == null)
continue;
/* Load/initialize per world state/config */
PerWorldState pws = getState(wname);
pws.par = def_config; /* Our parent is global default */
/* Now load settings */
pws.loadConfiguration(world);
//log.info("world " + wname + ": " + pws);
}
}
/* Now, process area-specific overrides */
w = cfg.getNodeList("areas", null);
if(w != null) {
for(ConfigurationNode area : w) {
String aname = area.getString("name"); /* Get name */
if(aname == null)
continue;
String wname = area.getString("worldname"); /* Get world name */
if(wname == null)
continue;
PerWorldState pws = getState(wname); /* Look up world state */
/* Now, make our area state */
AreaConfig ac = new AreaConfig(aname, pws);
if(pws.areas == null) pws.areas = new ArrayList<AreaConfig>();
pws.areas.add(ac); /* Add us to our world */
/* Now load settings */
ac.loadConfiguration(area);
//log.info("area " + aname + "/" + wname + ": " + ac);
}
}
if(dirty) { /* If updated, save it */
cfg.save();
}
}
|
diff --git a/pact/pact-examples/src/main/java/eu/stratosphere/pact/example/relational/TPCHQuery3.java b/pact/pact-examples/src/main/java/eu/stratosphere/pact/example/relational/TPCHQuery3.java
index 10f96c3a3..4ba1623d0 100644
--- a/pact/pact-examples/src/main/java/eu/stratosphere/pact/example/relational/TPCHQuery3.java
+++ b/pact/pact-examples/src/main/java/eu/stratosphere/pact/example/relational/TPCHQuery3.java
@@ -1,342 +1,341 @@
/***********************************************************************************************************************
*
* Copyright (C) 2010 by the Stratosphere project (http://stratosphere.eu)
*
* 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 eu.stratosphere.pact.example.relational;
import java.util.Iterator;
import org.apache.log4j.Logger;
import eu.stratosphere.pact.common.contract.DataSinkContract;
import eu.stratosphere.pact.common.contract.DataSourceContract;
import eu.stratosphere.pact.common.contract.MapContract;
import eu.stratosphere.pact.common.contract.MatchContract;
import eu.stratosphere.pact.common.contract.ReduceContract;
import eu.stratosphere.pact.common.contract.OutputContract.SameKey;
import eu.stratosphere.pact.common.contract.OutputContract.SuperKey;
import eu.stratosphere.pact.common.contract.OutputContract.UniqueKey;
import eu.stratosphere.pact.common.contract.ReduceContract.Combinable;
import eu.stratosphere.pact.common.plan.Plan;
import eu.stratosphere.pact.common.plan.PlanAssembler;
import eu.stratosphere.pact.common.plan.PlanAssemblerDescription;
import eu.stratosphere.pact.common.stub.Collector;
import eu.stratosphere.pact.common.stub.MapStub;
import eu.stratosphere.pact.common.stub.MatchStub;
import eu.stratosphere.pact.common.stub.ReduceStub;
import eu.stratosphere.pact.common.type.base.PactInteger;
import eu.stratosphere.pact.common.type.base.PactPair;
import eu.stratosphere.pact.common.type.base.PactString;
import eu.stratosphere.pact.example.relational.util.IntTupleDataInFormat;
import eu.stratosphere.pact.example.relational.util.StringTupleDataOutFormat;
import eu.stratosphere.pact.example.relational.util.Tuple;
/**
* The TPC-H is a decision support benchmark on relational data.
* Its documentation and the data generator (DBGEN) can be found
* on http://www.tpc.org/tpch/ .This implementation is tested with
* the DB2 data format.
* THe PACT program implements a modified version of the query 3 of
* the TPC-H benchmark including one join, some filtering and an
* aggregation.
*
* SELECT l_orderkey, o_shippriority, sum(l_extendedprice) as revenue
* FROM orders, lineitem
* WHERE l_orderkey = o_orderkey
* AND o_orderstatus = "X"
* AND YEAR(o_orderdate) > Y
* AND o_orderpriority LIKE "Z%"
* GROUP BY l_orderkey, o_shippriority;
*/
public class TPCHQuery3 implements PlanAssembler, PlanAssemblerDescription {
private static Logger LOGGER = Logger.getLogger(TPCHQuery3.class);
/**
* Concatenation of Integer and String. Used for concatenation of keys
* after join (ORDERKEY, SHIPPRIORITY)
*/
public static class N_IntStringPair extends PactPair<PactInteger, PactString> {
/**
* Initializes a blank pair. Required for deserialization
*/
public N_IntStringPair() {
super();
}
/**
* Initializes the concatenation of integer and string.
*
* @param first Integer value for concatenating
* @param second String value for concatenating
*/
public N_IntStringPair(PactInteger first, PactString second) {
super(first, second);
}
}
/**
* Map PACT implements the filter on the orders table. The SameKey
* OutputContract is annotated because the key does not change during
* filtering.
*
*/
@SameKey
public static class FilterO extends MapStub<PactInteger, Tuple, PactInteger, Tuple> {
private final int YEAR_FILTER = 1993;
private final String PRIO_FILTER = "5";
/**
* Filters the orders table by year, orderstatus and orderpriority
*
* o_orderstatus = "X"
* AND YEAR(o_orderdate) > Y
* AND o_orderpriority LIKE "Z"
*
* Output Schema:
* Key: ORDERKEY
* Value: 0:ORDERKEY, 1:SHIPPRIORITY
*/
@Override
public void map(final PactInteger oKey, final Tuple value, final Collector<PactInteger, Tuple> out) {
try {
if (Integer.parseInt(value.getStringValueAt(4).substring(0, 4)) > this.YEAR_FILTER
&& value.getStringValueAt(2).equals("F") && value.getStringValueAt(5).startsWith(this.PRIO_FILTER)) {
// project
value.project(129);
out.collect(oKey, value);
// Output Schema:
// KEY: ORDERKEY
// VALUE: 0:ORDERKEY, 1:SHIPPRIORITY
}
} catch (final StringIndexOutOfBoundsException e) {
LOGGER.error(e);
} catch (final Exception ex) {
LOGGER.error(ex);
}
}
}
/**
* Map PACT implements the projection on the LineItem table. The SameKey
* OutputContract is annotated because the key does not change during
* projection.
*
*/
@SameKey
public static class ProjectLi extends MapStub<PactInteger, Tuple, PactInteger, Tuple> {
/**
* Does the projection on the LineItem table
*
* Output Schema:
* Key: ORDERKEY
* Value: 0:ORDERKEY, 1:EXTENDEDPRICE
*/
@Override
public void map(PactInteger oKey, Tuple value, Collector<PactInteger, Tuple> out) {
value.project(33);
out.collect(oKey, value);
}
}
/**
* Match PACT realizes the join between LineItem and Order table. The
* SuperKey OutputContract is annotated because the new key is
* built of the keys of the inputs.
*
*/
@SuperKey
public static class JoinLiO extends MatchStub<PactInteger, Tuple, Tuple, N_IntStringPair, Tuple> {
/**
* Implements the join between LineItem and Order table on the
* order key.
*
* WHERE l_orderkey = o_orderkey
*
* Output Schema:
* Key: ORDERKEY, SHIPPRIORITY
* Value: 0:ORDERKEY, 1:SHIPPRIORITY, 2:EXTENDEDPRICE
*/
@Override
public void match(PactInteger oKey, Tuple oVal, Tuple liVal, Collector<N_IntStringPair, Tuple> out) {
oVal.concatenate(liVal);
oVal.project(11);
N_IntStringPair superKey = new N_IntStringPair(oKey, new PactString(oVal.getStringValueAt(1)));
out.collect(superKey, oVal);
}
}
/**
* Reduce PACT implements the aggregation of the results. The
* Combinable annotation is set as the partial sums can be calculated
* already in the combiner
*
*/
@Combinable
public static class AggLiO extends ReduceStub<N_IntStringPair, Tuple, PactInteger, Tuple> {
/**
* Does the aggregation of the query.
*
* sum(l_extendedprice) as revenue
* GROUP BY l_orderkey, o_shippriority;
*
* Output Schema:
* Key: ORDERKEY
* Value: 0:ORDERKEY, 1:SHIPPRIORITY, 2:EXTENDEDPRICESUM
*
*/
@Override
public void reduce(N_IntStringPair oKeyShipPrio, Iterator<Tuple> values, Collector<PactInteger, Tuple> out) {
long partExtendedPriceSum = 0;
Tuple value = null;
while (values.hasNext()) {
value = values.next();
partExtendedPriceSum += ((long) Double.parseDouble(value.getStringValueAt(2)));
}
if (value != null) {
value.project(3);
value.addAttribute(partExtendedPriceSum + "");
out.collect(oKeyShipPrio.getFirst(), value);
}
}
/**
* Creates partial sums on the price attribute for each data batch
*/
@Override
public void combine(N_IntStringPair oKeyShipPrio, Iterator<Tuple> values, Collector<N_IntStringPair, Tuple> out) {
long partExtendedPriceSum = 0;
Tuple value = null;
while (values.hasNext()) {
value = values.next();
partExtendedPriceSum += ((long) Double.parseDouble(value.getStringValueAt(2)));
}
if (value != null) {
value.project(3);
value.addAttribute(partExtendedPriceSum + "");
out.collect(oKeyShipPrio, value);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public Plan getPlan(final String... args) {
// parse program parameters
int noSubtasks = (args.length > 0 ? Integer.parseInt(args[0]) : 1);
String ordersPath = (args.length > 1 ? args[1] : "");
String lineitemsPath = (args.length > 2 ? args[2] : "");
String output = (args.length > 3 ? args[3] : "");
// create DataSourceContract for Orders input
DataSourceContract<PactInteger, Tuple> orders = new DataSourceContract<PactInteger, Tuple>(
IntTupleDataInFormat.class, ordersPath, "Orders");
orders.setFormatParameter("delimiter", "\n");
orders.setDegreeOfParallelism(noSubtasks);
orders.setOutputContract(UniqueKey.class);
orders.getCompilerHints().setAvgNumValuesPerKey(1);
// create DataSourceContract for LineItems input
DataSourceContract<PactInteger, Tuple> lineitems = new DataSourceContract<PactInteger, Tuple>(
IntTupleDataInFormat.class, lineitemsPath, "LineItems");
lineitems.setFormatParameter("delimiter", "\n");
lineitems.setDegreeOfParallelism(noSubtasks);
lineitems.getCompilerHints().setAvgNumValuesPerKey(4);
// create MapContract for filtering Orders tuples
MapContract<PactInteger, Tuple, PactInteger, Tuple> filterO = new MapContract<PactInteger, Tuple, PactInteger, Tuple>(
FilterO.class, "FilterO");
filterO.setDegreeOfParallelism(noSubtasks);
filterO.getCompilerHints().setAvgBytesPerRecord(32);
filterO.getCompilerHints().setAvgRecordsEmittedPerStubCall(0.05f);
filterO.getCompilerHints().setAvgNumValuesPerKey(1);
// create MapContract for projecting LineItems tuples
MapContract<PactInteger, Tuple, PactInteger, Tuple> projectLi = new MapContract<PactInteger, Tuple, PactInteger, Tuple>(
ProjectLi.class, "ProjectLi");
projectLi.setDegreeOfParallelism(noSubtasks);
projectLi.getCompilerHints().setAvgBytesPerRecord(48);
projectLi.getCompilerHints().setAvgRecordsEmittedPerStubCall(1.0f);
projectLi.getCompilerHints().setAvgNumValuesPerKey(4);
// create MatchContract for joining Orders and LineItems
MatchContract<PactInteger, Tuple, Tuple, N_IntStringPair, Tuple> joinLiO = new MatchContract<PactInteger, Tuple, Tuple, N_IntStringPair, Tuple>(
JoinLiO.class, "JoinLiO");
joinLiO.setDegreeOfParallelism(noSubtasks);
- joinLiO.getCompilerHints().setAvgRecordsEmittedPerStubCall(0.05f);
joinLiO.getCompilerHints().setAvgBytesPerRecord(64);
joinLiO.getCompilerHints().setAvgNumValuesPerKey(4);
// create ReduceContract for aggregating the result
ReduceContract<N_IntStringPair, Tuple, PactInteger, Tuple> aggLiO = new ReduceContract<N_IntStringPair, Tuple, PactInteger, Tuple>(
AggLiO.class, "AggLio");
aggLiO.setDegreeOfParallelism(noSubtasks);
aggLiO.getCompilerHints().setAvgBytesPerRecord(64);
aggLiO.getCompilerHints().setAvgRecordsEmittedPerStubCall(1.0f);
aggLiO.getCompilerHints().setAvgNumValuesPerKey(1);
// create DataSinkContract for writing the result
DataSinkContract<PactString, Tuple> result = new DataSinkContract<PactString, Tuple>(
StringTupleDataOutFormat.class, output, "Output");
result.setDegreeOfParallelism(noSubtasks);
// assemble the PACT plan
result.setInput(aggLiO);
aggLiO.setInput(joinLiO);
joinLiO.setFirstInput(filterO);
filterO.setInput(orders);
joinLiO.setSecondInput(projectLi);
projectLi.setInput(lineitems);
// return the PACT plan
return new Plan(result, "TPCH Q3");
}
/**
* {@inheritDoc}
*/
@Override
public String getDescription() {
return "Parameters: [noSubStasks], [orders], [lineitem], [output]";
}
}
| true | true | public Plan getPlan(final String... args) {
// parse program parameters
int noSubtasks = (args.length > 0 ? Integer.parseInt(args[0]) : 1);
String ordersPath = (args.length > 1 ? args[1] : "");
String lineitemsPath = (args.length > 2 ? args[2] : "");
String output = (args.length > 3 ? args[3] : "");
// create DataSourceContract for Orders input
DataSourceContract<PactInteger, Tuple> orders = new DataSourceContract<PactInteger, Tuple>(
IntTupleDataInFormat.class, ordersPath, "Orders");
orders.setFormatParameter("delimiter", "\n");
orders.setDegreeOfParallelism(noSubtasks);
orders.setOutputContract(UniqueKey.class);
orders.getCompilerHints().setAvgNumValuesPerKey(1);
// create DataSourceContract for LineItems input
DataSourceContract<PactInteger, Tuple> lineitems = new DataSourceContract<PactInteger, Tuple>(
IntTupleDataInFormat.class, lineitemsPath, "LineItems");
lineitems.setFormatParameter("delimiter", "\n");
lineitems.setDegreeOfParallelism(noSubtasks);
lineitems.getCompilerHints().setAvgNumValuesPerKey(4);
// create MapContract for filtering Orders tuples
MapContract<PactInteger, Tuple, PactInteger, Tuple> filterO = new MapContract<PactInteger, Tuple, PactInteger, Tuple>(
FilterO.class, "FilterO");
filterO.setDegreeOfParallelism(noSubtasks);
filterO.getCompilerHints().setAvgBytesPerRecord(32);
filterO.getCompilerHints().setAvgRecordsEmittedPerStubCall(0.05f);
filterO.getCompilerHints().setAvgNumValuesPerKey(1);
// create MapContract for projecting LineItems tuples
MapContract<PactInteger, Tuple, PactInteger, Tuple> projectLi = new MapContract<PactInteger, Tuple, PactInteger, Tuple>(
ProjectLi.class, "ProjectLi");
projectLi.setDegreeOfParallelism(noSubtasks);
projectLi.getCompilerHints().setAvgBytesPerRecord(48);
projectLi.getCompilerHints().setAvgRecordsEmittedPerStubCall(1.0f);
projectLi.getCompilerHints().setAvgNumValuesPerKey(4);
// create MatchContract for joining Orders and LineItems
MatchContract<PactInteger, Tuple, Tuple, N_IntStringPair, Tuple> joinLiO = new MatchContract<PactInteger, Tuple, Tuple, N_IntStringPair, Tuple>(
JoinLiO.class, "JoinLiO");
joinLiO.setDegreeOfParallelism(noSubtasks);
joinLiO.getCompilerHints().setAvgRecordsEmittedPerStubCall(0.05f);
joinLiO.getCompilerHints().setAvgBytesPerRecord(64);
joinLiO.getCompilerHints().setAvgNumValuesPerKey(4);
// create ReduceContract for aggregating the result
ReduceContract<N_IntStringPair, Tuple, PactInteger, Tuple> aggLiO = new ReduceContract<N_IntStringPair, Tuple, PactInteger, Tuple>(
AggLiO.class, "AggLio");
aggLiO.setDegreeOfParallelism(noSubtasks);
aggLiO.getCompilerHints().setAvgBytesPerRecord(64);
aggLiO.getCompilerHints().setAvgRecordsEmittedPerStubCall(1.0f);
aggLiO.getCompilerHints().setAvgNumValuesPerKey(1);
// create DataSinkContract for writing the result
DataSinkContract<PactString, Tuple> result = new DataSinkContract<PactString, Tuple>(
StringTupleDataOutFormat.class, output, "Output");
result.setDegreeOfParallelism(noSubtasks);
// assemble the PACT plan
result.setInput(aggLiO);
aggLiO.setInput(joinLiO);
joinLiO.setFirstInput(filterO);
filterO.setInput(orders);
joinLiO.setSecondInput(projectLi);
projectLi.setInput(lineitems);
// return the PACT plan
return new Plan(result, "TPCH Q3");
}
| public Plan getPlan(final String... args) {
// parse program parameters
int noSubtasks = (args.length > 0 ? Integer.parseInt(args[0]) : 1);
String ordersPath = (args.length > 1 ? args[1] : "");
String lineitemsPath = (args.length > 2 ? args[2] : "");
String output = (args.length > 3 ? args[3] : "");
// create DataSourceContract for Orders input
DataSourceContract<PactInteger, Tuple> orders = new DataSourceContract<PactInteger, Tuple>(
IntTupleDataInFormat.class, ordersPath, "Orders");
orders.setFormatParameter("delimiter", "\n");
orders.setDegreeOfParallelism(noSubtasks);
orders.setOutputContract(UniqueKey.class);
orders.getCompilerHints().setAvgNumValuesPerKey(1);
// create DataSourceContract for LineItems input
DataSourceContract<PactInteger, Tuple> lineitems = new DataSourceContract<PactInteger, Tuple>(
IntTupleDataInFormat.class, lineitemsPath, "LineItems");
lineitems.setFormatParameter("delimiter", "\n");
lineitems.setDegreeOfParallelism(noSubtasks);
lineitems.getCompilerHints().setAvgNumValuesPerKey(4);
// create MapContract for filtering Orders tuples
MapContract<PactInteger, Tuple, PactInteger, Tuple> filterO = new MapContract<PactInteger, Tuple, PactInteger, Tuple>(
FilterO.class, "FilterO");
filterO.setDegreeOfParallelism(noSubtasks);
filterO.getCompilerHints().setAvgBytesPerRecord(32);
filterO.getCompilerHints().setAvgRecordsEmittedPerStubCall(0.05f);
filterO.getCompilerHints().setAvgNumValuesPerKey(1);
// create MapContract for projecting LineItems tuples
MapContract<PactInteger, Tuple, PactInteger, Tuple> projectLi = new MapContract<PactInteger, Tuple, PactInteger, Tuple>(
ProjectLi.class, "ProjectLi");
projectLi.setDegreeOfParallelism(noSubtasks);
projectLi.getCompilerHints().setAvgBytesPerRecord(48);
projectLi.getCompilerHints().setAvgRecordsEmittedPerStubCall(1.0f);
projectLi.getCompilerHints().setAvgNumValuesPerKey(4);
// create MatchContract for joining Orders and LineItems
MatchContract<PactInteger, Tuple, Tuple, N_IntStringPair, Tuple> joinLiO = new MatchContract<PactInteger, Tuple, Tuple, N_IntStringPair, Tuple>(
JoinLiO.class, "JoinLiO");
joinLiO.setDegreeOfParallelism(noSubtasks);
joinLiO.getCompilerHints().setAvgBytesPerRecord(64);
joinLiO.getCompilerHints().setAvgNumValuesPerKey(4);
// create ReduceContract for aggregating the result
ReduceContract<N_IntStringPair, Tuple, PactInteger, Tuple> aggLiO = new ReduceContract<N_IntStringPair, Tuple, PactInteger, Tuple>(
AggLiO.class, "AggLio");
aggLiO.setDegreeOfParallelism(noSubtasks);
aggLiO.getCompilerHints().setAvgBytesPerRecord(64);
aggLiO.getCompilerHints().setAvgRecordsEmittedPerStubCall(1.0f);
aggLiO.getCompilerHints().setAvgNumValuesPerKey(1);
// create DataSinkContract for writing the result
DataSinkContract<PactString, Tuple> result = new DataSinkContract<PactString, Tuple>(
StringTupleDataOutFormat.class, output, "Output");
result.setDegreeOfParallelism(noSubtasks);
// assemble the PACT plan
result.setInput(aggLiO);
aggLiO.setInput(joinLiO);
joinLiO.setFirstInput(filterO);
filterO.setInput(orders);
joinLiO.setSecondInput(projectLi);
projectLi.setInput(lineitems);
// return the PACT plan
return new Plan(result, "TPCH Q3");
}
|
diff --git a/src/main/java/com/matejdro/bukkit/jail/commands/JailCommand.java b/src/main/java/com/matejdro/bukkit/jail/commands/JailCommand.java
index 7ae99e3..4c723da 100644
--- a/src/main/java/com/matejdro/bukkit/jail/commands/JailCommand.java
+++ b/src/main/java/com/matejdro/bukkit/jail/commands/JailCommand.java
@@ -1,116 +1,116 @@
package com.matejdro.bukkit.jail.commands;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.matejdro.bukkit.jail.InputOutput;
import com.matejdro.bukkit.jail.Jail;
import com.matejdro.bukkit.jail.JailPrisoner;
import com.matejdro.bukkit.jail.PrisonerManager;
import com.matejdro.bukkit.jail.Setting;
import com.matejdro.bukkit.jail.Util;
public class JailCommand extends BaseCommand {
public JailCommand()
{
needPlayer = false;
adminCommand = true;
permission = "jail.command.jail";
}
public Boolean run(CommandSender sender, String[] args) {
if (args.length < 1)
{
Util.Message("Usage: /jail [Name] (time) (j:Jail name) (c:Cell name) (r:Reason) (m)", sender);
return true;
}
if (Jail.zones.size() < 1)
{
Util.Message(InputOutput.global.getString(Setting.MessageNoJail.getString()), sender);
return true;
}
//Initialize defaults
String playerName = args[0].toLowerCase();
int time = InputOutput.global.getInt(Setting.DefaultJailTime.getString());
String jailname = "";
String cellname = "";
String reason = "";
Boolean muted = InputOutput.global.getBoolean(Setting.AutomaticMute.getString());
//Parse command line
for (int i = 1; i < args.length; i++)
{
String line = args[i];
if (Util.isInteger(line))
time = Integer.parseInt(line);
else if (line.startsWith("j:"))
jailname = line.substring(2);
else if (line.startsWith("c:"))
cellname = line.substring(2);
else if (line.equals("m"))
muted = !muted;
else if (line.startsWith("r:"))
{
if (line.startsWith("r:\""))
{
reason = line.substring(3);
while (!line.endsWith("\""))
{
i++;
if (i >= args.length)
{
Util.Message("Usage: /jail [Name] (t:time) (j:Jail name) (c:Cell name) (r:Reason) (m)", sender);
return true;
}
line = args[i];
if (line.endsWith("\""))
reason += " " + line.substring(0, line.length() - 1);
else
reason += " " + line;
}
}
else reason = line.substring(2);
int maxReason = InputOutput.global.getInt(Setting.MaximumReasonLength.getString());
if (maxReason > 250) maxReason = 250; //DB Limit
if (reason.length() > maxReason)
{
Util.Message(InputOutput.global.getString(Setting.MessageTooLongReason.getString()), sender);
return true;
}
}
}
Player player = Util.getPlayer(playerName, true);
if (player == null && !Util.playerExists(playerName))
{
- Util.Message(InputOutput.global.getString(Setting.MessageNoJail.getString()).replace("<Player>", playerName), sender);
+ Util.Message(InputOutput.global.getString(Setting.MessageNeverOnThisServer.getString()).replace("<Player>", playerName), sender);
return true;
}
else if (player != null) playerName = player.getName().toLowerCase();
JailPrisoner prisoner = new JailPrisoner(playerName, time * 6, jailname, cellname, false, "", reason, muted, "", sender instanceof Player ? ((Player) sender).getName() : "console", "");
PrisonerManager.PrepareJail(prisoner, player);
String message;
if (player == null)
message = InputOutput.global.getString(Setting.MessagePrisonerOffline.getString());
else
message = InputOutput.global.getString(Setting.MessagePrisonerJailed.getString());
message = prisoner.parseTags(message);
Util.Message(message, sender);
return true;
}
}
| true | true | public Boolean run(CommandSender sender, String[] args) {
if (args.length < 1)
{
Util.Message("Usage: /jail [Name] (time) (j:Jail name) (c:Cell name) (r:Reason) (m)", sender);
return true;
}
if (Jail.zones.size() < 1)
{
Util.Message(InputOutput.global.getString(Setting.MessageNoJail.getString()), sender);
return true;
}
//Initialize defaults
String playerName = args[0].toLowerCase();
int time = InputOutput.global.getInt(Setting.DefaultJailTime.getString());
String jailname = "";
String cellname = "";
String reason = "";
Boolean muted = InputOutput.global.getBoolean(Setting.AutomaticMute.getString());
//Parse command line
for (int i = 1; i < args.length; i++)
{
String line = args[i];
if (Util.isInteger(line))
time = Integer.parseInt(line);
else if (line.startsWith("j:"))
jailname = line.substring(2);
else if (line.startsWith("c:"))
cellname = line.substring(2);
else if (line.equals("m"))
muted = !muted;
else if (line.startsWith("r:"))
{
if (line.startsWith("r:\""))
{
reason = line.substring(3);
while (!line.endsWith("\""))
{
i++;
if (i >= args.length)
{
Util.Message("Usage: /jail [Name] (t:time) (j:Jail name) (c:Cell name) (r:Reason) (m)", sender);
return true;
}
line = args[i];
if (line.endsWith("\""))
reason += " " + line.substring(0, line.length() - 1);
else
reason += " " + line;
}
}
else reason = line.substring(2);
int maxReason = InputOutput.global.getInt(Setting.MaximumReasonLength.getString());
if (maxReason > 250) maxReason = 250; //DB Limit
if (reason.length() > maxReason)
{
Util.Message(InputOutput.global.getString(Setting.MessageTooLongReason.getString()), sender);
return true;
}
}
}
Player player = Util.getPlayer(playerName, true);
if (player == null && !Util.playerExists(playerName))
{
Util.Message(InputOutput.global.getString(Setting.MessageNoJail.getString()).replace("<Player>", playerName), sender);
return true;
}
else if (player != null) playerName = player.getName().toLowerCase();
JailPrisoner prisoner = new JailPrisoner(playerName, time * 6, jailname, cellname, false, "", reason, muted, "", sender instanceof Player ? ((Player) sender).getName() : "console", "");
PrisonerManager.PrepareJail(prisoner, player);
String message;
if (player == null)
message = InputOutput.global.getString(Setting.MessagePrisonerOffline.getString());
else
message = InputOutput.global.getString(Setting.MessagePrisonerJailed.getString());
message = prisoner.parseTags(message);
Util.Message(message, sender);
return true;
}
| public Boolean run(CommandSender sender, String[] args) {
if (args.length < 1)
{
Util.Message("Usage: /jail [Name] (time) (j:Jail name) (c:Cell name) (r:Reason) (m)", sender);
return true;
}
if (Jail.zones.size() < 1)
{
Util.Message(InputOutput.global.getString(Setting.MessageNoJail.getString()), sender);
return true;
}
//Initialize defaults
String playerName = args[0].toLowerCase();
int time = InputOutput.global.getInt(Setting.DefaultJailTime.getString());
String jailname = "";
String cellname = "";
String reason = "";
Boolean muted = InputOutput.global.getBoolean(Setting.AutomaticMute.getString());
//Parse command line
for (int i = 1; i < args.length; i++)
{
String line = args[i];
if (Util.isInteger(line))
time = Integer.parseInt(line);
else if (line.startsWith("j:"))
jailname = line.substring(2);
else if (line.startsWith("c:"))
cellname = line.substring(2);
else if (line.equals("m"))
muted = !muted;
else if (line.startsWith("r:"))
{
if (line.startsWith("r:\""))
{
reason = line.substring(3);
while (!line.endsWith("\""))
{
i++;
if (i >= args.length)
{
Util.Message("Usage: /jail [Name] (t:time) (j:Jail name) (c:Cell name) (r:Reason) (m)", sender);
return true;
}
line = args[i];
if (line.endsWith("\""))
reason += " " + line.substring(0, line.length() - 1);
else
reason += " " + line;
}
}
else reason = line.substring(2);
int maxReason = InputOutput.global.getInt(Setting.MaximumReasonLength.getString());
if (maxReason > 250) maxReason = 250; //DB Limit
if (reason.length() > maxReason)
{
Util.Message(InputOutput.global.getString(Setting.MessageTooLongReason.getString()), sender);
return true;
}
}
}
Player player = Util.getPlayer(playerName, true);
if (player == null && !Util.playerExists(playerName))
{
Util.Message(InputOutput.global.getString(Setting.MessageNeverOnThisServer.getString()).replace("<Player>", playerName), sender);
return true;
}
else if (player != null) playerName = player.getName().toLowerCase();
JailPrisoner prisoner = new JailPrisoner(playerName, time * 6, jailname, cellname, false, "", reason, muted, "", sender instanceof Player ? ((Player) sender).getName() : "console", "");
PrisonerManager.PrepareJail(prisoner, player);
String message;
if (player == null)
message = InputOutput.global.getString(Setting.MessagePrisonerOffline.getString());
else
message = InputOutput.global.getString(Setting.MessagePrisonerJailed.getString());
message = prisoner.parseTags(message);
Util.Message(message, sender);
return true;
}
|
diff --git a/src/org/jaudiotagger/tag/id3/ID3v24Frame.java b/src/org/jaudiotagger/tag/id3/ID3v24Frame.java
index 174f1a16..3eeebe69 100644
--- a/src/org/jaudiotagger/tag/id3/ID3v24Frame.java
+++ b/src/org/jaudiotagger/tag/id3/ID3v24Frame.java
@@ -1,938 +1,939 @@
/*
* MusicTag Copyright (C)2003,2004
*
* 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,
* you can get a copy from http://www.opensource.org/licenses/lgpl-license.php or write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jaudiotagger.tag.id3;
import org.jaudiotagger.audio.mp3.*;
import org.jaudiotagger.tag.datatype.*;
import org.jaudiotagger.tag.lyrics3.*;
import org.jaudiotagger.tag.*;
import org.jaudiotagger.tag.id3.framebody.*;
import org.jaudiotagger.FileConstants;
import java.io.IOException;
import java.io.ByteArrayOutputStream;
import java.util.Iterator;
import java.nio.*;
/**
* Represents an ID3v2.4 frame.
*
* @author : Paul Taylor
* @author : Eric Farng
* @version $Id$
*/
public class ID3v24Frame
extends ID3v23Frame
{
protected static final int FRAME_DATA_LENGTH_SIZE =4;
protected static final int FRAME_ENCRYPTION_INDICATOR_SIZE =1;
protected static final int FRAME_GROUPING_INDICATOR_SIZE =1;
public ID3v24Frame()
{
}
/**
* Creates a new ID3v2_4Frame of type identifier. An empty
* body of the correct type will be automatically created.
* This constructor should be used when wish to create a new
* frame from scratch using user input
*
* @param identifier defines the type of body to be created
*/
public ID3v24Frame(String identifier)
{
//Super Constructor creates a frame with empty body of type specified
super(identifier);
statusFlags = new StatusFlags();
encodingFlags = new EncodingFlags();
}
/**
* Copy Constructor:Creates a new ID3v2_4Frame datatype based on another frame.
*/
public ID3v24Frame(ID3v24Frame frame)
{
super(frame);
statusFlags = new StatusFlags(((ID3v23Frame) frame).getStatusFlags().getOriginalFlags());
encodingFlags = new EncodingFlags(((ID3v23Frame) frame).getEncodingFlags().getFlags());
}
/**
* Creates a new ID3v2_4Frame datatype based on another frame of different version
* Converts the framebody to the equivalent v24 framebody or to UnsupportedFrameBody if identifier
* is unknown.
*
* @param frame to construct a new frame from
*/
public ID3v24Frame(AbstractID3v2Frame frame) throws InvalidFrameException
{
//Should not be called
if ((frame instanceof ID3v24Frame == true))
{
throw new UnsupportedOperationException("Copy Constructor not called. Please type cast the argument");
}
//Flags
if (frame instanceof ID3v23Frame)
{
statusFlags = new StatusFlags((ID3v23Frame.StatusFlags) ((ID3v23Frame) frame).getStatusFlags());
encodingFlags = new EncodingFlags(((ID3v23Frame) frame).getEncodingFlags().getFlags());
}
else
{
statusFlags = new StatusFlags();
encodingFlags = new EncodingFlags();
}
/** Convert Identifier. If the id was a known id for the original
* version we should be able to convert it to an v24 frame, although it may mean minor
* modification to the data. If it was not recognised originally it should remain
* unknown.
*/
if (frame instanceof ID3v23Frame)
{
// Is it a straight conversion e.g TALB - TALB
identifier = ID3Tags.convertFrameID23To24(frame.getIdentifier());
if (identifier != null)
{
logger.info("V3:Orig id is:" + frame.getIdentifier() + ":New id is:" + identifier);
this.frameBody = (AbstractID3v2FrameBody) ID3Tags.copyObject(frame.getBody());
this.frameBody.setHeader(this);
return;
}
// Is it a known v3 frame which needs forcing to v4 frame e.g. TYER - TDRC
else if (ID3Tags.isID3v23FrameIdentifier(frame.getIdentifier()) == true)
{
identifier = ID3Tags.forceFrameID23To24(frame.getIdentifier());
if (identifier != null)
{
logger.info("V3:Orig id is:" + frame.getIdentifier() + ":New id is:" + identifier);
this.frameBody = this.readBody(identifier, (AbstractID3v2FrameBody) frame.getBody());
this.frameBody.setHeader(this);
return;
}
// No mechanism exists to convert it to a v24 frame, e.g deprecated frame e.g TSIZ, so hold
// as a deprecated frame consisting of an array of bytes*/
else
{
this.frameBody = new FrameBodyDeprecated((AbstractID3v2FrameBody) frame.getBody());
this.frameBody.setHeader(this);
identifier = frame.getIdentifier();
logger.info("V3:Deprecated:Orig id is:" + frame.getIdentifier() + ":New id is:" + identifier);
return;
}
}
// Unknown Frame e.g NCON or TDRL (because TDRL unknown to V23)
else
{
this.frameBody = new FrameBodyUnsupported((FrameBodyUnsupported) frame.getBody());
this.frameBody.setHeader(this);
identifier = frame.getIdentifier();
logger.info("V3:Unknown:Orig id is:" + frame.getIdentifier() + ":New id is:" + identifier);
return;
}
}
else if (frame instanceof ID3v22Frame)
{
/** Is it a straight conversion from v2 to v4 (e.g TAl - TALB) */
identifier = ID3Tags.convertFrameID22To24(frame.getIdentifier());
if (identifier != null)
{
logger.info("(1)V2:Orig id is:" + frame.getIdentifier() + "New id is:" + identifier);
this.frameBody = (AbstractID3v2FrameBody) ID3Tags.copyObject(frame.getBody());
this.frameBody.setHeader(this);
return;
}
/** Can we convert from v2 to v3 easily (e.g TYE - TYER) */
identifier = ID3Tags.convertFrameID22To23(frame.getIdentifier());
if (identifier != null)
{
//Convert from v2 to v3
logger.info("(2)V2:Orig id is:" + frame.getIdentifier() + "New id is:" + identifier);
this.frameBody = (AbstractID3v2FrameBody) ID3Tags.copyObject(frame.getBody());
this.frameBody.setHeader(this);
//Force v3 to v4
identifier = ID3Tags.forceFrameID23To24(identifier);
this.frameBody = this.readBody(identifier, (AbstractID3v2FrameBody) this.getBody());
this.frameBody.setHeader(this);
return;
}
/** Is it a known v2 frame which needs forcing to v4 frame e.g PIC - APIC */
else if (ID3Tags.isID3v22FrameIdentifier(frame.getIdentifier()) == true)
{
//Force v2 to v3
identifier = ID3Tags.forceFrameID22To23(frame.getIdentifier());
if (identifier != null)
{
logger.info("(3)V2:Orig id is:" + frame.getIdentifier() + "New id is:" + identifier);
this.frameBody = this.readBody(identifier, (AbstractID3v2FrameBody) frame.getBody());
this.frameBody.setHeader(this);
return;
}
/* No mechanism exists to convert it to a v24 frame */
else
{
this.frameBody = new FrameBodyDeprecated((AbstractID3v2FrameBody) frame.getBody());
this.frameBody.setHeader(this);
identifier = frame.getIdentifier();
logger.info("(4)V2:Deprecated Orig id id is:" + frame.getIdentifier() + ":New id is:" + identifier);
return;
}
}
/** Unknown Frame */
else
{
this.frameBody = new FrameBodyUnsupported((FrameBodyUnsupported) frame.getBody());
this.frameBody.setHeader(this);
identifier = frame.getIdentifier();
logger.info("(5)V2:Unknown:Orig id is:" + frame.getIdentifier() + ":New id is:" + identifier);
return;
}
}
}
/**
* Creates a new ID3v2_4Frame datatype based on Lyrics3.
*
* @param field
* @throws InvalidTagException
*/
public ID3v24Frame(Lyrics3v2Field field)
throws InvalidTagException
{
String id = field.getIdentifier();
String value;
if (id.equals("IND"))
{
throw new InvalidTagException("Cannot create ID3v2.40 frame from Lyrics3 indications field.");
}
else if (id.equals("LYR"))
{
FieldFrameBodyLYR lyric = (FieldFrameBodyLYR) field.getBody();
Lyrics3Line line;
Iterator iterator = lyric.iterator();
FrameBodySYLT sync;
FrameBodyUSLT unsync;
boolean hasTimeStamp = lyric.hasTimeStamp();
// we'll create only one frame here.
// if there is any timestamp at all, we will create a sync'ed frame.
sync = new FrameBodySYLT((byte) 0, "ENG", (byte) 2, (byte) 1, "",new byte[0]);
unsync = new FrameBodyUSLT((byte) 0, "ENG", "", "");
while (iterator.hasNext())
{
line = (Lyrics3Line) iterator.next();
if (hasTimeStamp)
{
// sync.addLyric(line);
}
else
{
unsync.addLyric(line);
}
}
if (hasTimeStamp)
{
this.frameBody = sync;
this.frameBody.setHeader(this);
}
else
{
this.frameBody = unsync;
this.frameBody.setHeader(this);
}
}
else if (id.equals("INF"))
{
value = ((FieldFrameBodyINF) field.getBody()).getAdditionalInformation();
this.frameBody = new FrameBodyCOMM((byte) 0, "ENG", "", value);
this.frameBody.setHeader(this);
}
else if (id.equals("AUT"))
{
value = ((FieldFrameBodyAUT) field.getBody()).getAuthor();
this.frameBody = new FrameBodyTCOM((byte) 0, value);
this.frameBody.setHeader(this);
}
else if (id.equals("EAL"))
{
value = ((FieldFrameBodyEAL) field.getBody()).getAlbum();
this.frameBody = new FrameBodyTALB((byte) 0, value);
this.frameBody.setHeader(this);
}
else if (id.equals("EAR"))
{
value = ((FieldFrameBodyEAR) field.getBody()).getArtist();
this.frameBody = new FrameBodyTPE1((byte) 0, value);
this.frameBody.setHeader(this);
}
else if (id.equals("ETT"))
{
value = ((FieldFrameBodyETT) field.getBody()).getTitle();
this.frameBody = new FrameBodyTIT2((byte) 0, value);
this.frameBody.setHeader(this);
}
else if (id.equals("IMG"))
{
throw new InvalidTagException("Cannot create ID3v2.40 frame from Lyrics3 image field.");
}
else
{
throw new InvalidTagException("Cannot caret ID3v2.40 frame from " + id + " Lyrics3 field");
}
}
/**
* Creates a new ID3v24Frame datatype by reading from byteBuffer.
*
* @param byteBuffer to read from
*/
public ID3v24Frame(ByteBuffer byteBuffer,String loggingFilename)
throws InvalidFrameException
{
setLoggingFilename(loggingFilename);
read(byteBuffer);
}
/**
* Creates a new ID3v24Frame datatype by reading from byteBuffer.
*
* @param byteBuffer to read from
*
* @deprecated use {@link #ID3v24Frame(ByteBuffer,String)} instead
*/
public ID3v24Frame(ByteBuffer byteBuffer)
throws InvalidFrameException
{
this(byteBuffer,"");
}
/**
* @param obj
* @return if obj is equivalent to this frame
*/
public boolean equals(Object obj)
{
if ((obj instanceof ID3v24Frame) == false)
{
return false;
}
return super.equals(obj);
}
/**
* Read the frame from the specified file.
* Read the frame header then delegate reading of data to frame body.
*
* @param byteBuffer to read the frame from
*/
public void read(ByteBuffer byteBuffer)
throws InvalidFrameException
{
byte[] buffer = new byte[FRAME_ID_SIZE];
if (byteBuffer.position() + FRAME_HEADER_SIZE >= byteBuffer.limit())
{
logger.warning(getLoggingFilename()+":"+"No space to find another frame:");
throw new InvalidFrameException(getLoggingFilename()+":"+"No space to find another frame");
}
//Read the Frame Identifier
byteBuffer.get(buffer, 0, FRAME_ID_SIZE);
identifier = new String(buffer);
logger.fine(getLoggingFilename()+":"+"Identifier is" + identifier);
//Is this a valid identifier?
if (isValidID3v2FrameIdentifier(identifier) == false)
{
//If not valid move file pointer back to one byte after
//the original check so can try again.
logger.info(getLoggingFilename()+":"+"Invalid identifier:" + identifier);
byteBuffer.position(byteBuffer.position() - (FRAME_ID_SIZE - 1));
throw new InvalidFrameIdentifierException(identifier + " is not a valid ID3v2.40 frame");
}
//Read frame size as syncsafe integer
frameSize = ID3SyncSafeInteger.bufferToValue(byteBuffer);
if (frameSize < 0)
{
logger.warning(getLoggingFilename()+":"+"Invalid Frame size:" + identifier);
throw new InvalidFrameException(identifier + " is invalid frame");
}
else if (frameSize == 0)
{
logger.warning(getLoggingFilename()+":"+"Empty Frame:" + identifier);
throw new EmptyFrameException(identifier + " is empty frame");
}
else if (frameSize > (byteBuffer.remaining() - FRAME_FLAGS_SIZE))
{
logger.warning(getLoggingFilename()+":"+"Invalid Frame size larger than size before mp3 audio:" + identifier);
throw new InvalidFrameException(identifier + " is invalid frame");
}
if(frameSize>ID3SyncSafeInteger.MAX_SAFE_SIZE)
{
//Set Just after size field this is where we want to be when we leave this if statement
int currentPosition = byteBuffer.position();
//Read as nonsync safe integer
byteBuffer.position(currentPosition - FRAME_ID_SIZE);
int nonSyncSafeFrameSize = byteBuffer.getInt();
//Is the frame size syncsafe, should always be BUT some encoders such as Itunes do not do it properly
//so do an easy check now.
byteBuffer.position(currentPosition - FRAME_ID_SIZE);
boolean isNotSyncSafe = ID3SyncSafeInteger.isBufferNotSyncSafe(byteBuffer);
//not relative so need to move position
byteBuffer.position(currentPosition);
if(isNotSyncSafe)
{
logger.warning(getLoggingFilename()+":"+"Frame size is NOT stored as a sync safe integer:" + identifier);
//This will return a larger frame size so need to check against buffer size if too large then we are
//buggered , give up
if (nonSyncSafeFrameSize > (byteBuffer.remaining() - - FRAME_FLAGS_SIZE))
{
logger.warning(getLoggingFilename()+":"+"Invalid Frame size larger than size before mp3 audio:" + identifier);
throw new InvalidFrameException(identifier + " is invalid frame");
}
else
{
frameSize = nonSyncSafeFrameSize;
}
}
else
{
//appears to be sync safe but lets look at the bytes just after the reported end of this
//frame to see if find a valid frame header
//Read the Frame Identifier
byte[] readAheadbuffer = new byte[FRAME_ID_SIZE];
byteBuffer.position(currentPosition + frameSize + FRAME_FLAGS_SIZE);
if(byteBuffer.remaining()<FRAME_ID_SIZE)
{
//There is no padding or framedata we are at end so assume syncsafe
//reset position to just after framesize
byteBuffer.position(currentPosition);
}
else
{
byteBuffer.get(readAheadbuffer, 0, FRAME_ID_SIZE);
//reset position to just after framesize
byteBuffer.position(currentPosition);
String readAheadIdentifier = new String(readAheadbuffer);
if(isValidID3v2FrameIdentifier(readAheadIdentifier))
{
//Everything ok, so continue
}
else if(ID3SyncSafeInteger.isBufferEmpty(readAheadbuffer))
{
//no data found so assume entered padding in which case assume it is last
//frame and we are ok
}
//havent found identifier so maybe not syncsafe or maybe there are no more frames, just padding
else
{
//Ok lets try using a non-syncsafe integer
//size returned will be larger so is it valid
if (nonSyncSafeFrameSize > byteBuffer.remaining() - FRAME_FLAGS_SIZE)
{
//invalid so assume syncsafe
byteBuffer.position(currentPosition);
}
else
{
readAheadbuffer = new byte[FRAME_ID_SIZE];
byteBuffer.position(currentPosition + nonSyncSafeFrameSize + FRAME_FLAGS_SIZE);
if(byteBuffer.remaining() >= FRAME_ID_SIZE)
{
byteBuffer.get(readAheadbuffer, 0, FRAME_ID_SIZE);
+ readAheadIdentifier = new String(readAheadbuffer);
//reset position to just after framesize
byteBuffer.position(currentPosition);
//ok found a valid identifier using non-syncsafe so assume non-syncsafe size
//and continue
if(isValidID3v2FrameIdentifier(readAheadIdentifier))
{
frameSize = nonSyncSafeFrameSize;
logger.warning(getLoggingFilename()+":"+"Assuming frame size is NOT stored as a sync safe integer:" + identifier);
}
//no data found so assume entered padding in which case assume it is last
//frame and we are ok whereas we didnt hit padding when using syncsafe integer
//or we wouldnt have got to this point. So assume syncsafe ineteger ended within
//the frame data whereas this has reached end of frames.
else if(ID3SyncSafeInteger.isBufferEmpty(readAheadbuffer))
{
frameSize = nonSyncSafeFrameSize;
logger.warning(getLoggingFilename()+":"+"Assuming frame size is NOT stored as a sync safe integer:" + identifier);
}
//invalid so assume syncsafe as that is is the standard
else
{
;
}
}
else
{
//reset position to just after framesize
byteBuffer.position(currentPosition);
//If the unsync framesize matches exactly the remaining bytes then assume it has the
//correct size for the last frame
if(byteBuffer.remaining() == 0)
{
frameSize = nonSyncSafeFrameSize;
}
//Inconclusive stick with syncsafe
else
{
;
}
}
}
}
}
}
}
//Read the flag bytes
statusFlags = new StatusFlags(byteBuffer.get());
encodingFlags = new EncodingFlags(byteBuffer.get());
//Read extra bits appended to frame header for various encodings
//These are not included in header size but are included in frame size but wont be read when we actually
//try to read the frame body data
int extraHeaderBytesCount = 0;
boolean isDataLengthindicatorRead = false;
if(((EncodingFlags)encodingFlags).isGrouping())
{
extraHeaderBytesCount = ID3v24Frame.FRAME_GROUPING_INDICATOR_SIZE;
byteBuffer.get();
}
if(((EncodingFlags)encodingFlags).isCompression())
{
//Read the sync safe size field
int datalengthSize = ID3SyncSafeInteger.bufferToValue(byteBuffer);
logger.info(getLoggingFilename()+":"+"Frame Size Is:"+ frameSize + "Data Length Size:"+datalengthSize);
extraHeaderBytesCount += ID3v24Frame.FRAME_DATA_LENGTH_SIZE;
isDataLengthindicatorRead=true;
}
if(((EncodingFlags)encodingFlags).isEncryption())
{
//Read the Encryption byte, but do nothing with it
extraHeaderBytesCount += ID3v24Frame.FRAME_ENCRYPTION_INDICATOR_SIZE;
byteBuffer.get();
}
if(((EncodingFlags)encodingFlags).isDataLengthIndicator())
{
//There is only data length indicator it may have already been read depending on what flags
//are set
if(!isDataLengthindicatorRead)
{
//Read the sync safe size field
int datalengthSize = ID3SyncSafeInteger.bufferToValue(byteBuffer);
//Read the Grouping byte, but do nothing with it
extraHeaderBytesCount += FRAME_DATA_LENGTH_SIZE;
logger.info(getLoggingFilename()+":"+"Frame Size Is:"+ frameSize + "Data Length Size:"+datalengthSize);
}
}
//Work out the real size of the framebody data
int realFrameSize = frameSize - extraHeaderBytesCount;
//Create Buffer that only contains the body of this frame rather than the remainder of tag
ByteBuffer frameBodyBuffer = byteBuffer.slice();
frameBodyBuffer.limit(realFrameSize);
//Do we need to synchronize the frame body
int syncSize=realFrameSize;
if(((EncodingFlags)encodingFlags).isUnsynchronised())
{
//We only want to synchronize the buffer upto the end of this frame (remember this
//buffer contains the remainder of this tag not just this frame), and we cant just
//create a new buffer because when this method returns the position of the buffer is used
//to look for the next frame, so we need to modify the buffer. The action of synchronizing causes
//bytes to be dropped so the existing buffer is large enough to hold the modifications
frameBodyBuffer=ID3Unsynchronization.synchronize(frameBodyBuffer);
syncSize = frameBodyBuffer.limit();
logger.info(getLoggingFilename()+":"+"Frame Size After Syncing is:"+ syncSize);
}
//Read the body data
try
{
frameBody = readBody(identifier, frameBodyBuffer, syncSize);
if (!(frameBody instanceof ID3v24FrameBody))
{
logger.info(getLoggingFilename()+":"+"Converted frame body with:" + identifier + " to deprecated framebody");
frameBody = new FrameBodyDeprecated((AbstractID3v2FrameBody) frameBody);
}
}
finally
{
//Update position of main buffer, so no attempt is made to reread these bytes
byteBuffer.position(byteBuffer.position()+realFrameSize);
}
}
/**
* Write the frame. Writes the frame header but writing the data is delegated to the
* frame body.
*
* @throws IOException
*/
public void write(ByteArrayOutputStream tagBuffer)
throws IOException
{
boolean unsynchronization;
logger.info("Writing frame to file:" + getIdentifier());
//This is where we will write header, move position to where we can
//write bodybuffer
ByteBuffer headerBuffer = ByteBuffer.allocate(FRAME_HEADER_SIZE);
//Write Frame Body Data to a new stream
ByteArrayOutputStream bodyOutputStream = new ByteArrayOutputStream();
((AbstractID3v2FrameBody) frameBody).write(bodyOutputStream);
//Does it need unsynchronizing, and are we allowing unsychronizing
byte[] bodyBuffer = bodyOutputStream.toByteArray();
if(TagOptionSingleton.getInstance().isUnsyncTags())
{
unsynchronization = ID3Unsynchronization.requiresUnsynchronization(bodyBuffer);
}
else
{
unsynchronization=false;
}
if(unsynchronization)
{
bodyBuffer=ID3Unsynchronization.unsynchronize(bodyBuffer);
logger.info("bodybytebuffer:sizeafterunsynchronisation:"+bodyBuffer.length);
}
//Write Frame Header
//Write Frame ID, the identifier must be 4 bytes bytes long it may not be
//because converted an unknown v2.2 id (only 3 bytes long)
if (getIdentifier().length() == 3)
{
identifier = identifier + ' ';
}
headerBuffer.put(getIdentifier().getBytes(), 0, FRAME_ID_SIZE);
//Write Frame Size based on size of body buffer (if it has been unsynced then it size
//will have increased accordingly
int size = bodyBuffer.length;
logger.fine("Frame Size Is:" + size);
headerBuffer.put(ID3SyncSafeInteger.valueToBuffer(size));
//Write the Flags
//Status Flags:leave as they were when we read
headerBuffer.put(statusFlags.getWriteFlags());
//Enclosing Flags, first reset
encodingFlags.resetFlags();
//Encoding we only support unsynchrnization
if(unsynchronization)
{
((ID3v24Frame.EncodingFlags)encodingFlags).setUnsynchronised();
}
headerBuffer.put(encodingFlags.getFlags());
//Add header to the Byte Array Output Stream
tagBuffer.write(headerBuffer.array());
//Add bodybuffer to the Byte Array Output Stream
tagBuffer.write(bodyBuffer);
}
/**
* Get Status Flags Object
*/
protected AbstractID3v2Frame.StatusFlags getStatusFlags()
{
return statusFlags;
}
/**
* Get Encoding Flags Object
*/
protected AbstractID3v2Frame.EncodingFlags getEncodingFlags()
{
return encodingFlags;
}
/**
* Member Class This represents a frame headers Status Flags
* Make adjustments if necessary based on frame type and specification.
*/
class StatusFlags
extends ID3v23Frame.StatusFlags
{
/** Note these are in a different location to v2.3*/
/**
* Discard frame if tag altered
*/
public static final int MASK_TAG_ALTER_PRESERVATION = FileConstants.BIT6;
/**
* Discard frame if audio part of file altered
*/
public static final int MASK_FILE_ALTER_PRESERVATION = FileConstants.BIT5;
/**
* Frame tagged as read only
*/
public static final int MASK_READ_ONLY = FileConstants.BIT4;
/**
* Use this when creating a frame from scratch
*/
StatusFlags()
{
super();
}
/**
* Use this constructor when reading from file or from another v4 frame
*/
StatusFlags(byte flags)
{
originalFlags = flags;
writeFlags = flags;
modifyFlags();
}
/**
* Use this constructor when convert a v23 frame
*/
StatusFlags(ID3v23Frame.StatusFlags statusFlags)
{
originalFlags = convertV3ToV4Flags(statusFlags.getOriginalFlags());
writeFlags = originalFlags;
modifyFlags();
}
/**
* Convert V3 Flags to equivalent V4 Flags
*/
private byte convertV3ToV4Flags(byte v3Flag)
{
byte v4Flag = (byte) 0;
if ((v3Flag & ID3v23Frame.StatusFlags.MASK_FILE_ALTER_PRESERVATION) != 0)
{
v4Flag |= (byte) MASK_FILE_ALTER_PRESERVATION;
}
if ((v3Flag & ID3v23Frame.StatusFlags.MASK_TAG_ALTER_PRESERVATION) != 0)
{
v4Flag |= (byte) MASK_TAG_ALTER_PRESERVATION;
}
return v4Flag;
}
/**
* Makes modifications to flags based on specification and frameid
*/
protected void modifyFlags()
{
String str = getIdentifier();
if (ID3v24Frames.getInstanceOf().isDiscardIfFileAltered(str) == true)
{
writeFlags |= (byte) MASK_FILE_ALTER_PRESERVATION;
writeFlags &= (byte) ~MASK_TAG_ALTER_PRESERVATION;
}
else
{
writeFlags &= (byte) ~MASK_FILE_ALTER_PRESERVATION;
writeFlags &= (byte) ~MASK_TAG_ALTER_PRESERVATION;
}
}
public void createStructure()
{
MP3File.getStructureFormatter().openHeadingElement(TYPE_FLAGS, "");
MP3File.getStructureFormatter().addElement(TYPE_TAGALTERPRESERVATION, originalFlags & MASK_TAG_ALTER_PRESERVATION);
MP3File.getStructureFormatter().addElement(TYPE_FILEALTERPRESERVATION, originalFlags & MASK_FILE_ALTER_PRESERVATION);
MP3File.getStructureFormatter().addElement(TYPE_READONLY, originalFlags & MASK_READ_ONLY);
MP3File.getStructureFormatter().closeHeadingElement(TYPE_FLAGS);
}
}
/**
* This represents a frame headers Encoding Flags
*/
class EncodingFlags
extends AbstractID3v2Frame.EncodingFlags
{
public static final String TYPE_COMPRESSION = "compression";
public static final String TYPE_ENCRYPTION = "encryption";
public static final String TYPE_GROUPIDENTITY = "groupidentity";
public static final String TYPE_FRAMEUNSYNCHRONIZATION = "frameUnsynchronisation";
public static final String TYPE_DATALENGTHINDICATOR = "dataLengthIndicator";
/**
* Frame is part of a group
*/
public static final int MASK_GROUPING_IDENTITY = FileConstants.BIT6;
/**
* Frame is compressed
*/
public static final int MASK_COMPRESSION = FileConstants.BIT3;
/**
* Frame is encrypted
*/
public static final int MASK_ENCRYPTION = FileConstants.BIT2;
/**
* Unsynchronisation
*/
public static final int MASK_FRAME_UNSYNCHRONIZATION = FileConstants.BIT1;
/**
* Length
*/
public static final int MASK_DATA_LENGTH_INDICATOR = FileConstants.BIT0;
/**
* Use this when creating a frame from scratch
*/
EncodingFlags()
{
super();
}
/**
* Use this when creating a frame from existing flags in another v4 frame
*/
EncodingFlags(byte flags)
{
super(flags);
logEnabledFlags();
}
public void logEnabledFlags()
{
if (isCompression())
{
logger.warning(getLoggingFilename()+":"+identifier+" is compressed");
}
if (isEncryption())
{
logger.warning(getLoggingFilename()+":"+identifier+" is encrypted");
}
if (isGrouping())
{
logger.warning(getLoggingFilename()+":"+identifier+" is grouped");
}
if (isUnsynchronised())
{
logger.warning(getLoggingFilename()+":"+identifier+" is unsynchronised");
}
if (isDataLengthIndicator())
{
logger.warning(getLoggingFilename()+":"+identifier+" has a data length indicator");
}
}
public byte getFlags()
{
return flags;
}
public boolean isCompression()
{
return (flags & MASK_COMPRESSION) >0;
}
public boolean isEncryption()
{
return (flags & MASK_ENCRYPTION) >0;
}
public boolean isGrouping()
{
return (flags & MASK_GROUPING_IDENTITY) >0;
}
public boolean isUnsynchronised()
{
return (flags & MASK_FRAME_UNSYNCHRONIZATION) >0;
}
public boolean isDataLengthIndicator()
{
return (flags & MASK_DATA_LENGTH_INDICATOR) >0;
}
public void setUnsynchronised()
{
flags |= MASK_FRAME_UNSYNCHRONIZATION;
}
public void createStructure()
{
MP3File.getStructureFormatter().openHeadingElement(TYPE_FLAGS, "");
MP3File.getStructureFormatter().addElement(TYPE_COMPRESSION, flags & MASK_COMPRESSION);
MP3File.getStructureFormatter().addElement(TYPE_ENCRYPTION, flags & MASK_ENCRYPTION);
MP3File.getStructureFormatter().addElement(TYPE_GROUPIDENTITY, flags & MASK_GROUPING_IDENTITY);
MP3File.getStructureFormatter().addElement(TYPE_FRAMEUNSYNCHRONIZATION, flags & MASK_FRAME_UNSYNCHRONIZATION);
MP3File.getStructureFormatter().addElement(TYPE_DATALENGTHINDICATOR, flags & MASK_DATA_LENGTH_INDICATOR);
MP3File.getStructureFormatter().closeHeadingElement(TYPE_FLAGS);
}
}
/**
* Return String Representation of body
*/
public void createStructure()
{
MP3File.getStructureFormatter().openHeadingElement(TYPE_FRAME, getIdentifier());
MP3File.getStructureFormatter().addElement(TYPE_FRAME_SIZE, frameSize);
statusFlags.createStructure();
encodingFlags.createStructure();
frameBody.createStructure();
MP3File.getStructureFormatter().closeHeadingElement(TYPE_FRAME);
}
}
| true | true | public void read(ByteBuffer byteBuffer)
throws InvalidFrameException
{
byte[] buffer = new byte[FRAME_ID_SIZE];
if (byteBuffer.position() + FRAME_HEADER_SIZE >= byteBuffer.limit())
{
logger.warning(getLoggingFilename()+":"+"No space to find another frame:");
throw new InvalidFrameException(getLoggingFilename()+":"+"No space to find another frame");
}
//Read the Frame Identifier
byteBuffer.get(buffer, 0, FRAME_ID_SIZE);
identifier = new String(buffer);
logger.fine(getLoggingFilename()+":"+"Identifier is" + identifier);
//Is this a valid identifier?
if (isValidID3v2FrameIdentifier(identifier) == false)
{
//If not valid move file pointer back to one byte after
//the original check so can try again.
logger.info(getLoggingFilename()+":"+"Invalid identifier:" + identifier);
byteBuffer.position(byteBuffer.position() - (FRAME_ID_SIZE - 1));
throw new InvalidFrameIdentifierException(identifier + " is not a valid ID3v2.40 frame");
}
//Read frame size as syncsafe integer
frameSize = ID3SyncSafeInteger.bufferToValue(byteBuffer);
if (frameSize < 0)
{
logger.warning(getLoggingFilename()+":"+"Invalid Frame size:" + identifier);
throw new InvalidFrameException(identifier + " is invalid frame");
}
else if (frameSize == 0)
{
logger.warning(getLoggingFilename()+":"+"Empty Frame:" + identifier);
throw new EmptyFrameException(identifier + " is empty frame");
}
else if (frameSize > (byteBuffer.remaining() - FRAME_FLAGS_SIZE))
{
logger.warning(getLoggingFilename()+":"+"Invalid Frame size larger than size before mp3 audio:" + identifier);
throw new InvalidFrameException(identifier + " is invalid frame");
}
if(frameSize>ID3SyncSafeInteger.MAX_SAFE_SIZE)
{
//Set Just after size field this is where we want to be when we leave this if statement
int currentPosition = byteBuffer.position();
//Read as nonsync safe integer
byteBuffer.position(currentPosition - FRAME_ID_SIZE);
int nonSyncSafeFrameSize = byteBuffer.getInt();
//Is the frame size syncsafe, should always be BUT some encoders such as Itunes do not do it properly
//so do an easy check now.
byteBuffer.position(currentPosition - FRAME_ID_SIZE);
boolean isNotSyncSafe = ID3SyncSafeInteger.isBufferNotSyncSafe(byteBuffer);
//not relative so need to move position
byteBuffer.position(currentPosition);
if(isNotSyncSafe)
{
logger.warning(getLoggingFilename()+":"+"Frame size is NOT stored as a sync safe integer:" + identifier);
//This will return a larger frame size so need to check against buffer size if too large then we are
//buggered , give up
if (nonSyncSafeFrameSize > (byteBuffer.remaining() - - FRAME_FLAGS_SIZE))
{
logger.warning(getLoggingFilename()+":"+"Invalid Frame size larger than size before mp3 audio:" + identifier);
throw new InvalidFrameException(identifier + " is invalid frame");
}
else
{
frameSize = nonSyncSafeFrameSize;
}
}
else
{
//appears to be sync safe but lets look at the bytes just after the reported end of this
//frame to see if find a valid frame header
//Read the Frame Identifier
byte[] readAheadbuffer = new byte[FRAME_ID_SIZE];
byteBuffer.position(currentPosition + frameSize + FRAME_FLAGS_SIZE);
if(byteBuffer.remaining()<FRAME_ID_SIZE)
{
//There is no padding or framedata we are at end so assume syncsafe
//reset position to just after framesize
byteBuffer.position(currentPosition);
}
else
{
byteBuffer.get(readAheadbuffer, 0, FRAME_ID_SIZE);
//reset position to just after framesize
byteBuffer.position(currentPosition);
String readAheadIdentifier = new String(readAheadbuffer);
if(isValidID3v2FrameIdentifier(readAheadIdentifier))
{
//Everything ok, so continue
}
else if(ID3SyncSafeInteger.isBufferEmpty(readAheadbuffer))
{
//no data found so assume entered padding in which case assume it is last
//frame and we are ok
}
//havent found identifier so maybe not syncsafe or maybe there are no more frames, just padding
else
{
//Ok lets try using a non-syncsafe integer
//size returned will be larger so is it valid
if (nonSyncSafeFrameSize > byteBuffer.remaining() - FRAME_FLAGS_SIZE)
{
//invalid so assume syncsafe
byteBuffer.position(currentPosition);
}
else
{
readAheadbuffer = new byte[FRAME_ID_SIZE];
byteBuffer.position(currentPosition + nonSyncSafeFrameSize + FRAME_FLAGS_SIZE);
if(byteBuffer.remaining() >= FRAME_ID_SIZE)
{
byteBuffer.get(readAheadbuffer, 0, FRAME_ID_SIZE);
//reset position to just after framesize
byteBuffer.position(currentPosition);
//ok found a valid identifier using non-syncsafe so assume non-syncsafe size
//and continue
if(isValidID3v2FrameIdentifier(readAheadIdentifier))
{
frameSize = nonSyncSafeFrameSize;
logger.warning(getLoggingFilename()+":"+"Assuming frame size is NOT stored as a sync safe integer:" + identifier);
}
//no data found so assume entered padding in which case assume it is last
//frame and we are ok whereas we didnt hit padding when using syncsafe integer
//or we wouldnt have got to this point. So assume syncsafe ineteger ended within
//the frame data whereas this has reached end of frames.
else if(ID3SyncSafeInteger.isBufferEmpty(readAheadbuffer))
{
frameSize = nonSyncSafeFrameSize;
logger.warning(getLoggingFilename()+":"+"Assuming frame size is NOT stored as a sync safe integer:" + identifier);
}
//invalid so assume syncsafe as that is is the standard
else
{
;
}
}
else
{
//reset position to just after framesize
byteBuffer.position(currentPosition);
//If the unsync framesize matches exactly the remaining bytes then assume it has the
//correct size for the last frame
if(byteBuffer.remaining() == 0)
{
frameSize = nonSyncSafeFrameSize;
}
//Inconclusive stick with syncsafe
else
{
;
}
}
}
}
}
}
}
//Read the flag bytes
statusFlags = new StatusFlags(byteBuffer.get());
encodingFlags = new EncodingFlags(byteBuffer.get());
//Read extra bits appended to frame header for various encodings
//These are not included in header size but are included in frame size but wont be read when we actually
//try to read the frame body data
int extraHeaderBytesCount = 0;
boolean isDataLengthindicatorRead = false;
if(((EncodingFlags)encodingFlags).isGrouping())
{
extraHeaderBytesCount = ID3v24Frame.FRAME_GROUPING_INDICATOR_SIZE;
byteBuffer.get();
}
if(((EncodingFlags)encodingFlags).isCompression())
{
//Read the sync safe size field
int datalengthSize = ID3SyncSafeInteger.bufferToValue(byteBuffer);
logger.info(getLoggingFilename()+":"+"Frame Size Is:"+ frameSize + "Data Length Size:"+datalengthSize);
extraHeaderBytesCount += ID3v24Frame.FRAME_DATA_LENGTH_SIZE;
isDataLengthindicatorRead=true;
}
if(((EncodingFlags)encodingFlags).isEncryption())
{
//Read the Encryption byte, but do nothing with it
extraHeaderBytesCount += ID3v24Frame.FRAME_ENCRYPTION_INDICATOR_SIZE;
byteBuffer.get();
}
if(((EncodingFlags)encodingFlags).isDataLengthIndicator())
{
//There is only data length indicator it may have already been read depending on what flags
//are set
if(!isDataLengthindicatorRead)
{
//Read the sync safe size field
int datalengthSize = ID3SyncSafeInteger.bufferToValue(byteBuffer);
//Read the Grouping byte, but do nothing with it
extraHeaderBytesCount += FRAME_DATA_LENGTH_SIZE;
logger.info(getLoggingFilename()+":"+"Frame Size Is:"+ frameSize + "Data Length Size:"+datalengthSize);
}
}
//Work out the real size of the framebody data
int realFrameSize = frameSize - extraHeaderBytesCount;
//Create Buffer that only contains the body of this frame rather than the remainder of tag
ByteBuffer frameBodyBuffer = byteBuffer.slice();
frameBodyBuffer.limit(realFrameSize);
//Do we need to synchronize the frame body
int syncSize=realFrameSize;
if(((EncodingFlags)encodingFlags).isUnsynchronised())
{
//We only want to synchronize the buffer upto the end of this frame (remember this
//buffer contains the remainder of this tag not just this frame), and we cant just
//create a new buffer because when this method returns the position of the buffer is used
//to look for the next frame, so we need to modify the buffer. The action of synchronizing causes
//bytes to be dropped so the existing buffer is large enough to hold the modifications
frameBodyBuffer=ID3Unsynchronization.synchronize(frameBodyBuffer);
syncSize = frameBodyBuffer.limit();
logger.info(getLoggingFilename()+":"+"Frame Size After Syncing is:"+ syncSize);
}
//Read the body data
try
{
frameBody = readBody(identifier, frameBodyBuffer, syncSize);
if (!(frameBody instanceof ID3v24FrameBody))
{
logger.info(getLoggingFilename()+":"+"Converted frame body with:" + identifier + " to deprecated framebody");
frameBody = new FrameBodyDeprecated((AbstractID3v2FrameBody) frameBody);
}
}
finally
{
//Update position of main buffer, so no attempt is made to reread these bytes
byteBuffer.position(byteBuffer.position()+realFrameSize);
}
}
| public void read(ByteBuffer byteBuffer)
throws InvalidFrameException
{
byte[] buffer = new byte[FRAME_ID_SIZE];
if (byteBuffer.position() + FRAME_HEADER_SIZE >= byteBuffer.limit())
{
logger.warning(getLoggingFilename()+":"+"No space to find another frame:");
throw new InvalidFrameException(getLoggingFilename()+":"+"No space to find another frame");
}
//Read the Frame Identifier
byteBuffer.get(buffer, 0, FRAME_ID_SIZE);
identifier = new String(buffer);
logger.fine(getLoggingFilename()+":"+"Identifier is" + identifier);
//Is this a valid identifier?
if (isValidID3v2FrameIdentifier(identifier) == false)
{
//If not valid move file pointer back to one byte after
//the original check so can try again.
logger.info(getLoggingFilename()+":"+"Invalid identifier:" + identifier);
byteBuffer.position(byteBuffer.position() - (FRAME_ID_SIZE - 1));
throw new InvalidFrameIdentifierException(identifier + " is not a valid ID3v2.40 frame");
}
//Read frame size as syncsafe integer
frameSize = ID3SyncSafeInteger.bufferToValue(byteBuffer);
if (frameSize < 0)
{
logger.warning(getLoggingFilename()+":"+"Invalid Frame size:" + identifier);
throw new InvalidFrameException(identifier + " is invalid frame");
}
else if (frameSize == 0)
{
logger.warning(getLoggingFilename()+":"+"Empty Frame:" + identifier);
throw new EmptyFrameException(identifier + " is empty frame");
}
else if (frameSize > (byteBuffer.remaining() - FRAME_FLAGS_SIZE))
{
logger.warning(getLoggingFilename()+":"+"Invalid Frame size larger than size before mp3 audio:" + identifier);
throw new InvalidFrameException(identifier + " is invalid frame");
}
if(frameSize>ID3SyncSafeInteger.MAX_SAFE_SIZE)
{
//Set Just after size field this is where we want to be when we leave this if statement
int currentPosition = byteBuffer.position();
//Read as nonsync safe integer
byteBuffer.position(currentPosition - FRAME_ID_SIZE);
int nonSyncSafeFrameSize = byteBuffer.getInt();
//Is the frame size syncsafe, should always be BUT some encoders such as Itunes do not do it properly
//so do an easy check now.
byteBuffer.position(currentPosition - FRAME_ID_SIZE);
boolean isNotSyncSafe = ID3SyncSafeInteger.isBufferNotSyncSafe(byteBuffer);
//not relative so need to move position
byteBuffer.position(currentPosition);
if(isNotSyncSafe)
{
logger.warning(getLoggingFilename()+":"+"Frame size is NOT stored as a sync safe integer:" + identifier);
//This will return a larger frame size so need to check against buffer size if too large then we are
//buggered , give up
if (nonSyncSafeFrameSize > (byteBuffer.remaining() - - FRAME_FLAGS_SIZE))
{
logger.warning(getLoggingFilename()+":"+"Invalid Frame size larger than size before mp3 audio:" + identifier);
throw new InvalidFrameException(identifier + " is invalid frame");
}
else
{
frameSize = nonSyncSafeFrameSize;
}
}
else
{
//appears to be sync safe but lets look at the bytes just after the reported end of this
//frame to see if find a valid frame header
//Read the Frame Identifier
byte[] readAheadbuffer = new byte[FRAME_ID_SIZE];
byteBuffer.position(currentPosition + frameSize + FRAME_FLAGS_SIZE);
if(byteBuffer.remaining()<FRAME_ID_SIZE)
{
//There is no padding or framedata we are at end so assume syncsafe
//reset position to just after framesize
byteBuffer.position(currentPosition);
}
else
{
byteBuffer.get(readAheadbuffer, 0, FRAME_ID_SIZE);
//reset position to just after framesize
byteBuffer.position(currentPosition);
String readAheadIdentifier = new String(readAheadbuffer);
if(isValidID3v2FrameIdentifier(readAheadIdentifier))
{
//Everything ok, so continue
}
else if(ID3SyncSafeInteger.isBufferEmpty(readAheadbuffer))
{
//no data found so assume entered padding in which case assume it is last
//frame and we are ok
}
//havent found identifier so maybe not syncsafe or maybe there are no more frames, just padding
else
{
//Ok lets try using a non-syncsafe integer
//size returned will be larger so is it valid
if (nonSyncSafeFrameSize > byteBuffer.remaining() - FRAME_FLAGS_SIZE)
{
//invalid so assume syncsafe
byteBuffer.position(currentPosition);
}
else
{
readAheadbuffer = new byte[FRAME_ID_SIZE];
byteBuffer.position(currentPosition + nonSyncSafeFrameSize + FRAME_FLAGS_SIZE);
if(byteBuffer.remaining() >= FRAME_ID_SIZE)
{
byteBuffer.get(readAheadbuffer, 0, FRAME_ID_SIZE);
readAheadIdentifier = new String(readAheadbuffer);
//reset position to just after framesize
byteBuffer.position(currentPosition);
//ok found a valid identifier using non-syncsafe so assume non-syncsafe size
//and continue
if(isValidID3v2FrameIdentifier(readAheadIdentifier))
{
frameSize = nonSyncSafeFrameSize;
logger.warning(getLoggingFilename()+":"+"Assuming frame size is NOT stored as a sync safe integer:" + identifier);
}
//no data found so assume entered padding in which case assume it is last
//frame and we are ok whereas we didnt hit padding when using syncsafe integer
//or we wouldnt have got to this point. So assume syncsafe ineteger ended within
//the frame data whereas this has reached end of frames.
else if(ID3SyncSafeInteger.isBufferEmpty(readAheadbuffer))
{
frameSize = nonSyncSafeFrameSize;
logger.warning(getLoggingFilename()+":"+"Assuming frame size is NOT stored as a sync safe integer:" + identifier);
}
//invalid so assume syncsafe as that is is the standard
else
{
;
}
}
else
{
//reset position to just after framesize
byteBuffer.position(currentPosition);
//If the unsync framesize matches exactly the remaining bytes then assume it has the
//correct size for the last frame
if(byteBuffer.remaining() == 0)
{
frameSize = nonSyncSafeFrameSize;
}
//Inconclusive stick with syncsafe
else
{
;
}
}
}
}
}
}
}
//Read the flag bytes
statusFlags = new StatusFlags(byteBuffer.get());
encodingFlags = new EncodingFlags(byteBuffer.get());
//Read extra bits appended to frame header for various encodings
//These are not included in header size but are included in frame size but wont be read when we actually
//try to read the frame body data
int extraHeaderBytesCount = 0;
boolean isDataLengthindicatorRead = false;
if(((EncodingFlags)encodingFlags).isGrouping())
{
extraHeaderBytesCount = ID3v24Frame.FRAME_GROUPING_INDICATOR_SIZE;
byteBuffer.get();
}
if(((EncodingFlags)encodingFlags).isCompression())
{
//Read the sync safe size field
int datalengthSize = ID3SyncSafeInteger.bufferToValue(byteBuffer);
logger.info(getLoggingFilename()+":"+"Frame Size Is:"+ frameSize + "Data Length Size:"+datalengthSize);
extraHeaderBytesCount += ID3v24Frame.FRAME_DATA_LENGTH_SIZE;
isDataLengthindicatorRead=true;
}
if(((EncodingFlags)encodingFlags).isEncryption())
{
//Read the Encryption byte, but do nothing with it
extraHeaderBytesCount += ID3v24Frame.FRAME_ENCRYPTION_INDICATOR_SIZE;
byteBuffer.get();
}
if(((EncodingFlags)encodingFlags).isDataLengthIndicator())
{
//There is only data length indicator it may have already been read depending on what flags
//are set
if(!isDataLengthindicatorRead)
{
//Read the sync safe size field
int datalengthSize = ID3SyncSafeInteger.bufferToValue(byteBuffer);
//Read the Grouping byte, but do nothing with it
extraHeaderBytesCount += FRAME_DATA_LENGTH_SIZE;
logger.info(getLoggingFilename()+":"+"Frame Size Is:"+ frameSize + "Data Length Size:"+datalengthSize);
}
}
//Work out the real size of the framebody data
int realFrameSize = frameSize - extraHeaderBytesCount;
//Create Buffer that only contains the body of this frame rather than the remainder of tag
ByteBuffer frameBodyBuffer = byteBuffer.slice();
frameBodyBuffer.limit(realFrameSize);
//Do we need to synchronize the frame body
int syncSize=realFrameSize;
if(((EncodingFlags)encodingFlags).isUnsynchronised())
{
//We only want to synchronize the buffer upto the end of this frame (remember this
//buffer contains the remainder of this tag not just this frame), and we cant just
//create a new buffer because when this method returns the position of the buffer is used
//to look for the next frame, so we need to modify the buffer. The action of synchronizing causes
//bytes to be dropped so the existing buffer is large enough to hold the modifications
frameBodyBuffer=ID3Unsynchronization.synchronize(frameBodyBuffer);
syncSize = frameBodyBuffer.limit();
logger.info(getLoggingFilename()+":"+"Frame Size After Syncing is:"+ syncSize);
}
//Read the body data
try
{
frameBody = readBody(identifier, frameBodyBuffer, syncSize);
if (!(frameBody instanceof ID3v24FrameBody))
{
logger.info(getLoggingFilename()+":"+"Converted frame body with:" + identifier + " to deprecated framebody");
frameBody = new FrameBodyDeprecated((AbstractID3v2FrameBody) frameBody);
}
}
finally
{
//Update position of main buffer, so no attempt is made to reread these bytes
byteBuffer.position(byteBuffer.position()+realFrameSize);
}
}
|
diff --git a/src/test/org/apache/hadoop/chukwa/dataloader/TestSocketDataLoader.java b/src/test/org/apache/hadoop/chukwa/dataloader/TestSocketDataLoader.java
index 97573b6..e271f9e 100644
--- a/src/test/org/apache/hadoop/chukwa/dataloader/TestSocketDataLoader.java
+++ b/src/test/org/apache/hadoop/chukwa/dataloader/TestSocketDataLoader.java
@@ -1,70 +1,70 @@
/*
* 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.chukwa.dataloader;
import junit.framework.TestCase;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.chukwa.ChunkImpl;
import org.apache.hadoop.chukwa.Chunk;
import java.util.ArrayList;
import java.util.Collection;
import java.util.NoSuchElementException;
import java.util.regex.Matcher;
import org.apache.hadoop.chukwa.datacollection.collector.CaptureWriter;
import org.apache.hadoop.chukwa.datacollection.writer.PipelineStageWriter;
import org.apache.hadoop.chukwa.datacollection.writer.SocketTeeWriter;
import org.apache.hadoop.chukwa.rest.bean.ClientTraceBean;
import java.net.*;
import java.io.*;
public class TestSocketDataLoader extends TestCase{
public void testSocketTee() throws Exception {
Configuration conf = new Configuration();
conf.set("chukwaCollector.pipeline",
SocketTeeWriter.class.getCanonicalName());
conf.set("chukwaCollector.writerClass",
PipelineStageWriter.class.getCanonicalName());
PipelineStageWriter psw = new PipelineStageWriter();
psw.init(conf);
SocketDataLoader sdl = new SocketDataLoader("all");
System.out.println("pipeline established; now pushing a chunk");
ArrayList<Chunk> l = new ArrayList<Chunk>();
l.add(new ChunkImpl("dt", "name", 1, new byte[] {'a'}, null));
psw.add(l);
//push a chunk through. SocketDataLoader should receive this chunk.
try {
Collection<Chunk> clist = sdl.read();
for(Chunk c : clist) {
if(c!=null && c.getData()!=null) {
- assertEquals('a',c.getData());
+ assertEquals("a",c.getData().toString());
}
}
} catch(NoSuchElementException e) {
}
}
}
| true | true | public void testSocketTee() throws Exception {
Configuration conf = new Configuration();
conf.set("chukwaCollector.pipeline",
SocketTeeWriter.class.getCanonicalName());
conf.set("chukwaCollector.writerClass",
PipelineStageWriter.class.getCanonicalName());
PipelineStageWriter psw = new PipelineStageWriter();
psw.init(conf);
SocketDataLoader sdl = new SocketDataLoader("all");
System.out.println("pipeline established; now pushing a chunk");
ArrayList<Chunk> l = new ArrayList<Chunk>();
l.add(new ChunkImpl("dt", "name", 1, new byte[] {'a'}, null));
psw.add(l);
//push a chunk through. SocketDataLoader should receive this chunk.
try {
Collection<Chunk> clist = sdl.read();
for(Chunk c : clist) {
if(c!=null && c.getData()!=null) {
assertEquals('a',c.getData());
}
}
} catch(NoSuchElementException e) {
}
}
| public void testSocketTee() throws Exception {
Configuration conf = new Configuration();
conf.set("chukwaCollector.pipeline",
SocketTeeWriter.class.getCanonicalName());
conf.set("chukwaCollector.writerClass",
PipelineStageWriter.class.getCanonicalName());
PipelineStageWriter psw = new PipelineStageWriter();
psw.init(conf);
SocketDataLoader sdl = new SocketDataLoader("all");
System.out.println("pipeline established; now pushing a chunk");
ArrayList<Chunk> l = new ArrayList<Chunk>();
l.add(new ChunkImpl("dt", "name", 1, new byte[] {'a'}, null));
psw.add(l);
//push a chunk through. SocketDataLoader should receive this chunk.
try {
Collection<Chunk> clist = sdl.read();
for(Chunk c : clist) {
if(c!=null && c.getData()!=null) {
assertEquals("a",c.getData().toString());
}
}
} catch(NoSuchElementException e) {
}
}
|
diff --git a/src/api/org/openmrs/validator/ConceptValidator.java b/src/api/org/openmrs/validator/ConceptValidator.java
index c439d88f..01f76954 100644
--- a/src/api/org/openmrs/validator/ConceptValidator.java
+++ b/src/api/org/openmrs/validator/ConceptValidator.java
@@ -1,124 +1,124 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.validator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Concept;
import org.openmrs.annotation.Handler;
import org.openmrs.api.APIException;
import org.openmrs.api.DuplicateConceptNameException;
import org.openmrs.api.context.Context;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
/**
* Validates methods of the {@link Concept} object.
*/
@Handler(supports = { Concept.class }, order = 50)
public class ConceptValidator implements Validator {
/** Log for this class and subclasses */
protected final Log log = LogFactory.getLog(getClass());
/**
* Determines if the command object being submitted is a valid type
*
* @see org.springframework.validation.Validator#supports(java.lang.Class)
*/
@SuppressWarnings("unchecked")
public boolean supports(Class c) {
return c.equals(Concept.class);
}
/**
* Checks that a given concept object has a unique name or preferred name across the entire
* unretired and preferred concept name space in a given locale(should be the default
* application locale set in the openmrs context). Currently this method is called just before
* the concept is persisted in the database
*
* @should fail if there is a duplicate unretired concept name in the locale
* @should fail if the preferred name is an empty string
* @should fail if the object parameter is null
* @should pass if the found duplicate concept is actually retired
* @should pass if the concept is being updated with no name change
*/
public void validate(Object obj, Errors errorss) throws APIException, DuplicateConceptNameException {
if (obj == null || !(obj instanceof Concept)) {
if (log.isErrorEnabled())
log.error("The parameter obj should not be null and must be of type" + Concept.class);
throw new IllegalArgumentException("Concept name is null or of invalid class");
} else {
Concept newConcept = (Concept) obj;
String newName = null;
//no name to validate, but why is this the case?
if (newConcept.getName() == null)
return;
//if the new concept name is in a different locale other than openmrs' default one
- if (newConcept.getName().getLocale() != null && newConcept.getName().getLocale() != Context.getLocale())
+ if (newConcept.getName().getLocale() != null && !newConcept.getName().getLocale().equals(Context.getLocale()))
newName = newConcept.getName().getName();
else
newName = newConcept.getPreferredName(Context.getLocale()).getName();
if (StringUtils.isBlank(newName)) {
if (log.isErrorEnabled())
log.error("No preferred name specified for the concept to be validated");
throw new APIException("Concept name cannot be an empty String");
}
if (log.isDebugEnabled())
log.debug("Looking up concept names matching " + newName);
List<Concept> matchingConcepts = Context.getConceptService().getConceptsByName(newName);
Set<Concept> duplicates = new HashSet<Concept>();
for (Concept c : matchingConcepts) {
//If updating a concept, read past the concept being updated
- if (newConcept.getConceptId() != null && c.getConceptId() == newConcept.getConceptId())
+ if (newConcept.getConceptId() != null && c.getConceptId().intValue() == newConcept.getConceptId())
continue;
//get only duplicates that are not retired
if (c.getPreferredName(Context.getLocale()).getName().equalsIgnoreCase(newName) && !c.isRetired()) {
duplicates.add(c);
}
}
if (duplicates.size() > 0) {
for (Concept duplicate : duplicates) {
if (log.isErrorEnabled())
log.error("The name '" + newName + "' is already being used by concept with Id: "
+ duplicate.getConceptId());
throw new DuplicateConceptNameException("Duplicate concept name '" + newName + "'");
}
}
}
}
}
| false | true | public void validate(Object obj, Errors errorss) throws APIException, DuplicateConceptNameException {
if (obj == null || !(obj instanceof Concept)) {
if (log.isErrorEnabled())
log.error("The parameter obj should not be null and must be of type" + Concept.class);
throw new IllegalArgumentException("Concept name is null or of invalid class");
} else {
Concept newConcept = (Concept) obj;
String newName = null;
//no name to validate, but why is this the case?
if (newConcept.getName() == null)
return;
//if the new concept name is in a different locale other than openmrs' default one
if (newConcept.getName().getLocale() != null && newConcept.getName().getLocale() != Context.getLocale())
newName = newConcept.getName().getName();
else
newName = newConcept.getPreferredName(Context.getLocale()).getName();
if (StringUtils.isBlank(newName)) {
if (log.isErrorEnabled())
log.error("No preferred name specified for the concept to be validated");
throw new APIException("Concept name cannot be an empty String");
}
if (log.isDebugEnabled())
log.debug("Looking up concept names matching " + newName);
List<Concept> matchingConcepts = Context.getConceptService().getConceptsByName(newName);
Set<Concept> duplicates = new HashSet<Concept>();
for (Concept c : matchingConcepts) {
//If updating a concept, read past the concept being updated
if (newConcept.getConceptId() != null && c.getConceptId() == newConcept.getConceptId())
continue;
//get only duplicates that are not retired
if (c.getPreferredName(Context.getLocale()).getName().equalsIgnoreCase(newName) && !c.isRetired()) {
duplicates.add(c);
}
}
if (duplicates.size() > 0) {
for (Concept duplicate : duplicates) {
if (log.isErrorEnabled())
log.error("The name '" + newName + "' is already being used by concept with Id: "
+ duplicate.getConceptId());
throw new DuplicateConceptNameException("Duplicate concept name '" + newName + "'");
}
}
}
}
| public void validate(Object obj, Errors errorss) throws APIException, DuplicateConceptNameException {
if (obj == null || !(obj instanceof Concept)) {
if (log.isErrorEnabled())
log.error("The parameter obj should not be null and must be of type" + Concept.class);
throw new IllegalArgumentException("Concept name is null or of invalid class");
} else {
Concept newConcept = (Concept) obj;
String newName = null;
//no name to validate, but why is this the case?
if (newConcept.getName() == null)
return;
//if the new concept name is in a different locale other than openmrs' default one
if (newConcept.getName().getLocale() != null && !newConcept.getName().getLocale().equals(Context.getLocale()))
newName = newConcept.getName().getName();
else
newName = newConcept.getPreferredName(Context.getLocale()).getName();
if (StringUtils.isBlank(newName)) {
if (log.isErrorEnabled())
log.error("No preferred name specified for the concept to be validated");
throw new APIException("Concept name cannot be an empty String");
}
if (log.isDebugEnabled())
log.debug("Looking up concept names matching " + newName);
List<Concept> matchingConcepts = Context.getConceptService().getConceptsByName(newName);
Set<Concept> duplicates = new HashSet<Concept>();
for (Concept c : matchingConcepts) {
//If updating a concept, read past the concept being updated
if (newConcept.getConceptId() != null && c.getConceptId().intValue() == newConcept.getConceptId())
continue;
//get only duplicates that are not retired
if (c.getPreferredName(Context.getLocale()).getName().equalsIgnoreCase(newName) && !c.isRetired()) {
duplicates.add(c);
}
}
if (duplicates.size() > 0) {
for (Concept duplicate : duplicates) {
if (log.isErrorEnabled())
log.error("The name '" + newName + "' is already being used by concept with Id: "
+ duplicate.getConceptId());
throw new DuplicateConceptNameException("Duplicate concept name '" + newName + "'");
}
}
}
}
|
diff --git a/src/powercrystals/minefactoryreloaded/block/BlockRedstoneCable.java b/src/powercrystals/minefactoryreloaded/block/BlockRedstoneCable.java
index 2994f82e..39bd7463 100644
--- a/src/powercrystals/minefactoryreloaded/block/BlockRedstoneCable.java
+++ b/src/powercrystals/minefactoryreloaded/block/BlockRedstoneCable.java
@@ -1,266 +1,270 @@
package powercrystals.minefactoryreloaded.block;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import powercrystals.minefactoryreloaded.MineFactoryReloadedCore;
import powercrystals.minefactoryreloaded.api.IToolHammer;
import powercrystals.minefactoryreloaded.gui.MFRCreativeTab;
import powercrystals.minefactoryreloaded.tile.TileRedstoneCable;
import powercrystals.minefactoryreloaded.tile.TileRedstoneCable.ConnectionState;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.client.renderer.texture.IconRegister;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraft.util.MovingObjectPosition;
import net.minecraft.util.Vec3;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.common.ForgeDirection;
public class BlockRedstoneCable extends BlockContainer
{
private static float _wireSize = 0.25F;
private static float _plateWidth = 14.0F / 16.0F;
private static float _plateDepth = 1.0F / 16.0F;
private static float _bandWidth = 5.0F / 16.0F;
private static float _bandOffset = 2.0F / 16.0F;
private static float _bandDepth = 1.0F / 16.0F;
private static float _wireStart = 0.5F - _wireSize / 2.0F;
private static float _wireEnd = 0.5F + _wireSize / 2.0F;
private static float _plateStart = 0.5F - _plateWidth / 2.0F;
private static float _plateEnd = 0.5F + _plateWidth / 2.0F;
private static float _bandWidthStart = 0.5F - _bandWidth / 2.0F;
private static float _bandWidthEnd = 0.5F + _bandWidth / 2.0F;
private static float _bandDepthStart = _bandOffset;
private static float _bandDepthEnd = _bandOffset + _bandDepth;
private static int[] _partSideMappings = new int[] { -1, -1, -1, -1, -1, -1, -1, -1, -1, 4, 5, 0, 1, 2, 3 };
public BlockRedstoneCable(int id)
{
super(id, Material.clay);
setUnlocalizedName("mfr.cable.redstone");
setHardness(0.8F);
setCreativeTab(MFRCreativeTab.tab);
}
private AxisAlignedBB[] getParts(TileRedstoneCable cable)
{
ConnectionState csu = cable.getConnectionState(ForgeDirection.UP);
ConnectionState csd = cable.getConnectionState(ForgeDirection.DOWN);
ConnectionState csn = cable.getConnectionState(ForgeDirection.NORTH);
ConnectionState css = cable.getConnectionState(ForgeDirection.SOUTH);
ConnectionState csw = cable.getConnectionState(ForgeDirection.WEST);
ConnectionState cse = cable.getConnectionState(ForgeDirection.EAST);
AxisAlignedBB[] parts = new AxisAlignedBB[15];
parts[0] = AxisAlignedBB.getBoundingBox(csw != ConnectionState.None ? 0 : _wireStart, _wireStart, _wireStart, cse != ConnectionState.None ? 1 : _wireEnd, _wireEnd, _wireEnd);
parts[1] = AxisAlignedBB.getBoundingBox(_wireStart, csd != ConnectionState.None ? 0 : _wireStart, _wireStart, _wireEnd, csu != ConnectionState.None ? 1 : _wireEnd, _wireEnd);
parts[2] = AxisAlignedBB.getBoundingBox(_wireStart, _wireStart, csn != ConnectionState.None ? 0 : _wireStart, _wireEnd, _wireEnd, css != ConnectionState.None ? 1 : _wireEnd);
parts[3] = csw != ConnectionState.FlatSingle ? null : AxisAlignedBB.getBoundingBox(0, _plateStart, _plateStart, _plateDepth, _plateEnd, _plateEnd);
parts[4] = cse != ConnectionState.FlatSingle ? null : AxisAlignedBB.getBoundingBox(1.0F - _plateDepth, _plateStart, _plateStart, 1.0F, _plateEnd, _plateEnd);
parts[5] = csd != ConnectionState.FlatSingle ? null : AxisAlignedBB.getBoundingBox(_plateStart, 0 , _plateStart, _plateEnd, _plateDepth, _plateEnd);
parts[6] = csu != ConnectionState.FlatSingle ? null : AxisAlignedBB.getBoundingBox(_plateStart, 1.0F - _plateDepth, _plateStart, _plateEnd, 1.0F, _plateEnd);
parts[7] = csn != ConnectionState.FlatSingle ? null : AxisAlignedBB.getBoundingBox(_plateStart, _plateStart, 0, _plateEnd, _plateDepth, _plateEnd);
parts[8] = css != ConnectionState.FlatSingle ? null : AxisAlignedBB.getBoundingBox(_plateStart, _plateStart, 1.0F - _plateDepth, _plateEnd, _plateEnd, 1.0F);
parts[9] = csw != ConnectionState.FlatSingle && csw != ConnectionState.CableSingle ? null : AxisAlignedBB.getBoundingBox(_bandDepthStart, _bandWidthStart, _bandWidthStart, _bandDepthEnd, _bandWidthEnd, _bandWidthEnd);
parts[10] = cse != ConnectionState.FlatSingle && cse != ConnectionState.CableSingle ? null : AxisAlignedBB.getBoundingBox(1.0F - _bandDepthEnd, _bandWidthStart, _bandWidthStart, 1.0F - _bandDepthStart, _bandDepthEnd, _bandWidthEnd);
parts[11] = csd != ConnectionState.FlatSingle && csd != ConnectionState.CableSingle ? null : AxisAlignedBB.getBoundingBox(_bandWidthStart, _bandDepthStart, _bandWidthStart, _bandWidthEnd, _bandDepthEnd, _bandWidthEnd);
parts[12] = csu != ConnectionState.FlatSingle && csu != ConnectionState.CableSingle ? null : AxisAlignedBB.getBoundingBox(_bandWidthStart, 1.0F - _bandDepthEnd, _bandWidthStart, _bandWidthEnd, 1.0F - _bandDepthStart, _bandWidthEnd);
parts[13] = csn != ConnectionState.FlatSingle && csn != ConnectionState.CableSingle ? null : AxisAlignedBB.getBoundingBox(_bandWidthStart, _bandWidthStart, _bandDepthStart, _bandWidthEnd, _bandWidthEnd, _bandDepthEnd);
parts[14] = css != ConnectionState.FlatSingle && css != ConnectionState.CableSingle ? null : AxisAlignedBB.getBoundingBox(_bandWidthStart, _bandWidthStart, 1.0F - _bandDepthEnd, _bandWidthEnd, _bandWidthEnd, 1.0F - _bandDepthStart);
return parts;
}
private int getPartClicked(EntityPlayer player, double reachDistance, TileRedstoneCable cable)
{
AxisAlignedBB[] wireparts = getParts(cable);
Vec3 playerPosition = Vec3.createVectorHelper(player.posX - cable.xCoord, player.posY - cable.yCoord + player.getEyeHeight(), player.posZ - cable.zCoord);
Vec3 playerLook = player.getLookVec();
Vec3 playerViewOffset = Vec3.createVectorHelper(playerPosition.xCoord + playerLook.xCoord * reachDistance, playerPosition.yCoord + playerLook.yCoord * reachDistance, playerPosition.zCoord + playerLook.zCoord * reachDistance);
int closest = -1;
double closestdistance = Double.MAX_VALUE;
for(int i = 0; i < wireparts.length; i++)
{
AxisAlignedBB part = wireparts[i];
if(part == null)
{
continue;
}
MovingObjectPosition hit = part.calculateIntercept(playerPosition, playerViewOffset);
if(hit != null)
{
double distance = playerPosition.distanceTo(hit.hitVec);
if(distance < closestdistance)
{
distance = closestdistance;
closest = i;
}
}
}
return closest;
}
@Override
public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float xOffset, float yOffset, float zOffset)
{
TileEntity te = world.getBlockTileEntity(x, y, z);
if(te != null && te instanceof TileRedstoneCable)
{
TileRedstoneCable cable = (TileRedstoneCable)te;
int subHit = getPartClicked(player, 3.0F, cable);
if(subHit >= 9)
{
- if(!world.isRemote)
+ ItemStack s = player.inventory.getCurrentItem();
+ if(s != null && s.getItem() instanceof IToolHammer)
{
- ItemStack s = player.inventory.getCurrentItem();
- if(s != null && s.getItem() instanceof IToolHammer)
+ if(!world.isRemote)
{
side = _partSideMappings[subHit];
int nextColor = cable.getSideColor(ForgeDirection.VALID_DIRECTIONS[side]) + 1;
if(nextColor > 15) nextColor = 0;
cable.setSideColor(ForgeDirection.VALID_DIRECTIONS[side], nextColor);
world.markBlockForUpdate(x, y, z);
+ return true;
}
- else if(s != null && s.itemID == Item.dyePowder.itemID)
+ }
+ else if(s != null && s.itemID == Item.dyePowder.itemID)
+ {
+ if(!world.isRemote)
{
side = _partSideMappings[subHit];
- cable.setSideColor(ForgeDirection.VALID_DIRECTIONS[side], 16 - s.getItemDamage());
+ cable.setSideColor(ForgeDirection.VALID_DIRECTIONS[side], s.getItemDamage());
world.markBlockForUpdate(x, y, z);
+ return true;
}
}
- return true;
}
}
return false;
}
@Override
public void setBlockBoundsBasedOnState(IBlockAccess world, int x, int y, int z)
{
super.setBlockBoundsBasedOnState(world, x, y, z);
/*
TileEntity te = world.getBlockTileEntity(x, y, z);
if(te != null && te instanceof TileRedstoneCable)
{
TileRedstoneCable cable = (TileRedstoneCable)te;
float xMin = cable.getConnectionState(ForgeDirection.WEST) != ConnectionState.None ? 0 : 0.375F;
float xMax = cable.getConnectionState(ForgeDirection.EAST) != ConnectionState.None ? 1 : 0.625F;
float yMin = cable.getConnectionState(ForgeDirection.DOWN) != ConnectionState.None ? 0 : 0.375F;
float yMax = cable.getConnectionState(ForgeDirection.UP) != ConnectionState.None ? 1 : 0.625F;
float zMin = cable.getConnectionState(ForgeDirection.NORTH) != ConnectionState.None ? 0 : 0.375F;
float zMax = cable.getConnectionState(ForgeDirection.SOUTH) != ConnectionState.None ? 1 : 0.625F;
setBlockBounds(xMin, yMin, zMin, xMax, yMax, zMax);
}*/
}
@Override
public boolean isOpaqueCube()
{
return false;
}
@Override
public boolean renderAsNormalBlock()
{
return false;
}
@Override
public void onNeighborBlockChange(World world, int x, int y, int z, int blockId)
{
super.onNeighborBlockChange(world, x, y, z, blockId);
TileEntity te = world.getBlockTileEntity(x, y, z);
if(te != null && te instanceof TileRedstoneCable)
{
((TileRedstoneCable)te).onNeighboorChanged();
}
}
@Override
public void breakBlock(World world, int x, int y, int z, int id, int meta)
{
TileEntity te = world.getBlockTileEntity(x, y, z);
if(te != null && te instanceof TileRedstoneCable && ((TileRedstoneCable)te).getNetwork() != null)
{
((TileRedstoneCable)te).getNetwork().setInvalid();
}
super.breakBlock(world, x, y, z, id, meta);
}
@Override
public int isProvidingWeakPower(IBlockAccess world, int x, int y, int z, int side)
{
int power = 0;
TileEntity te = world.getBlockTileEntity(x, y, z);
if(te != null && te instanceof TileRedstoneCable && ((TileRedstoneCable)te).getNetwork() != null)
{
int subnet = ((TileRedstoneCable)te).getSideColor(ForgeDirection.VALID_DIRECTIONS[side].getOpposite());
power = ((TileRedstoneCable)te).getNetwork().getPowerLevelOutput(subnet);
//System.out.println("Asked for weak power at " + x + "," + y + "," + z + " - got " + power + " from network " + ((TileRedstoneCable)te).getNetwork().getId() + ":" + subnet);
}
return power;
}
@Override
public int isProvidingStrongPower(IBlockAccess world, int x, int y, int z, int side)
{
int power = 0;
TileEntity te = world.getBlockTileEntity(x, y, z);
if(te != null && te instanceof TileRedstoneCable && ((TileRedstoneCable)te).getNetwork() != null)
{
int subnet = ((TileRedstoneCable)te).getSideColor(ForgeDirection.VALID_DIRECTIONS[side].getOpposite());
power = ((TileRedstoneCable)te).getNetwork().getPowerLevelOutput(subnet);
//System.out.println("Asked for strong power at " + x + "," + y + "," + z + " - got " + power + " from network " + ((TileRedstoneCable)te).getNetwork().getId() + ":" + subnet);
}
return power;
}
@Override
public boolean isBlockSolidOnSide(World world, int x, int y, int z, ForgeDirection side)
{
return true;
}
@Override
public boolean canProvidePower()
{
return true;
}
@Override
public TileEntity createNewTileEntity(World world)
{
return new TileRedstoneCable();
}
@Override
public int getRenderType()
{
return MineFactoryReloadedCore.renderIdRedstoneCable;
}
@Override
@SideOnly(Side.CLIENT)
public void registerIcons(IconRegister ir)
{
blockIcon = ir.registerIcon("powercrystals/minefactoryreloaded/" + getUnlocalizedName());
}
}
| false | true | public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float xOffset, float yOffset, float zOffset)
{
TileEntity te = world.getBlockTileEntity(x, y, z);
if(te != null && te instanceof TileRedstoneCable)
{
TileRedstoneCable cable = (TileRedstoneCable)te;
int subHit = getPartClicked(player, 3.0F, cable);
if(subHit >= 9)
{
if(!world.isRemote)
{
ItemStack s = player.inventory.getCurrentItem();
if(s != null && s.getItem() instanceof IToolHammer)
{
side = _partSideMappings[subHit];
int nextColor = cable.getSideColor(ForgeDirection.VALID_DIRECTIONS[side]) + 1;
if(nextColor > 15) nextColor = 0;
cable.setSideColor(ForgeDirection.VALID_DIRECTIONS[side], nextColor);
world.markBlockForUpdate(x, y, z);
}
else if(s != null && s.itemID == Item.dyePowder.itemID)
{
side = _partSideMappings[subHit];
cable.setSideColor(ForgeDirection.VALID_DIRECTIONS[side], 16 - s.getItemDamage());
world.markBlockForUpdate(x, y, z);
}
}
return true;
}
}
return false;
}
| public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float xOffset, float yOffset, float zOffset)
{
TileEntity te = world.getBlockTileEntity(x, y, z);
if(te != null && te instanceof TileRedstoneCable)
{
TileRedstoneCable cable = (TileRedstoneCable)te;
int subHit = getPartClicked(player, 3.0F, cable);
if(subHit >= 9)
{
ItemStack s = player.inventory.getCurrentItem();
if(s != null && s.getItem() instanceof IToolHammer)
{
if(!world.isRemote)
{
side = _partSideMappings[subHit];
int nextColor = cable.getSideColor(ForgeDirection.VALID_DIRECTIONS[side]) + 1;
if(nextColor > 15) nextColor = 0;
cable.setSideColor(ForgeDirection.VALID_DIRECTIONS[side], nextColor);
world.markBlockForUpdate(x, y, z);
return true;
}
}
else if(s != null && s.itemID == Item.dyePowder.itemID)
{
if(!world.isRemote)
{
side = _partSideMappings[subHit];
cable.setSideColor(ForgeDirection.VALID_DIRECTIONS[side], s.getItemDamage());
world.markBlockForUpdate(x, y, z);
return true;
}
}
}
}
return false;
}
|
diff --git a/studio-schemaeditor/src/main/java/org/apache/directory/studio/schemaeditor/view/views/ProblemsViewLabelProvider.java b/studio-schemaeditor/src/main/java/org/apache/directory/studio/schemaeditor/view/views/ProblemsViewLabelProvider.java
index efdef6f9d..b6a52b53c 100644
--- a/studio-schemaeditor/src/main/java/org/apache/directory/studio/schemaeditor/view/views/ProblemsViewLabelProvider.java
+++ b/studio-schemaeditor/src/main/java/org/apache/directory/studio/schemaeditor/view/views/ProblemsViewLabelProvider.java
@@ -1,309 +1,309 @@
/*
* 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.directory.studio.schemaeditor.view.views;
import org.apache.directory.shared.ldap.schema.ObjectClassTypeEnum;
import org.apache.directory.shared.ldap.schema.SchemaObject;
import org.apache.directory.studio.schemaeditor.Activator;
import org.apache.directory.studio.schemaeditor.PluginConstants;
import org.apache.directory.studio.schemaeditor.model.AttributeTypeImpl;
import org.apache.directory.studio.schemaeditor.model.ObjectClassImpl;
import org.apache.directory.studio.schemaeditor.model.schemachecker.ClassTypeHierarchyError;
import org.apache.directory.studio.schemaeditor.model.schemachecker.DifferentCollectiveAsSuperiorError;
import org.apache.directory.studio.schemaeditor.model.schemachecker.DifferentUsageAsSuperiorError;
import org.apache.directory.studio.schemaeditor.model.schemachecker.DuplicateAliasError;
import org.apache.directory.studio.schemaeditor.model.schemachecker.DuplicateOidError;
import org.apache.directory.studio.schemaeditor.model.schemachecker.NoAliasWarning;
import org.apache.directory.studio.schemaeditor.model.schemachecker.NonExistingATSuperiorError;
import org.apache.directory.studio.schemaeditor.model.schemachecker.NonExistingMandatoryATError;
import org.apache.directory.studio.schemaeditor.model.schemachecker.NonExistingMatchingRuleError;
import org.apache.directory.studio.schemaeditor.model.schemachecker.NonExistingOCSuperiorError;
import org.apache.directory.studio.schemaeditor.model.schemachecker.NonExistingOptionalATError;
import org.apache.directory.studio.schemaeditor.model.schemachecker.NonExistingSyntaxError;
import org.apache.directory.studio.schemaeditor.model.schemachecker.SchemaCheckerElement;
import org.apache.directory.studio.schemaeditor.view.wrappers.Folder;
import org.apache.directory.studio.schemaeditor.view.wrappers.SchemaErrorWrapper;
import org.apache.directory.studio.schemaeditor.view.wrappers.SchemaWarningWrapper;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.plugin.AbstractUIPlugin;
/**
* This class implements the LabelProvider for the SchemaView.
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
* @version $Rev$, $Date$
*/
public class ProblemsViewLabelProvider extends LabelProvider implements ITableLabelProvider
{
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnImage(java.lang.Object, int)
*/
public Image getColumnImage( Object element, int columnIndex )
{
if ( columnIndex == 0 )
{
if ( element instanceof SchemaErrorWrapper )
{
return AbstractUIPlugin.imageDescriptorFromPlugin( Activator.PLUGIN_ID,
PluginConstants.IMG_PROBLEMS_ERROR ).createImage();
}
else if ( element instanceof SchemaWarningWrapper )
{
return AbstractUIPlugin.imageDescriptorFromPlugin( Activator.PLUGIN_ID,
PluginConstants.IMG_PROBLEMS_WARNING ).createImage();
}
else if ( element instanceof Folder )
{
return AbstractUIPlugin.imageDescriptorFromPlugin( Activator.PLUGIN_ID,
PluginConstants.IMG_PROBLEMS_GROUP ).createImage();
}
}
// Default
return null;
}
/* (non-Javadoc)
* @see org.eclipse.jface.viewers.ITableLabelProvider#getColumnText(java.lang.Object, int)
*/
public String getColumnText( Object element, int columnIndex )
{
if ( element instanceof SchemaErrorWrapper )
{
SchemaErrorWrapper errorWrapper = ( SchemaErrorWrapper ) element;
if ( columnIndex == 0 )
{
return getMessage( errorWrapper.getSchemaError() );
}
else if ( columnIndex == 1 )
{
return getDisplayName( errorWrapper.getSchemaError().getSource() );
}
}
else if ( element instanceof SchemaWarningWrapper )
{
SchemaWarningWrapper warningWrapper = ( SchemaWarningWrapper ) element;
if ( columnIndex == 0 )
{
return getMessage( warningWrapper.getSchemaWarning() );
}
else if ( columnIndex == 1 )
{
String name = warningWrapper.getSchemaWarning().getSource().getName();
if ( ( name != null ) && ( !name.equals( "" ) ) )
{
return name;
}
else
{
return warningWrapper.getSchemaWarning().getSource().getOid();
}
}
}
else if ( element instanceof Folder )
{
Folder folder = ( Folder ) element;
if ( columnIndex == 0 )
{
return folder.getName() + " (" + folder.getChildren().size() + ")";
}
else
{
return "";
}
}
// Default
return element.toString();
}
private String getMessage( SchemaCheckerElement element )
{
StringBuffer message = new StringBuffer();
if ( element instanceof DuplicateAliasError )
{
DuplicateAliasError duplicateAliasError = ( DuplicateAliasError ) element;
message.append( "Alias '" + duplicateAliasError.getAlias() + "' is already used by another item: " );
SchemaObject duplicate = duplicateAliasError.getDuplicate();
if ( duplicate instanceof AttributeTypeImpl )
{
message.append( "attribute type" );
}
else if ( duplicate instanceof ObjectClassImpl )
{
message.append( "object class" );
}
message.append( " with OID '" + duplicate.getOid() + "'." );
}
else if ( element instanceof DuplicateOidError )
{
DuplicateOidError duplicateOidError = ( DuplicateOidError ) element;
message.append( "OID '" + duplicateOidError.getOid() + "' is already used by another item: " );
SchemaObject duplicate = duplicateOidError.getDuplicate();
if ( duplicate instanceof AttributeTypeImpl )
{
message.append( "attribute type" );
}
else if ( duplicate instanceof ObjectClassImpl )
{
message.append( "object class" );
}
message.append( " with alias '" + duplicate.getName() + "'." );
}
else if ( element instanceof NonExistingATSuperiorError )
{
NonExistingATSuperiorError nonExistingATSuperiorError = ( NonExistingATSuperiorError ) element;
message.append( "Superior attribute type '" + nonExistingATSuperiorError.getSuperiorAlias()
+ "' does not exist." );
}
else if ( element instanceof NonExistingOCSuperiorError )
{
NonExistingOCSuperiorError nonExistingOCSuperiorError = ( NonExistingOCSuperiorError ) element;
message.append( "Superior object class '" + nonExistingOCSuperiorError.getSuperiorAlias()
+ "' does not exist." );
}
else if ( element instanceof NonExistingMandatoryATError )
{
NonExistingMandatoryATError nonExistingMandatoryATError = ( NonExistingMandatoryATError ) element;
message
.append( "Mandatory attribute type '" + nonExistingMandatoryATError.getAlias() + "' does not exist." );
}
else if ( element instanceof NonExistingOptionalATError )
{
NonExistingOptionalATError nonExistingOptionalATError = ( NonExistingOptionalATError ) element;
message.append( "Optional attribute type '" + nonExistingOptionalATError.getAlias() + "' does not exist." );
}
else if ( element instanceof NonExistingSyntaxError )
{
NonExistingSyntaxError nonExistingSyntaxError = ( NonExistingSyntaxError ) element;
message.append( "Syntax with OID '" + nonExistingSyntaxError.getSyntaxOid() + "' does not exist." );
}
else if ( element instanceof NonExistingMatchingRuleError )
{
NonExistingMatchingRuleError nonExistingMatchingRuleError = ( NonExistingMatchingRuleError ) element;
message.append( "Matching rule '" + nonExistingMatchingRuleError.getMatchingRuleAlias()
+ "' does not exist." );
}
else if ( element instanceof NoAliasWarning )
{
NoAliasWarning noAliasWarning = ( NoAliasWarning ) element;
SchemaObject source = noAliasWarning.getSource();
if ( source instanceof AttributeTypeImpl )
{
message.append( "Attribute type" );
}
else if ( source instanceof ObjectClassImpl )
{
message.append( "Object class" );
}
message.append( " with OID '" + source.getOid() + "' does not have any alias." );
}
else if ( element instanceof ClassTypeHierarchyError )
{
ClassTypeHierarchyError classTypeHierarchyError = ( ClassTypeHierarchyError ) element;
ObjectClassImpl source = ( ObjectClassImpl ) classTypeHierarchyError.getSource();
ObjectClassImpl superior = ( ObjectClassImpl ) classTypeHierarchyError.getSuperior();
if ( source.getType().equals( ObjectClassTypeEnum.ABSTRACT ) )
{
- message.append( "Abstract object class �" + getDisplayName( source ) + "' can not extend " );
+ message.append( "Abstract object class '" + getDisplayName( source ) + "' can not extend " );
if ( superior.getType().equals( ObjectClassTypeEnum.STRUCTURAL ) )
{
message.append( "Structural object class :'" + getDisplayName( superior ) + "'." );
}
else if ( superior.getType().equals( ObjectClassTypeEnum.AUXILIARY ) )
{
message.append( "Auxiliary object class :'" + getDisplayName( superior ) + "'." );
}
}
else if ( source.getType().equals( ObjectClassTypeEnum.AUXILIARY ) )
{
- message.append( "Auxiliary object class �" + getDisplayName( source ) + "' can not extend " );
+ message.append( "Auxiliary object class '" + getDisplayName( source ) + "' can not extend " );
if ( superior.getType().equals( ObjectClassTypeEnum.STRUCTURAL ) )
{
message.append( "Structural object class :'" + getDisplayName( superior ) + "'." );
}
}
}
else if ( element instanceof DifferentUsageAsSuperiorError )
{
DifferentUsageAsSuperiorError differentUsageAsSuperiorError = ( DifferentUsageAsSuperiorError ) element;
AttributeTypeImpl source = ( AttributeTypeImpl ) differentUsageAsSuperiorError.getSource();
AttributeTypeImpl superior = ( AttributeTypeImpl ) differentUsageAsSuperiorError.getSuperior();
message.append( "Attribute type '" + getDisplayName( source )
+ "' has a different usage value than its superior '" + getDisplayName( superior ) + "'." );
}
else if ( element instanceof DifferentCollectiveAsSuperiorError )
{
DifferentCollectiveAsSuperiorError differentCollectiveAsSuperiorError = ( DifferentCollectiveAsSuperiorError ) element;
AttributeTypeImpl source = ( AttributeTypeImpl ) differentCollectiveAsSuperiorError.getSource();
AttributeTypeImpl superior = ( AttributeTypeImpl ) differentCollectiveAsSuperiorError.getSuperior();
message.append( "Attribute type '" + getDisplayName( source ) + "' must be collective as its superior '"
+ getDisplayName( superior ) + "'." );
}
return message.toString();
}
/**
* Gets the displayable name of the given SchemaObject.
*
* @param so
* the SchemaObject
* @return
* the displayable name of the given SchemaObject
*/
private String getDisplayName( SchemaObject so )
{
String name = so.getName();
if ( ( name != null ) && ( !name.equals( "" ) ) )
{
return name;
}
else
{
return so.getOid();
}
}
}
| false | true | private String getMessage( SchemaCheckerElement element )
{
StringBuffer message = new StringBuffer();
if ( element instanceof DuplicateAliasError )
{
DuplicateAliasError duplicateAliasError = ( DuplicateAliasError ) element;
message.append( "Alias '" + duplicateAliasError.getAlias() + "' is already used by another item: " );
SchemaObject duplicate = duplicateAliasError.getDuplicate();
if ( duplicate instanceof AttributeTypeImpl )
{
message.append( "attribute type" );
}
else if ( duplicate instanceof ObjectClassImpl )
{
message.append( "object class" );
}
message.append( " with OID '" + duplicate.getOid() + "'." );
}
else if ( element instanceof DuplicateOidError )
{
DuplicateOidError duplicateOidError = ( DuplicateOidError ) element;
message.append( "OID '" + duplicateOidError.getOid() + "' is already used by another item: " );
SchemaObject duplicate = duplicateOidError.getDuplicate();
if ( duplicate instanceof AttributeTypeImpl )
{
message.append( "attribute type" );
}
else if ( duplicate instanceof ObjectClassImpl )
{
message.append( "object class" );
}
message.append( " with alias '" + duplicate.getName() + "'." );
}
else if ( element instanceof NonExistingATSuperiorError )
{
NonExistingATSuperiorError nonExistingATSuperiorError = ( NonExistingATSuperiorError ) element;
message.append( "Superior attribute type '" + nonExistingATSuperiorError.getSuperiorAlias()
+ "' does not exist." );
}
else if ( element instanceof NonExistingOCSuperiorError )
{
NonExistingOCSuperiorError nonExistingOCSuperiorError = ( NonExistingOCSuperiorError ) element;
message.append( "Superior object class '" + nonExistingOCSuperiorError.getSuperiorAlias()
+ "' does not exist." );
}
else if ( element instanceof NonExistingMandatoryATError )
{
NonExistingMandatoryATError nonExistingMandatoryATError = ( NonExistingMandatoryATError ) element;
message
.append( "Mandatory attribute type '" + nonExistingMandatoryATError.getAlias() + "' does not exist." );
}
else if ( element instanceof NonExistingOptionalATError )
{
NonExistingOptionalATError nonExistingOptionalATError = ( NonExistingOptionalATError ) element;
message.append( "Optional attribute type '" + nonExistingOptionalATError.getAlias() + "' does not exist." );
}
else if ( element instanceof NonExistingSyntaxError )
{
NonExistingSyntaxError nonExistingSyntaxError = ( NonExistingSyntaxError ) element;
message.append( "Syntax with OID '" + nonExistingSyntaxError.getSyntaxOid() + "' does not exist." );
}
else if ( element instanceof NonExistingMatchingRuleError )
{
NonExistingMatchingRuleError nonExistingMatchingRuleError = ( NonExistingMatchingRuleError ) element;
message.append( "Matching rule '" + nonExistingMatchingRuleError.getMatchingRuleAlias()
+ "' does not exist." );
}
else if ( element instanceof NoAliasWarning )
{
NoAliasWarning noAliasWarning = ( NoAliasWarning ) element;
SchemaObject source = noAliasWarning.getSource();
if ( source instanceof AttributeTypeImpl )
{
message.append( "Attribute type" );
}
else if ( source instanceof ObjectClassImpl )
{
message.append( "Object class" );
}
message.append( " with OID '" + source.getOid() + "' does not have any alias." );
}
else if ( element instanceof ClassTypeHierarchyError )
{
ClassTypeHierarchyError classTypeHierarchyError = ( ClassTypeHierarchyError ) element;
ObjectClassImpl source = ( ObjectClassImpl ) classTypeHierarchyError.getSource();
ObjectClassImpl superior = ( ObjectClassImpl ) classTypeHierarchyError.getSuperior();
if ( source.getType().equals( ObjectClassTypeEnum.ABSTRACT ) )
{
message.append( "Abstract object class �" + getDisplayName( source ) + "' can not extend " );
if ( superior.getType().equals( ObjectClassTypeEnum.STRUCTURAL ) )
{
message.append( "Structural object class :'" + getDisplayName( superior ) + "'." );
}
else if ( superior.getType().equals( ObjectClassTypeEnum.AUXILIARY ) )
{
message.append( "Auxiliary object class :'" + getDisplayName( superior ) + "'." );
}
}
else if ( source.getType().equals( ObjectClassTypeEnum.AUXILIARY ) )
{
message.append( "Auxiliary object class �" + getDisplayName( source ) + "' can not extend " );
if ( superior.getType().equals( ObjectClassTypeEnum.STRUCTURAL ) )
{
message.append( "Structural object class :'" + getDisplayName( superior ) + "'." );
}
}
}
else if ( element instanceof DifferentUsageAsSuperiorError )
{
DifferentUsageAsSuperiorError differentUsageAsSuperiorError = ( DifferentUsageAsSuperiorError ) element;
AttributeTypeImpl source = ( AttributeTypeImpl ) differentUsageAsSuperiorError.getSource();
AttributeTypeImpl superior = ( AttributeTypeImpl ) differentUsageAsSuperiorError.getSuperior();
message.append( "Attribute type '" + getDisplayName( source )
+ "' has a different usage value than its superior '" + getDisplayName( superior ) + "'." );
}
else if ( element instanceof DifferentCollectiveAsSuperiorError )
{
DifferentCollectiveAsSuperiorError differentCollectiveAsSuperiorError = ( DifferentCollectiveAsSuperiorError ) element;
AttributeTypeImpl source = ( AttributeTypeImpl ) differentCollectiveAsSuperiorError.getSource();
AttributeTypeImpl superior = ( AttributeTypeImpl ) differentCollectiveAsSuperiorError.getSuperior();
message.append( "Attribute type '" + getDisplayName( source ) + "' must be collective as its superior '"
+ getDisplayName( superior ) + "'." );
}
return message.toString();
}
| private String getMessage( SchemaCheckerElement element )
{
StringBuffer message = new StringBuffer();
if ( element instanceof DuplicateAliasError )
{
DuplicateAliasError duplicateAliasError = ( DuplicateAliasError ) element;
message.append( "Alias '" + duplicateAliasError.getAlias() + "' is already used by another item: " );
SchemaObject duplicate = duplicateAliasError.getDuplicate();
if ( duplicate instanceof AttributeTypeImpl )
{
message.append( "attribute type" );
}
else if ( duplicate instanceof ObjectClassImpl )
{
message.append( "object class" );
}
message.append( " with OID '" + duplicate.getOid() + "'." );
}
else if ( element instanceof DuplicateOidError )
{
DuplicateOidError duplicateOidError = ( DuplicateOidError ) element;
message.append( "OID '" + duplicateOidError.getOid() + "' is already used by another item: " );
SchemaObject duplicate = duplicateOidError.getDuplicate();
if ( duplicate instanceof AttributeTypeImpl )
{
message.append( "attribute type" );
}
else if ( duplicate instanceof ObjectClassImpl )
{
message.append( "object class" );
}
message.append( " with alias '" + duplicate.getName() + "'." );
}
else if ( element instanceof NonExistingATSuperiorError )
{
NonExistingATSuperiorError nonExistingATSuperiorError = ( NonExistingATSuperiorError ) element;
message.append( "Superior attribute type '" + nonExistingATSuperiorError.getSuperiorAlias()
+ "' does not exist." );
}
else if ( element instanceof NonExistingOCSuperiorError )
{
NonExistingOCSuperiorError nonExistingOCSuperiorError = ( NonExistingOCSuperiorError ) element;
message.append( "Superior object class '" + nonExistingOCSuperiorError.getSuperiorAlias()
+ "' does not exist." );
}
else if ( element instanceof NonExistingMandatoryATError )
{
NonExistingMandatoryATError nonExistingMandatoryATError = ( NonExistingMandatoryATError ) element;
message
.append( "Mandatory attribute type '" + nonExistingMandatoryATError.getAlias() + "' does not exist." );
}
else if ( element instanceof NonExistingOptionalATError )
{
NonExistingOptionalATError nonExistingOptionalATError = ( NonExistingOptionalATError ) element;
message.append( "Optional attribute type '" + nonExistingOptionalATError.getAlias() + "' does not exist." );
}
else if ( element instanceof NonExistingSyntaxError )
{
NonExistingSyntaxError nonExistingSyntaxError = ( NonExistingSyntaxError ) element;
message.append( "Syntax with OID '" + nonExistingSyntaxError.getSyntaxOid() + "' does not exist." );
}
else if ( element instanceof NonExistingMatchingRuleError )
{
NonExistingMatchingRuleError nonExistingMatchingRuleError = ( NonExistingMatchingRuleError ) element;
message.append( "Matching rule '" + nonExistingMatchingRuleError.getMatchingRuleAlias()
+ "' does not exist." );
}
else if ( element instanceof NoAliasWarning )
{
NoAliasWarning noAliasWarning = ( NoAliasWarning ) element;
SchemaObject source = noAliasWarning.getSource();
if ( source instanceof AttributeTypeImpl )
{
message.append( "Attribute type" );
}
else if ( source instanceof ObjectClassImpl )
{
message.append( "Object class" );
}
message.append( " with OID '" + source.getOid() + "' does not have any alias." );
}
else if ( element instanceof ClassTypeHierarchyError )
{
ClassTypeHierarchyError classTypeHierarchyError = ( ClassTypeHierarchyError ) element;
ObjectClassImpl source = ( ObjectClassImpl ) classTypeHierarchyError.getSource();
ObjectClassImpl superior = ( ObjectClassImpl ) classTypeHierarchyError.getSuperior();
if ( source.getType().equals( ObjectClassTypeEnum.ABSTRACT ) )
{
message.append( "Abstract object class '" + getDisplayName( source ) + "' can not extend " );
if ( superior.getType().equals( ObjectClassTypeEnum.STRUCTURAL ) )
{
message.append( "Structural object class :'" + getDisplayName( superior ) + "'." );
}
else if ( superior.getType().equals( ObjectClassTypeEnum.AUXILIARY ) )
{
message.append( "Auxiliary object class :'" + getDisplayName( superior ) + "'." );
}
}
else if ( source.getType().equals( ObjectClassTypeEnum.AUXILIARY ) )
{
message.append( "Auxiliary object class '" + getDisplayName( source ) + "' can not extend " );
if ( superior.getType().equals( ObjectClassTypeEnum.STRUCTURAL ) )
{
message.append( "Structural object class :'" + getDisplayName( superior ) + "'." );
}
}
}
else if ( element instanceof DifferentUsageAsSuperiorError )
{
DifferentUsageAsSuperiorError differentUsageAsSuperiorError = ( DifferentUsageAsSuperiorError ) element;
AttributeTypeImpl source = ( AttributeTypeImpl ) differentUsageAsSuperiorError.getSource();
AttributeTypeImpl superior = ( AttributeTypeImpl ) differentUsageAsSuperiorError.getSuperior();
message.append( "Attribute type '" + getDisplayName( source )
+ "' has a different usage value than its superior '" + getDisplayName( superior ) + "'." );
}
else if ( element instanceof DifferentCollectiveAsSuperiorError )
{
DifferentCollectiveAsSuperiorError differentCollectiveAsSuperiorError = ( DifferentCollectiveAsSuperiorError ) element;
AttributeTypeImpl source = ( AttributeTypeImpl ) differentCollectiveAsSuperiorError.getSource();
AttributeTypeImpl superior = ( AttributeTypeImpl ) differentCollectiveAsSuperiorError.getSuperior();
message.append( "Attribute type '" + getDisplayName( source ) + "' must be collective as its superior '"
+ getDisplayName( superior ) + "'." );
}
return message.toString();
}
|
diff --git a/core/vdmj/src/main/java/org/overturetool/vdmj/debug/DBGPReader.java b/core/vdmj/src/main/java/org/overturetool/vdmj/debug/DBGPReader.java
index d980810b49..4431163f4d 100644
--- a/core/vdmj/src/main/java/org/overturetool/vdmj/debug/DBGPReader.java
+++ b/core/vdmj/src/main/java/org/overturetool/vdmj/debug/DBGPReader.java
@@ -1,2096 +1,2096 @@
/*******************************************************************************
*
* Copyright (c) 2009 Fujitsu Services Ltd.
*
* Author: Nick Battle
*
* This file is part of VDMJ.
*
* VDMJ 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.
*
* VDMJ 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 VDMJ. If not, see <http://www.gnu.org/licenses/>.
*
******************************************************************************/
package org.overturetool.vdmj.debug;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.Vector;
import java.util.Map.Entry;
import org.overturetool.vdmj.ExitStatus;
import org.overturetool.vdmj.Settings;
import org.overturetool.vdmj.VDMJ;
import org.overturetool.vdmj.VDMOV;
import org.overturetool.vdmj.VDMPP;
import org.overturetool.vdmj.VDMRT;
import org.overturetool.vdmj.VDMSL;
import org.overturetool.vdmj.definitions.ClassDefinition;
import org.overturetool.vdmj.definitions.ClassList;
import org.overturetool.vdmj.expressions.Expression;
import org.overturetool.vdmj.lex.Dialect;
import org.overturetool.vdmj.lex.LexException;
import org.overturetool.vdmj.lex.LexLocation;
import org.overturetool.vdmj.lex.LexNameToken;
import org.overturetool.vdmj.lex.LexToken;
import org.overturetool.vdmj.lex.LexTokenReader;
import org.overturetool.vdmj.lex.Token;
import org.overturetool.vdmj.messages.Console;
import org.overturetool.vdmj.messages.InternalException;
import org.overturetool.vdmj.messages.RTLogger;
import org.overturetool.vdmj.modules.Module;
import org.overturetool.vdmj.pog.ProofObligation;
import org.overturetool.vdmj.pog.ProofObligationList;
import org.overturetool.vdmj.runtime.Breakpoint;
import org.overturetool.vdmj.runtime.ClassContext;
import org.overturetool.vdmj.runtime.ClassInterpreter;
import org.overturetool.vdmj.runtime.Context;
import org.overturetool.vdmj.runtime.ContextException;
import org.overturetool.vdmj.runtime.DebuggerException;
import org.overturetool.vdmj.runtime.Interpreter;
import org.overturetool.vdmj.runtime.ModuleInterpreter;
import org.overturetool.vdmj.runtime.ObjectContext;
import org.overturetool.vdmj.runtime.RootContext;
import org.overturetool.vdmj.runtime.SourceFile;
import org.overturetool.vdmj.runtime.StateContext;
import org.overturetool.vdmj.statements.Statement;
import org.overturetool.vdmj.syntax.ParserException;
import org.overturetool.vdmj.util.Base64;
import org.overturetool.vdmj.values.NameValuePairMap;
import org.overturetool.vdmj.values.Value;
public class DBGPReader
{
private final String host;
private final int port;
private final String ideKey;
private final String expression;
private final Socket socket;
private final InputStream input;
private final OutputStream output;
private final Interpreter interpreter;
private int sessionId = 0;
private DBGPStatus status = null;
private DBGPReason statusReason = null;
private DBGPCommandType command = null;
private String transaction = "";
private DBGPFeatures features;
private byte separator = '\0';
private Context breakContext = null;
private Breakpoint breakpoint = null;
private Value theAnswer = null;
private boolean breaksSuspended = false;
private static final int SOURCE_LINES = 5;
public static void main(String[] args)
{
Settings.usingDBGP = true;
String host = null;
- int port = 0;
+ int port = -1;
String ideKey = null;
Settings.dialect = null;
String expression = null;
List<File> files = new Vector<File>();
List<String> largs = Arrays.asList(args);
VDMJ controller = null;
boolean warnings = true;
for (Iterator<String> i = largs.iterator(); i.hasNext();)
{
String arg = i.next();
if (arg.equals("-vdmsl"))
{
controller = new VDMSL();
}
else if (arg.equals("-vdmpp"))
{
controller = new VDMPP();
}
else if (arg.equals("-vdmrt"))
{
controller = new VDMRT();
}
else if (arg.equals("-overture"))
{
controller = new VDMOV();
}
else if (arg.equals("-h"))
{
if (i.hasNext())
{
host = i.next();
}
else
{
usage("-h option requires a hostname");
}
}
else if (arg.equals("-p"))
{
try
{
port = Integer.parseInt(i.next());
}
catch (Exception e)
{
usage("-p option requires a port");
}
}
else if (arg.equals("-k"))
{
if (i.hasNext())
{
ideKey = i.next();
}
else
{
usage("-k option requires a key");
}
}
else if (arg.equals("-e"))
{
if (i.hasNext())
{
expression = i.next();
}
else
{
usage("-e option requires an expression");
}
}
else if (arg.equals("-w"))
{
warnings = false;
}
else if (arg.startsWith("-"))
{
usage("Unknown option " + arg);
}
else
{
try
{
files.add(new File(new URI(arg)));
}
catch (URISyntaxException e)
{
usage(e.getMessage() + ": " + arg);
}
catch (IllegalArgumentException e)
{
usage(e.getMessage() + ": " + arg);
}
}
}
- if (host == null || port == 0 || controller == null ||
+ if (host == null || port == -1 || controller == null ||
ideKey == null || expression == null || Settings.dialect == null ||
files.isEmpty())
{
usage("Missing mandatory arguments");
}
controller.setWarnings(warnings);
if (controller.parse(files) == ExitStatus.EXIT_OK)
{
if (controller.typeCheck() == ExitStatus.EXIT_OK)
{
try
{
Interpreter i = controller.getInterpreter();
new DBGPReader(host, port, ideKey, i, expression).run(true);
System.exit(0);
}
catch (ContextException e)
{
System.out.println("Initialization: " + e);
e.ctxt.printStackTrace(Console.out, true);
System.exit(3);
}
catch (Exception e)
{
System.out.println("Initialization: " + e);
System.exit(3);
}
}
else
{
System.exit(2);
}
}
else
{
System.exit(1);
}
}
private static void usage(String string)
{
System.err.println(string);
System.err.println("Usage: -h <host> -p <port> -k <ide key> <-vdmpp|-vdmsl|-vdmrt> -e <expression> {<filename URLs>}");
System.exit(1);
}
public DBGPReader(
String host, int port, String ideKey,
Interpreter interpreter, String expression)
throws Exception
{
this.host = host;
this.port = port;
this.ideKey = ideKey;
this.expression = expression;
this.interpreter = interpreter;
if (port > 0)
{
InetAddress server = InetAddress.getByName(host);
socket = new Socket(server, port);
input = socket.getInputStream();
output = socket.getOutputStream();
}
else
{
socket = null;
input = System.in;
output = System.out;
separator = ' ';
}
init();
}
public DBGPReader newThread() throws Exception
{
DBGPReader r = new DBGPReader(host, port, ideKey, interpreter, null);
r.command = DBGPCommandType.UNKNOWN;
r.transaction = "?";
return r;
}
private void init() throws IOException
{
sessionId = Math.abs(new Random().nextInt());
status = DBGPStatus.STARTING;
statusReason = DBGPReason.OK;
features = new DBGPFeatures();
StringBuilder sb = new StringBuilder();
sb.append("<init ");
sb.append("appid=\"");
sb.append(features.getProperty("language_name"));
sb.append("\" ");
sb.append("idekey=\"" + ideKey + "\" ");
sb.append("session=\"" + sessionId + "\" ");
sb.append("thread=\"");
sb.append(Thread.currentThread().getId());
sb.append("\" ");
sb.append("parent=\"");
sb.append(features.getProperty("language_name"));
sb.append("\" ");
sb.append("language=\"");
sb.append(features.getProperty("language_name"));
sb.append("\" ");
sb.append("protocol_version=\"");
sb.append(features.getProperty("protocol_version"));
sb.append("\"");
Set<File> files = interpreter.getSourceFiles();
sb.append(" fileuri=\"");
sb.append(files.iterator().next().toURI()); // Any old one...
sb.append("\"");
sb.append("/>\n");
write(sb);
}
private String readLine() throws IOException
{
StringBuilder line = new StringBuilder();
int c = input.read();
while (c != '\n' && c > 0)
{
if (c != '\r') line.append((char)c); // Ignore CRs
c = input.read();
}
return (line.length() == 0 && c == -1) ? null : line.toString();
}
private void write(StringBuilder data) throws IOException
{
byte[] header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>".getBytes("UTF-8");
byte[] body = data.toString().getBytes("UTF-8");
byte[] size = Integer.toString(header.length + body.length).getBytes("UTF-8");
output.write(size);
output.write(separator);
output.write(header);
output.write(body);
output.write(separator);
output.flush();
}
private void response(StringBuilder hdr, StringBuilder body) throws IOException
{
StringBuilder sb = new StringBuilder();
sb.append("<response command=\"");
sb.append(command);
sb.append("\"");
if (hdr != null)
{
sb.append(" ");
sb.append(hdr);
}
sb.append(" transaction_id=\"");
sb.append(transaction);
sb.append("\"");
if (body != null)
{
sb.append(">");
sb.append(body);
sb.append("</response>\n");
}
else
{
sb.append("/>\n");
}
write(sb);
}
private void errorResponse(DBGPErrorCode errorCode, String reason)
{
try
{
StringBuilder sb = new StringBuilder();
sb.append("<error code=\"");
sb.append(errorCode.value);
sb.append("\" apperr=\"\"><message>");
sb.append(reason);
sb.append("</message></error>");
response(null, sb);
}
catch (IOException e)
{
throw new InternalException(29, "DBGP: " + reason);
}
}
private void statusResponse() throws IOException
{
statusResponse(status, statusReason);
}
private void statusResponse(DBGPStatus s, DBGPReason reason)
throws IOException
{
StringBuilder sb = new StringBuilder();
status = s;
statusReason = reason;
sb.append("status=\"");
sb.append(status);
sb.append("\"");
sb.append(" reason=\"");
sb.append(statusReason);
sb.append("\"");
response(sb, null);
}
private StringBuilder breakpointResponse(Breakpoint bp)
{
StringBuilder sb = new StringBuilder();
sb.append("<breakpoint id=\"" + bp.number + "\"");
sb.append(" type=\"line\"");
sb.append(" state=\"enabled\"");
sb.append(" filename=\"" + bp.location.file.toURI() + "\"");
sb.append(" lineno=\"" + bp.location.startLine + "\"");
sb.append(">");
if (bp.trace != null)
{
sb.append("<expression>" + quote(bp.trace) + "</expression>");
}
sb.append("</breakpoint>");
return sb;
}
private StringBuilder stackResponse(LexLocation location, int level)
{
StringBuilder sb = new StringBuilder();
sb.append("<stack level=\"" + level + "\"");
sb.append(" type=\"file\"");
sb.append(" filename=\"" + location.file.toURI() + "\"");
sb.append(" lineno=\"" + location.startLine + "\"");
sb.append(" cmdbegin=\"" + location.startLine + ":" + location.startPos + "\"");
sb.append("/>");
return sb;
}
private StringBuilder propertyResponse(NameValuePairMap vars)
throws UnsupportedEncodingException
{
StringBuilder sb = new StringBuilder();
for (Entry<LexNameToken, Value> e: vars.entrySet())
{
sb.append(propertyResponse(e.getKey(), e.getValue()));
}
return sb;
}
private StringBuilder propertyResponse(LexNameToken name, Value value)
throws UnsupportedEncodingException
{
return propertyResponse(
name.name, name.getExplicit(true).toString(),
name.module, value.toString());
}
private StringBuilder propertyResponse(
String name, String fullname, String clazz, String value)
throws UnsupportedEncodingException
{
StringBuilder sb = new StringBuilder();
sb.append("<property");
sb.append(" name=\"" + quote(name) + "\"");
sb.append(" fullname=\"" + quote(fullname) + "\"");
sb.append(" type=\"string\"");
sb.append(" classname=\"" + clazz + "\"");
sb.append(" constant=\"0\"");
sb.append(" children=\"0\"");
sb.append(" size=\"" + value.length() + "\"");
sb.append(" encoding=\"base64\"");
sb.append("><![CDATA[");
sb.append(Base64.encode(value.getBytes("UTF-8")));
sb.append("]]></property>");
return sb;
}
private void cdataResponse(String msg) throws IOException
{
// Send back a CDATA response with a plain message
response(null, new StringBuilder("<![CDATA[" + quote(msg) + "]]>"));
}
private static String quote(String in)
{
return in
.replaceAll("&", "&")
.replaceAll("<", "<")
.replaceAll(">", ">")
.replaceAll("\\\"", """);
}
private void run(boolean init) throws IOException
{
if (init)
{
interpreter.init(this);
}
String line = null;
do
{
line = readLine();
}
while (line != null && process(line));
}
public void stopped(Context ctxt, Breakpoint bp)
{
if (breaksSuspended)
{
return; // We're inside an eval command, so don't stop
}
try
{
breakContext = ctxt;
breakpoint = bp;
statusResponse(DBGPStatus.BREAK, DBGPReason.OK);
run(false);
breakContext = null;
breakpoint = null;
}
catch (Exception e)
{
errorResponse(DBGPErrorCode.INTERNAL_ERROR, e.getMessage());
}
}
public void tracing(String display)
{
try
{
cdataResponse(display);
}
catch (Exception e)
{
errorResponse(DBGPErrorCode.INTERNAL_ERROR, e.getMessage());
}
}
public void complete(DBGPReason reason, ContextException ctxt)
{
try
{
if (reason == DBGPReason.EXCEPTION && ctxt != null)
{
dyingThread(ctxt);
}
else
{
statusResponse(DBGPStatus.STOPPED, reason);
}
}
catch (IOException e)
{
errorResponse(DBGPErrorCode.INTERNAL_ERROR, e.getMessage());
}
finally
{
try
{
if (socket != null)
{
socket.close();
}
}
catch (IOException e)
{
// ?
}
}
}
private boolean process(String line)
{
boolean carryOn = true;
try
{
command = DBGPCommandType.UNKNOWN;
transaction = "?";
String[] parts = line.split("\\s+");
DBGPCommand c = parse(parts);
switch (c.type)
{
case STATUS:
processStatus(c);
break;
case FEATURE_GET:
processFeatureGet(c);
break;
case FEATURE_SET:
processFeatureSet(c);
break;
case RUN:
carryOn = processRun(c);
break;
case EVAL:
carryOn = processEval(c);
break;
case EXPR:
carryOn = processExpr(c);
break;
case STEP_INTO:
processStepInto(c);
carryOn = false;
break;
case STEP_OVER:
processStepOver(c);
carryOn = false;
break;
case STEP_OUT:
processStepOut(c);
carryOn = false;
break;
case STOP:
processStop(c);
break;
case BREAKPOINT_GET:
breakpointGet(c);
break;
case BREAKPOINT_SET:
breakpointSet(c);
break;
case BREAKPOINT_UPDATE:
breakpointUpdate(c);
break;
case BREAKPOINT_REMOVE:
breakpointRemove(c);
break;
case BREAKPOINT_LIST:
breakpointList(c);
break;
case STACK_DEPTH:
stackDepth(c);
break;
case STACK_GET:
stackGet(c);
break;
case CONTEXT_NAMES:
contextNames(c);
break;
case CONTEXT_GET:
contextGet(c);
break;
case PROPERTY_GET:
propertyGet(c);
break;
case SOURCE:
processSource(c);
break;
case STDOUT:
processStdout(c);
break;
case STDERR:
processStderr(c);
break;
case DETACH:
carryOn = false;
break;
case XCMD_OVERTURE_CMD:
processOvertureCmd(c);
break;
case PROPERTY_SET:
default:
errorResponse(DBGPErrorCode.NOT_AVAILABLE, c.type.value);
}
}
catch (DBGPException e)
{
errorResponse(e.code, e.reason);
}
catch (Throwable e)
{
errorResponse(DBGPErrorCode.INTERNAL_ERROR, e.toString());
}
return carryOn;
}
private DBGPCommand parse(String[] parts) throws Exception
{
// "<type> [<options>] [-- <base64 args>]"
List<DBGPOption> options = new Vector<DBGPOption>();
String args = null;
boolean doneOpts = false;
boolean gotXID = false;
try
{
command = DBGPCommandType.lookup(parts[0]);
for (int i=1; i<parts.length; i++)
{
if (doneOpts)
{
if (args != null)
{
throw new Exception("Expecting one base64 arg after '--'");
}
else
{
args = parts[i];
}
}
else
{
if (parts[i].equals("--"))
{
doneOpts = true;
}
else
{
DBGPOptionType opt = DBGPOptionType.lookup(parts[i++]);
if (opt == DBGPOptionType.TRANSACTION_ID)
{
gotXID = true;
transaction = parts[i];
}
options.add(new DBGPOption(opt, parts[i]));
}
}
}
if (!gotXID)
{
throw new Exception("No transaction_id");
}
}
catch (DBGPException e)
{
throw e;
}
catch (ArrayIndexOutOfBoundsException e)
{
throw new DBGPException(
DBGPErrorCode.INVALID_OPTIONS, "Option arg missing");
}
catch (Exception e)
{
if (doneOpts)
{
throw new DBGPException(DBGPErrorCode.PARSE, e.getMessage());
}
else
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, e.getMessage());
}
}
return new DBGPCommand(command, options, args);
}
private void checkArgs(DBGPCommand c, int n, boolean data) throws DBGPException
{
if (data && c.data == null)
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, c.toString());
}
if (c.options.size() != n)
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, c.toString());
}
}
private void processStatus(DBGPCommand c) throws DBGPException, IOException
{
checkArgs(c, 1, false);
statusResponse();
}
private void processFeatureGet(DBGPCommand c) throws DBGPException, IOException
{
checkArgs(c, 2, false);
DBGPOption option = c.getOption(DBGPOptionType.N);
if (option == null)
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, c.toString());
}
String feature = features.getProperty(option.value);
StringBuilder hdr = new StringBuilder();
StringBuilder body = new StringBuilder();
if (feature == null)
{
// Unknown feature - unsupported in header; nothing in body
hdr.append("feature_name=\"");
hdr.append(option.value);
hdr.append("\" supported=\"0\"");
}
else
{
// Known feature - supported in header; body reflects actual support
hdr.append("feature_name=\"");
hdr.append(option.value);
hdr.append("\" supported=\"1\"");
body.append(feature);
}
response(hdr, body);
}
private void processFeatureSet(DBGPCommand c) throws DBGPException, IOException
{
checkArgs(c, 3, false);
DBGPOption option = c.getOption(DBGPOptionType.N);
if (option == null)
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, c.toString());
}
String feature = features.getProperty(option.value);
if (feature == null)
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, c.toString());
}
DBGPOption newval = c.getOption(DBGPOptionType.V);
if (newval == null)
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, c.toString());
}
features.setProperty(option.value, newval.value);
StringBuilder hdr = new StringBuilder();
hdr.append("feature_name=\"");
hdr.append(option.value);
hdr.append("\" success=\"1\"");
response(hdr, null);
}
private void dyingThread(ContextException ex)
{
try
{
breakContext = ex.ctxt;
breakpoint = new Breakpoint(ex.ctxt.location);
status = DBGPStatus.STOPPING;
statusReason = DBGPReason.EXCEPTION;
errorResponse(DBGPErrorCode.EVALUATION_ERROR, ex.getMessage());
run(false);
breakContext = null;
breakpoint = null;
statusResponse(DBGPStatus.STOPPED, DBGPReason.EXCEPTION);
}
catch (Exception e)
{
errorResponse(DBGPErrorCode.INTERNAL_ERROR, e.getMessage());
}
}
private boolean processRun(DBGPCommand c) throws DBGPException
{
checkArgs(c, 1, false);
if (status == DBGPStatus.BREAK || status == DBGPStatus.STOPPING)
{
breakContext.threadState.set(0, null, null);
return false; // run means continue
}
if (expression == null || status != DBGPStatus.STARTING)
{
throw new DBGPException(DBGPErrorCode.NOT_AVAILABLE, c.toString());
}
if (c.data != null)
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, c.toString());
}
try
{
interpreter.init(this);
theAnswer = interpreter.execute(expression, this);
stdout(theAnswer.toString());
statusResponse(DBGPStatus.STOPPED, DBGPReason.OK);
}
catch (ContextException e)
{
dyingThread(e);
}
catch (Exception e)
{
status = DBGPStatus.STOPPED;
statusReason = DBGPReason.ERROR;
errorResponse(DBGPErrorCode.EVALUATION_ERROR, e.getMessage());
}
return true;
}
private boolean processEval(DBGPCommand c) throws DBGPException
{
checkArgs(c, 1, true);
if (status != DBGPStatus.BREAK && status != DBGPStatus.STOPPING)
{
throw new DBGPException(DBGPErrorCode.NOT_AVAILABLE, c.toString());
}
breaksSuspended = true;
try
{
String exp = c.data; // Already base64 decoded by the parser
interpreter.setDefaultName(breakpoint.location.module);
theAnswer = interpreter.evaluate(exp, breakContext);
StringBuilder property = propertyResponse(
exp, exp, interpreter.getDefaultName(), theAnswer.toString());
StringBuilder hdr = new StringBuilder("success=\"1\"");
response(hdr, property);
}
catch (ContextException e)
{
dyingThread(e);
}
catch (Exception e)
{
errorResponse(DBGPErrorCode.EVALUATION_ERROR, e.getMessage());
}
finally
{
breaksSuspended = false;
}
return true;
}
private boolean processExpr(DBGPCommand c) throws DBGPException
{
checkArgs(c, 1, true);
if (status == DBGPStatus.BREAK || status == DBGPStatus.STOPPING)
{
throw new DBGPException(DBGPErrorCode.NOT_AVAILABLE, c.toString());
}
try
{
String exp = c.data; // Already base64 decoded by the parser
theAnswer = interpreter.execute(exp, this);
StringBuilder property = propertyResponse(
exp, exp, interpreter.getDefaultName(), theAnswer.toString());
StringBuilder hdr = new StringBuilder("success=\"1\"");
status = DBGPStatus.STOPPED;
statusReason = DBGPReason.OK;
response(hdr, property);
}
catch (ContextException e)
{
dyingThread(e);
}
catch (Exception e)
{
status = DBGPStatus.STOPPED;
statusReason = DBGPReason.ERROR;
errorResponse(DBGPErrorCode.EVALUATION_ERROR, e.getMessage());
}
return true;
}
private void processStepInto(DBGPCommand c) throws DBGPException
{
checkArgs(c, 1, false);
if (status != DBGPStatus.BREAK || breakpoint == null)
{
throw new DBGPException(DBGPErrorCode.NOT_AVAILABLE, c.toString());
}
breakContext.threadState.set(breakpoint.location.startLine, null, null);
}
private void processStepOver(DBGPCommand c) throws DBGPException
{
checkArgs(c, 1, false);
if (status != DBGPStatus.BREAK || breakpoint == null)
{
throw new DBGPException(DBGPErrorCode.NOT_AVAILABLE, c.toString());
}
breakContext.threadState.set(breakpoint.location.startLine, breakContext.getRoot(), null);
}
private void processStepOut(DBGPCommand c) throws DBGPException
{
checkArgs(c, 1, false);
if (status != DBGPStatus.BREAK)
{
throw new DBGPException(DBGPErrorCode.NOT_AVAILABLE, c.toString());
}
breakContext.threadState.set(breakpoint.location.startLine, null, breakContext.getRoot().outer);
}
private void processStop(DBGPCommand c) throws DBGPException, IOException
{
checkArgs(c, 1, false);
if (status != DBGPStatus.BREAK)
{
throw new DBGPException(DBGPErrorCode.NOT_AVAILABLE, c.toString());
}
statusResponse(DBGPStatus.STOPPING, DBGPReason.OK);
DebuggerException e = new DebuggerException("terminated");
Interpreter.stop(null, e, breakContext);
}
private void breakpointGet(DBGPCommand c) throws DBGPException, IOException
{
checkArgs(c, 2, false);
DBGPOption option = c.getOption(DBGPOptionType.D);
if (option == null)
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, c.toString());
}
Breakpoint bp = interpreter.breakpoints.get(Integer.parseInt(option.value));
if (bp == null)
{
throw new DBGPException(DBGPErrorCode.INVALID_BREAKPOINT, c.toString());
}
response(null, breakpointResponse(bp));
}
private void breakpointSet(DBGPCommand c)
throws DBGPException, IOException, URISyntaxException
{
DBGPOption option = c.getOption(DBGPOptionType.T);
if (option == null)
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, c.toString());
}
DBGPBreakpointType type = DBGPBreakpointType.lookup(option.value);
if (type == null)
{
throw new DBGPException(DBGPErrorCode.BREAKPOINT_TYPE_UNSUPPORTED, option.value);
}
option = c.getOption(DBGPOptionType.F);
File filename = null;
if (option != null)
{
filename = new File(new URI(option.value));
}
else
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, c.toString());
}
option = c.getOption(DBGPOptionType.S);
if (option != null)
{
if (!option.value.equalsIgnoreCase("enabled"))
{
throw new DBGPException(DBGPErrorCode.INVALID_BREAKPOINT, option.value);
}
}
option = c.getOption(DBGPOptionType.N);
int lineno = 0;
if (option != null)
{
lineno = Integer.parseInt(option.value);
}
String condition = null;
if (c.data != null)
{
condition = c.data;
}
else
{
DBGPOption cond = c.getOption(DBGPOptionType.O);
DBGPOption hits = c.getOption(DBGPOptionType.H);
if (cond != null || hits != null)
{
String cs = (cond == null) ? ">=" : cond.value;
String hs = (hits == null) ? "0" : hits.value;
if (hs.equals("0"))
{
condition = "= 0"; // impossible (disabled)
}
else if (cs.equals("=="))
{
condition = "= " + hs;
}
else if (cs.equals(">="))
{
condition = ">= " + hs;
}
else if (cs.equals("%"))
{
condition = "mod " + hs;
}
else
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, c.toString());
}
}
}
Breakpoint bp = null;
Statement stmt = interpreter.findStatement(filename, lineno);
if (stmt == null)
{
Expression exp = interpreter.findExpression(filename, lineno);
if (exp == null)
{
throw new DBGPException(DBGPErrorCode.CANT_SET_BREAKPOINT, filename + ":" + lineno);
}
else
{
try
{
interpreter.clearBreakpoint(exp.breakpoint.number);
bp = interpreter.setBreakpoint(exp, condition);
}
catch (ParserException e)
{
throw new DBGPException(DBGPErrorCode.CANT_SET_BREAKPOINT,
filename + ":" + lineno + ", " + e.getMessage());
}
catch (LexException e)
{
throw new DBGPException(DBGPErrorCode.CANT_SET_BREAKPOINT,
filename + ":" + lineno + ", " + e.getMessage());
}
}
}
else
{
try
{
interpreter.clearBreakpoint(stmt.breakpoint.number);
bp = interpreter.setBreakpoint(stmt, condition);
}
catch (ParserException e)
{
throw new DBGPException(DBGPErrorCode.CANT_SET_BREAKPOINT,
filename + ":" + lineno + ", " + e.getMessage());
}
catch (LexException e)
{
throw new DBGPException(DBGPErrorCode.CANT_SET_BREAKPOINT,
filename + ":" + lineno + ", " + e.getMessage());
}
}
StringBuilder hdr = new StringBuilder(
"state=\"enabled\" id=\"" + bp.number + "\"");
response(hdr, null);
}
private void breakpointUpdate(DBGPCommand c) throws DBGPException
{
checkArgs(c, 2, false);
DBGPOption option = c.getOption(DBGPOptionType.D);
if (option == null)
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, c.toString());
}
Breakpoint bp = interpreter.breakpoints.get(Integer.parseInt(option.value));
if (bp == null)
{
throw new DBGPException(DBGPErrorCode.INVALID_BREAKPOINT, c.toString());
}
throw new DBGPException(DBGPErrorCode.UNIMPLEMENTED, c.toString());
}
private void breakpointRemove(DBGPCommand c) throws DBGPException, IOException
{
checkArgs(c, 2, false);
DBGPOption option = c.getOption(DBGPOptionType.D);
if (option == null)
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, c.toString());
}
Breakpoint old = interpreter.clearBreakpoint(Integer.parseInt(option.value));
if (old == null)
{
throw new DBGPException(DBGPErrorCode.INVALID_BREAKPOINT, c.toString());
}
response(null, null);
}
private void breakpointList(DBGPCommand c) throws IOException, DBGPException
{
checkArgs(c, 1, false);
StringBuilder bps = new StringBuilder();
for (Integer key: interpreter.breakpoints.keySet())
{
Breakpoint bp = interpreter.breakpoints.get(key);
bps.append(breakpointResponse(bp));
}
response(null, bps);
}
private void stackDepth(DBGPCommand c) throws DBGPException, IOException
{
checkArgs(c, 1, false);
if (status != DBGPStatus.BREAK && status != DBGPStatus.STOPPING)
{
throw new DBGPException(DBGPErrorCode.NOT_AVAILABLE, c.toString());
}
StringBuilder sb = new StringBuilder();
sb.append(breakContext.getDepth());
response(null, sb);
}
private void stackGet(DBGPCommand c) throws DBGPException, IOException
{
checkArgs(c, 1, false);
if (status != DBGPStatus.BREAK && status != DBGPStatus.STOPPING)
{
throw new DBGPException(DBGPErrorCode.NOT_AVAILABLE, c.toString());
}
DBGPOption option = c.getOption(DBGPOptionType.D);
int depth = -1;
if (option != null)
{
depth = Integer.parseInt(option.value); // 0 to n-1
}
// We omit the last frame, as this is unhelpful (globals),
int actualDepth = breakContext.getDepth() - 1;
if (depth >= actualDepth)
{
throw new DBGPException(DBGPErrorCode.INVALID_STACK_DEPTH, c.toString());
}
if (depth == 0)
{
response(null, stackResponse(breakpoint.location, 0));
}
else if (depth > 0)
{
RootContext ctxt = breakContext.getFrame(depth).getRoot();
response(null, stackResponse(ctxt.location, depth));
}
else
{
StringBuilder sb = new StringBuilder();
Context ctxt = breakContext;
int d = 0;
sb.append(stackResponse(breakpoint.location, d++));
while (d < actualDepth)
{
ctxt = breakContext.getFrame(d);
sb.append(stackResponse(ctxt.location, d++));
}
response(null, sb);
}
}
private void contextNames(DBGPCommand c) throws DBGPException, IOException
{
if (c.data != null)
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, c.toString());
}
DBGPOption option = c.getOption(DBGPOptionType.D);
if (c.options.size() > ((option == null) ? 1 : 2))
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, c.toString());
}
StringBuilder names = new StringBuilder();
names.append("<context name=\"Local\" id=\"0\"/>");
names.append("<context name=\"Class\" id=\"1\"/>");
names.append("<context name=\"Global\" id=\"2\"/>");
response(null, names);
}
private NameValuePairMap getContextValues(DBGPContextType context, int depth)
{
NameValuePairMap vars = new NameValuePairMap();
Context frame = breakContext.getFrame(depth);
switch (context)
{
case LOCAL:
vars.putAll(frame.getFreeVariables());
break;
case CLASS:
RootContext root = frame.getRoot();
if (root instanceof ObjectContext)
{
ObjectContext octxt = (ObjectContext)root;
vars.putAll(octxt.self.members);
}
else if (root instanceof ClassContext)
{
ClassContext cctxt = (ClassContext)root;
vars.putAll(cctxt);
}
else
{
StateContext sctxt = (StateContext)root;
vars.putAll(sctxt.stateCtxt);
}
break;
case GLOBAL:
vars.putAll(interpreter.initialContext);
break;
}
return vars;
}
private void contextGet(DBGPCommand c) throws DBGPException, IOException
{
if (c.data != null || c.options.size() > 3)
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, c.toString());
}
if (status != DBGPStatus.BREAK && status != DBGPStatus.STOPPING)
{
throw new DBGPException(DBGPErrorCode.NOT_AVAILABLE, c.toString());
}
DBGPOption option = c.getOption(DBGPOptionType.C);
int type = 0;
if (option != null)
{
type = Integer.parseInt(option.value);
}
DBGPContextType context = DBGPContextType.lookup(type);
option = c.getOption(DBGPOptionType.D);
int depth = 0;
if (option != null)
{
depth = Integer.parseInt(option.value);
}
int actualDepth = breakContext.getDepth() - 1;
if (depth >= actualDepth)
{
throw new DBGPException(DBGPErrorCode.INVALID_STACK_DEPTH, c.toString());
}
NameValuePairMap vars = getContextValues(context, depth);
response(null, propertyResponse(vars));
}
private void propertyGet(DBGPCommand c) throws DBGPException, IOException
{
if (c.data != null || c.options.size() > 4)
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, c.toString());
}
if (status != DBGPStatus.BREAK && status != DBGPStatus.STOPPING)
{
throw new DBGPException(DBGPErrorCode.NOT_AVAILABLE, c.toString());
}
DBGPOption option = c.getOption(DBGPOptionType.C);
int type = 0;
if (option != null)
{
type = Integer.parseInt(option.value);
}
DBGPContextType context = DBGPContextType.lookup(type);
option = c.getOption(DBGPOptionType.D);
int depth = -1;
if (option != null)
{
depth = Integer.parseInt(option.value);
}
option = c.getOption(DBGPOptionType.N);
if (option == null)
{
throw new DBGPException(DBGPErrorCode.CANT_GET_PROPERTY, c.toString());
}
LexTokenReader ltr = new LexTokenReader(option.value, Dialect.VDM_PP);
LexToken token = null;
try
{
token = ltr.nextToken();
}
catch (LexException e)
{
throw new DBGPException(DBGPErrorCode.CANT_GET_PROPERTY, option.value);
}
if (token.isNot(Token.NAME))
{
throw new DBGPException(DBGPErrorCode.CANT_GET_PROPERTY, token.toString());
}
NameValuePairMap vars = getContextValues(context, depth);
LexNameToken longname = (LexNameToken)token;
Value value = vars.get(longname);
if (value == null)
{
throw new DBGPException(
DBGPErrorCode.CANT_GET_PROPERTY, longname.toString());
}
response(null, propertyResponse(longname, value));
}
private void processSource(DBGPCommand c) throws DBGPException, IOException
{
if (c.data != null || c.options.size() > 4)
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, c.toString());
}
DBGPOption option = c.getOption(DBGPOptionType.B);
int begin = 1;
if (option != null)
{
begin = Integer.parseInt(option.value);
}
option = c.getOption(DBGPOptionType.E);
int end = 0;
if (option != null)
{
end = Integer.parseInt(option.value);
}
option = c.getOption(DBGPOptionType.F);
if (option == null)
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, c.toString());
}
File file = null;
try
{
file = new File(new URI(option.value));
}
catch (URISyntaxException e)
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, c.toString());
}
SourceFile s = interpreter.getSourceFile(file);
StringBuilder sb = new StringBuilder();
if (end == 0)
{
end = s.getCount();
}
sb.append("<![CDATA[");
for (int n = begin; n <= end; n++)
{
sb.append(quote(s.getLine(n)));
sb.append("\n");
}
sb.append("]]>");
response(null, sb);
}
private void processStdout(DBGPCommand c) throws DBGPException, IOException
{
checkArgs(c, 2, false);
DBGPOption option = c.getOption(DBGPOptionType.C);
if (option == null)
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, c.toString());
}
DBGPRedirect redirect = DBGPRedirect.lookup(option.value);
Console.directStdout(this, redirect);
response(new StringBuilder("success=\"1\""), null);
}
private void processStderr(DBGPCommand c) throws DBGPException, IOException
{
checkArgs(c, 2, false);
DBGPOption option = c.getOption(DBGPOptionType.C);
if (option == null)
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, c.toString());
}
DBGPRedirect redirect = DBGPRedirect.lookup(option.value);
Console.directStderr(this, redirect);
response(new StringBuilder("success=\"1\""), null);
}
public synchronized void stdout(String line) throws IOException
{
StringBuilder sb = new StringBuilder("<stream type=\"stdout\"><![CDATA[");
sb.append(Base64.encode(line.getBytes("UTF-8")));
sb.append("]]></stream>\n");
write(sb);
}
public synchronized void stderr(String line) throws IOException
{
StringBuilder sb = new StringBuilder("<stream type=\"stderr\"><![CDATA[");
sb.append(Base64.encode(line.getBytes("UTF-8")));
sb.append("]]></stream>\n");
write(sb);
}
private void processOvertureCmd(DBGPCommand c)
throws DBGPException, IOException, URISyntaxException
{
checkArgs(c, 2, false);
DBGPOption option = c.getOption(DBGPOptionType.C);
if (option == null)
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, c.toString());
}
if (option.value.equals("init"))
{
processInit(c);
}
else if (option.value.equals("create"))
{
processCreate(c);
}
else if (option.value.equals("currentline"))
{
processCurrentLine(c);
}
else if (option.value.equals("source"))
{
processCurrentSource(c);
}
else if (option.value.equals("coverage"))
{
processCoverage(c);
}
else if (option.value.equals("pog"))
{
processPOG(c);
}
else if (option.value.equals("stack"))
{
processStack(c);
}
else if (option.value.equals("trace"))
{
processTrace(c);
}
else if (option.value.equals("list"))
{
processList();
}
else if (option.value.equals("files"))
{
processFiles();
}
else if (option.value.equals("classes"))
{
processClasses(c);
}
else if (option.value.equals("modules"))
{
processModules(c);
}
else if (option.value.equals("default"))
{
processDefault(c);
}
else if (option.value.equals("log"))
{
processLog(c);
}
else
{
throw new DBGPException(DBGPErrorCode.INVALID_OPTIONS, c.toString());
}
}
private void processInit(DBGPCommand c) throws IOException, DBGPException
{
if (status == DBGPStatus.BREAK || status == DBGPStatus.STOPPING)
{
throw new DBGPException(DBGPErrorCode.NOT_AVAILABLE, c.toString());
}
LexLocation.clearLocations();
interpreter.init(this);
cdataResponse("Global context and test coverage initialized");
}
private void processLog(DBGPCommand c) throws IOException
{
StringBuilder out = new StringBuilder();
try
{
if (c.data == null)
{
if (RTLogger.getLogSize() > 0)
{
out.append("Flushing " + RTLogger.getLogSize() + " RT events\n");
}
RTLogger.setLogfile(null);
out.append("RT events now logged to the console");
}
else if (c.data.equals("off"))
{
RTLogger.enable(false);
out.append("RT event logging disabled");
}
else
{
PrintWriter p = new PrintWriter(new FileOutputStream(c.data, true));
RTLogger.setLogfile(p);
out.append("RT events now logged to " + c.data);
}
}
catch (FileNotFoundException e)
{
out.append("Cannot create RT event log: " + e.getMessage());
}
cdataResponse(out.toString());
}
private void processCreate(DBGPCommand c) throws DBGPException
{
if (!(interpreter instanceof ClassInterpreter))
{
throw new DBGPException(DBGPErrorCode.INTERNAL_ERROR, c.toString());
}
try
{
int i = c.data.indexOf(' ');
String var = c.data.substring(0, i);
String exp = c.data.substring(i + 1);
((ClassInterpreter)interpreter).create(var, exp);
}
catch (Exception e)
{
throw new DBGPException(DBGPErrorCode.INTERNAL_ERROR, e.getMessage());
}
}
private void processStack(DBGPCommand c) throws IOException, DBGPException
{
if (status != DBGPStatus.BREAK && status != DBGPStatus.STOPPING)
{
throw new DBGPException(DBGPErrorCode.NOT_AVAILABLE, c.toString());
}
OutputStream out = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(out);
pw.println("Stopped at " + breakpoint);
breakContext.printStackTrace(pw, true);
pw.close();
cdataResponse(out.toString());
}
private void processTrace(DBGPCommand c) throws DBGPException
{
File file = null;
int line = 0;
String trace = null;
try
{
int i = c.data.indexOf(' ');
int j = c.data.indexOf(' ', i+1);
file = new File(new URI(c.data.substring(0, i)));
line = Integer.parseInt(c.data.substring(i+1, j));
trace = c.data.substring(j+1);
if (trace.length() == 0) trace = null;
OutputStream out = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(out);
Statement stmt = interpreter.findStatement(file, line);
if (stmt == null)
{
Expression exp = interpreter.findExpression(file, line);
if (exp == null)
{
throw new DBGPException(DBGPErrorCode.CANT_SET_BREAKPOINT,
"No breakable expressions or statements at " + file + ":" + line);
}
else
{
interpreter.clearBreakpoint(exp.breakpoint.number);
Breakpoint bp = interpreter.setTracepoint(exp, trace);
pw.println("Created " + bp);
pw.println(interpreter.getSourceLine(bp.location));
}
}
else
{
interpreter.clearBreakpoint(stmt.breakpoint.number);
Breakpoint bp = interpreter.setTracepoint(stmt, trace);
pw.println("Created " + bp);
pw.println(interpreter.getSourceLine(bp.location));
}
pw.close();
cdataResponse(out.toString());
}
catch (Exception e)
{
throw new DBGPException(DBGPErrorCode.CANT_SET_BREAKPOINT, e.getMessage());
}
}
private void processList() throws IOException
{
Map<Integer, Breakpoint> map = interpreter.getBreakpoints();
OutputStream out = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(out);
for (Integer key: map.keySet())
{
Breakpoint bp = map.get(key);
pw.println(bp.toString());
pw.println(interpreter.getSourceLine(bp.location));
}
pw.close();
cdataResponse(out.toString());
}
private void processFiles() throws IOException
{
Set<File> filenames = interpreter.getSourceFiles();
OutputStream out = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(out);
for (File file: filenames)
{
pw.println(file.getPath());
}
pw.close();
cdataResponse(out.toString());
}
private void processClasses(DBGPCommand c) throws IOException, DBGPException
{
if (!(interpreter instanceof ClassInterpreter))
{
throw new DBGPException(DBGPErrorCode.INTERNAL_ERROR, c.toString());
}
ClassInterpreter cinterpreter = (ClassInterpreter)interpreter;
String def = cinterpreter.getDefaultName();
ClassList classes = cinterpreter.getClasses();
OutputStream out = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(out);
for (ClassDefinition cls: classes)
{
if (cls.name.name.equals(def))
{
pw.println(cls.name.name + " (default)");
}
else
{
pw.println(cls.name.name);
}
}
pw.close();
cdataResponse(out.toString());
}
private void processModules(DBGPCommand c) throws DBGPException, IOException
{
if (!(interpreter instanceof ModuleInterpreter))
{
throw new DBGPException(DBGPErrorCode.INTERNAL_ERROR, c.toString());
}
ModuleInterpreter minterpreter = (ModuleInterpreter)interpreter;
String def = minterpreter.getDefaultName();
List<Module> modules = minterpreter.getModules();
OutputStream out = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(out);
for (Module m: modules)
{
if (m.name.name.equals(def))
{
pw.println(m.name.name + " (default)");
}
else
{
pw.println(m.name.name);
}
}
pw.close();
cdataResponse(out.toString());
}
private void processDefault(DBGPCommand c) throws DBGPException
{
try
{
interpreter.setDefaultName(c.data);
cdataResponse("Default set to " + interpreter.getDefaultName());
}
catch (Exception e)
{
throw new DBGPException(DBGPErrorCode.INTERNAL_ERROR, c.toString());
}
}
private void processCoverage(DBGPCommand c)
throws DBGPException, IOException, URISyntaxException
{
if (status == DBGPStatus.BREAK)
{
throw new DBGPException(DBGPErrorCode.NOT_AVAILABLE, c.toString());
}
File file = new File(new URI(c.data));
SourceFile source = interpreter.getSourceFile(file);
if (source == null)
{
cdataResponse(file + ": file not found");
}
else
{
OutputStream out = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(out);
source.printCoverage(pw);
pw.close();
cdataResponse(out.toString());
}
}
private void processCurrentLine(DBGPCommand c) throws DBGPException, IOException
{
if (status != DBGPStatus.BREAK && status != DBGPStatus.STOPPING)
{
throw new DBGPException(DBGPErrorCode.NOT_AVAILABLE, c.toString());
}
OutputStream out = new ByteArrayOutputStream();
PrintWriter pw = new PrintWriter(out);
pw.println("Stopped at " + breakpoint);
pw.println(interpreter.getSourceLine(
breakpoint.location.file, breakpoint.location.startLine, ": "));
pw.close();
cdataResponse(out.toString());
}
private void processCurrentSource(DBGPCommand c) throws DBGPException, IOException
{
if (status != DBGPStatus.BREAK && status != DBGPStatus.STOPPING)
{
throw new DBGPException(DBGPErrorCode.NOT_AVAILABLE, c.toString());
}
File file = breakpoint.location.file;
int current = breakpoint.location.startLine;
int start = current - SOURCE_LINES;
if (start < 1) start = 1;
int end = start + SOURCE_LINES*2 + 1;
StringBuilder sb = new StringBuilder();
for (int src = start; src < end; src++)
{
sb.append(interpreter.getSourceLine(
file, src, (src == current) ? ":>>" : ": "));
sb.append("\n");
}
cdataResponse(sb.toString());
}
private void processPOG(DBGPCommand c) throws IOException
{
ProofObligationList all = interpreter.getProofObligations();
ProofObligationList list = null;
if (c.data.equals("*"))
{
list = all;
}
else
{
list = new ProofObligationList();
String name = c.data + "(";
for (ProofObligation po: all)
{
if (po.name.indexOf(name) >= 0)
{
list.add(po);
}
}
}
if (list.isEmpty())
{
cdataResponse("No proof obligations generated");
}
else
{
StringBuilder sb = new StringBuilder();
sb.append("Generated ");
sb.append(plural(list.size(), "proof obligation", "s"));
sb.append(":\n");
sb.append(list);
cdataResponse(sb.toString());
}
}
private String plural(int n, String s, String pl)
{
return n + " " + (n != 1 ? s + pl : s);
}
}
| false | true | public static void main(String[] args)
{
Settings.usingDBGP = true;
String host = null;
int port = 0;
String ideKey = null;
Settings.dialect = null;
String expression = null;
List<File> files = new Vector<File>();
List<String> largs = Arrays.asList(args);
VDMJ controller = null;
boolean warnings = true;
for (Iterator<String> i = largs.iterator(); i.hasNext();)
{
String arg = i.next();
if (arg.equals("-vdmsl"))
{
controller = new VDMSL();
}
else if (arg.equals("-vdmpp"))
{
controller = new VDMPP();
}
else if (arg.equals("-vdmrt"))
{
controller = new VDMRT();
}
else if (arg.equals("-overture"))
{
controller = new VDMOV();
}
else if (arg.equals("-h"))
{
if (i.hasNext())
{
host = i.next();
}
else
{
usage("-h option requires a hostname");
}
}
else if (arg.equals("-p"))
{
try
{
port = Integer.parseInt(i.next());
}
catch (Exception e)
{
usage("-p option requires a port");
}
}
else if (arg.equals("-k"))
{
if (i.hasNext())
{
ideKey = i.next();
}
else
{
usage("-k option requires a key");
}
}
else if (arg.equals("-e"))
{
if (i.hasNext())
{
expression = i.next();
}
else
{
usage("-e option requires an expression");
}
}
else if (arg.equals("-w"))
{
warnings = false;
}
else if (arg.startsWith("-"))
{
usage("Unknown option " + arg);
}
else
{
try
{
files.add(new File(new URI(arg)));
}
catch (URISyntaxException e)
{
usage(e.getMessage() + ": " + arg);
}
catch (IllegalArgumentException e)
{
usage(e.getMessage() + ": " + arg);
}
}
}
if (host == null || port == 0 || controller == null ||
ideKey == null || expression == null || Settings.dialect == null ||
files.isEmpty())
{
usage("Missing mandatory arguments");
}
controller.setWarnings(warnings);
if (controller.parse(files) == ExitStatus.EXIT_OK)
{
if (controller.typeCheck() == ExitStatus.EXIT_OK)
{
try
{
Interpreter i = controller.getInterpreter();
new DBGPReader(host, port, ideKey, i, expression).run(true);
System.exit(0);
}
catch (ContextException e)
{
System.out.println("Initialization: " + e);
e.ctxt.printStackTrace(Console.out, true);
System.exit(3);
}
catch (Exception e)
{
System.out.println("Initialization: " + e);
System.exit(3);
}
}
else
{
System.exit(2);
}
}
else
{
System.exit(1);
}
}
| public static void main(String[] args)
{
Settings.usingDBGP = true;
String host = null;
int port = -1;
String ideKey = null;
Settings.dialect = null;
String expression = null;
List<File> files = new Vector<File>();
List<String> largs = Arrays.asList(args);
VDMJ controller = null;
boolean warnings = true;
for (Iterator<String> i = largs.iterator(); i.hasNext();)
{
String arg = i.next();
if (arg.equals("-vdmsl"))
{
controller = new VDMSL();
}
else if (arg.equals("-vdmpp"))
{
controller = new VDMPP();
}
else if (arg.equals("-vdmrt"))
{
controller = new VDMRT();
}
else if (arg.equals("-overture"))
{
controller = new VDMOV();
}
else if (arg.equals("-h"))
{
if (i.hasNext())
{
host = i.next();
}
else
{
usage("-h option requires a hostname");
}
}
else if (arg.equals("-p"))
{
try
{
port = Integer.parseInt(i.next());
}
catch (Exception e)
{
usage("-p option requires a port");
}
}
else if (arg.equals("-k"))
{
if (i.hasNext())
{
ideKey = i.next();
}
else
{
usage("-k option requires a key");
}
}
else if (arg.equals("-e"))
{
if (i.hasNext())
{
expression = i.next();
}
else
{
usage("-e option requires an expression");
}
}
else if (arg.equals("-w"))
{
warnings = false;
}
else if (arg.startsWith("-"))
{
usage("Unknown option " + arg);
}
else
{
try
{
files.add(new File(new URI(arg)));
}
catch (URISyntaxException e)
{
usage(e.getMessage() + ": " + arg);
}
catch (IllegalArgumentException e)
{
usage(e.getMessage() + ": " + arg);
}
}
}
if (host == null || port == -1 || controller == null ||
ideKey == null || expression == null || Settings.dialect == null ||
files.isEmpty())
{
usage("Missing mandatory arguments");
}
controller.setWarnings(warnings);
if (controller.parse(files) == ExitStatus.EXIT_OK)
{
if (controller.typeCheck() == ExitStatus.EXIT_OK)
{
try
{
Interpreter i = controller.getInterpreter();
new DBGPReader(host, port, ideKey, i, expression).run(true);
System.exit(0);
}
catch (ContextException e)
{
System.out.println("Initialization: " + e);
e.ctxt.printStackTrace(Console.out, true);
System.exit(3);
}
catch (Exception e)
{
System.out.println("Initialization: " + e);
System.exit(3);
}
}
else
{
System.exit(2);
}
}
else
{
System.exit(1);
}
}
|
diff --git a/library/src/se/emilsjolander/stickylistheaders/StickyListHeadersListView.java b/library/src/se/emilsjolander/stickylistheaders/StickyListHeadersListView.java
index 6891e87..2330653 100644
--- a/library/src/se/emilsjolander/stickylistheaders/StickyListHeadersListView.java
+++ b/library/src/se/emilsjolander/stickylistheaders/StickyListHeadersListView.java
@@ -1,763 +1,763 @@
package se.emilsjolander.stickylistheaders;
import se.emilsjolander.stickylistheaders.WrapperViewList.LifeCycleListener;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.res.TypedArray;
import android.database.DataSetObserver;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.FrameLayout;
import android.widget.ListView;
import android.widget.SectionIndexer;
/**
* Even though this is a FrameLayout subclass we it is called a
* ListView. This is because of 2 reasons. 1. It acts like as ListView
* 2. It used to be a ListView subclass and i did not was to change to
* name causing compatibility errors.
*
* @author Emil Sjölander
*/
public class StickyListHeadersListView extends FrameLayout {
public interface OnHeaderClickListener {
public void onHeaderClick(StickyListHeadersListView l, View header, int itemPosition, long headerId,
boolean currentlySticky);
}
/* --- Children --- */
private WrapperViewList mList;
private View mHeader;
/* --- Header state --- */
private Long mHeaderId;
// used to not have to call getHeaderId() all the time
private Integer mHeaderPosition;
private Integer mHeaderOffset;
/* --- Delegates --- */
private OnScrollListener mOnScrollListenerDelegate;
/* --- Settings --- */
private boolean mAreHeadersSticky = true;
private boolean mClippingToPadding = true;
private boolean mIsDrawingListUnderStickyHeader = true;
private int mPaddingLeft = 0;
private int mPaddingTop = 0;
private int mPaddingRight = 0;
private int mPaddingBottom = 0;
/* --- Other --- */
private AdapterWrapper mAdapter;
private OnHeaderClickListener mOnHeaderClickListener;
private Drawable mDivider;
private int mDividerHeight;
private AdapterWrapperDataSetObserver mDataSetObserver;
public StickyListHeadersListView(Context context) {
this(context, null);
}
public StickyListHeadersListView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public StickyListHeadersListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Initialize the list
mList = new WrapperViewList(context);
mDivider = mList.getDivider();
mDividerHeight = mList.getDividerHeight();
// null out divider, dividers are handled by adapter so they look good
// with headers
mList.setDivider(null);
mList.setDividerHeight(0);
mList.setLifeCycleListener(new WrapperViewListLifeCycleListener());
mList.setOnScrollListener(new WrapperListScrollListener());
addView(mList);
if (attrs != null) {
TypedArray a = context.getTheme()
.obtainStyledAttributes(attrs, R.styleable.StickyListHeadersListView, 0, 0);
try {
// Android attributes
if (a.hasValue(R.styleable.StickyListHeadersListView_android_padding)) {
int padding = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_padding, 0);
mPaddingLeft = padding;
mPaddingTop = padding;
mPaddingRight = padding;
mPaddingBottom = padding;
} else {
mPaddingLeft = a
.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingLeft, 0);
mPaddingTop = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingTop, 0);
mPaddingRight = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingRight,
0);
mPaddingBottom = a.getDimensionPixelSize(
R.styleable.StickyListHeadersListView_android_paddingBottom, 0);
}
setPadding(mPaddingLeft, mPaddingTop, mPaddingRight, mPaddingBottom);
// Set clip to padding on the list and reset value to default on
// wrapper
mClippingToPadding = a.getBoolean(R.styleable.StickyListHeadersListView_android_clipToPadding, true);
super.setClipToPadding(true);
mList.setClipToPadding(mClippingToPadding);
// ListView attributes
mList.setFadingEdgeLength(a.getDimensionPixelSize(
R.styleable.StickyListHeadersListView_android_fadingEdgeLength,
mList.getVerticalFadingEdgeLength()));
final int fadingEdge = a.getInt(R.styleable.StickyListHeadersListView_android_requiresFadingEdge, 0);
if (fadingEdge == 0x00001000) {
mList.setVerticalFadingEdgeEnabled(false);
mList.setHorizontalFadingEdgeEnabled(true);
} else if (fadingEdge == 0x00002000) {
mList.setVerticalFadingEdgeEnabled(true);
mList.setHorizontalFadingEdgeEnabled(false);
} else {
mList.setVerticalFadingEdgeEnabled(false);
mList.setHorizontalFadingEdgeEnabled(false);
}
mList.setCacheColorHint(a.getColor(R.styleable.StickyListHeadersListView_android_cacheColorHint,
mList.getCacheColorHint()));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mList.setChoiceMode(a.getInt(R.styleable.StickyListHeadersListView_android_choiceMode,
mList.getChoiceMode()));
}
mList.setDrawSelectorOnTop(a.getBoolean(
R.styleable.StickyListHeadersListView_android_drawSelectorOnTop, false));
mList.setFastScrollEnabled(a.getBoolean(
R.styleable.StickyListHeadersListView_android_fastScrollEnabled, mList.isFastScrollEnabled()));
mList.setScrollBarStyle(a.getInt(R.styleable.StickyListHeadersListView_android_scrollbarStyle, 0));
final Drawable selector = a.getDrawable(R.styleable.StickyListHeadersListView_android_listSelector);
if (selector != null) {
mList.setSelector(selector);
}
mList.setScrollingCacheEnabled(a.getBoolean(
R.styleable.StickyListHeadersListView_android_scrollingCache, mList.isScrollingCacheEnabled()));
final Drawable divider = a.getDrawable(R.styleable.StickyListHeadersListView_android_divider);
if (divider != null) {
mDivider = divider;
}
- mDividerHeight = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_dividerHeight, 0);
+ mDividerHeight = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_dividerHeight, mDividerHeight);
// StickyListHeaders attributes
mAreHeadersSticky = a.getBoolean(R.styleable.StickyListHeadersListView_hasStickyHeaders, true);
mIsDrawingListUnderStickyHeader = a.getBoolean(
R.styleable.StickyListHeadersListView_isDrawingListUnderStickyHeader, true);
} finally {
a.recycle();
}
}
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
mList.layout(mPaddingLeft, 0, mList.getMeasuredWidth() + mPaddingLeft, getHeight());
if (mHeader != null) {
MarginLayoutParams lp = (MarginLayoutParams) mHeader.getLayoutParams();
int headerTop = lp.topMargin + (mClippingToPadding ? mPaddingTop : 0);
// The left parameter must for some reason be set to 0.
// I think it should be set to mPaddingLeft but apparently not
mHeader.layout(0, headerTop, mHeader.getMeasuredWidth(), headerTop + mHeader.getMeasuredHeight());
}
}
@Override
protected void dispatchDraw(Canvas canvas) {
// Only draw the list here.
// The header should be drawn right after the lists children are drawn.
// This is done so that the header is above the list items
// but below the list decorators (scroll bars etc).
drawChild(canvas, mList, 0);
}
// Reset values tied the header. also remove header form layout
// This is called in response to the data set or the adapter changing
private void clearHeader() {
if (mHeader != null) {
removeView(mHeader);
mHeader = null;
mHeaderId = null;
mHeaderPosition = null;
mHeaderOffset = null;
// reset the top clipping length
mList.setTopClippingLength(0);
updateHeaderVisibilities();
}
}
private void updateOrClearHeader(int firstVisiblePosition) {
final int adapterCount = mAdapter == null ? 0 : mAdapter.getCount();
if (adapterCount == 0 || !mAreHeadersSticky) {
return;
}
final int headerViewCount = mList.getHeaderViewsCount();
final int realFirstVisibleItem = firstVisiblePosition - headerViewCount;
// It is not a mistake to call getFirstVisiblePosition() here.
// Most of the time getFixedFirstVisibleItem() should be called
// but that does not work great together with getChildAt()
final boolean isFirstViewBelowTop = mList.getFirstVisiblePosition() == 0 && mList.getChildAt(0).getTop() > 0;
final boolean isFirstVisibleItemOutsideAdapterRange = realFirstVisibleItem > adapterCount - 1
|| realFirstVisibleItem < 0;
final boolean doesListHaveChildren = mList.getChildCount() != 0;
if (!doesListHaveChildren || isFirstVisibleItemOutsideAdapterRange || isFirstViewBelowTop) {
clearHeader();
return;
}
updateHeader(realFirstVisibleItem);
}
private void updateHeader(int firstVisiblePosition) {
// check if there is a new header should be sticky
if (mHeaderPosition == null || mHeaderPosition != firstVisiblePosition) {
mHeaderPosition = firstVisiblePosition;
final long headerId = mAdapter.getHeaderId(firstVisiblePosition);
if (mHeaderId == null || mHeaderId != headerId) {
mHeaderId = headerId;
final View header = mAdapter.getHeaderView(mHeaderPosition, mHeader, this);
if (mHeader != header) {
if (header == null) {
throw new NullPointerException("header may not be null");
}
swapHeader(header);
}
// measure the header
final int width = getWidth();
final int parentWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
final int parentHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
measureChild(mHeader, parentWidthMeasureSpec, parentHeightMeasureSpec);
// Reset mHeaderOffset to null ensuring
// that it will be set on the header and
// not skipped for performance reasons.
mHeaderOffset = null;
}
}
int headerOffset = 0;
// Calculate new header offset
// Skip looking at the first view. it never matters because it always
// results in a headerOffset = 0
int headerBottom = mHeader.getMeasuredHeight() + (mClippingToPadding ? mPaddingTop : 0);
for (int i = 0; i < mList.getChildCount(); i++) {
final View child = mList.getChildAt(i);
final boolean doesChildHaveHeader = child instanceof WrapperView && ((WrapperView) child).hasHeader();
final boolean isChildFooter = mList.containsFooterView(child);
if (child.getTop() >= (mClippingToPadding ? mPaddingTop : 0) && (doesChildHaveHeader || isChildFooter)) {
headerOffset = Math.min(child.getTop() - headerBottom, 0);
break;
}
}
setHeaderOffet(headerOffset);
if (!mIsDrawingListUnderStickyHeader) {
mList.setTopClippingLength(mHeader.getMeasuredHeight() + mHeaderOffset);
}
updateHeaderVisibilities();
}
private void swapHeader(View newHeader) {
if (mHeader != null) {
removeView(mHeader);
}
mHeader = newHeader;
addView(mHeader);
mHeader.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (mOnHeaderClickListener != null) {
mOnHeaderClickListener.onHeaderClick(StickyListHeadersListView.this, mHeader, mHeaderPosition,
mHeaderId, true);
}
}
});
}
// hides the headers in the list under the sticky header.
// Makes sure the other ones are showing
private void updateHeaderVisibilities() {
int top;
if (mHeader != null) {
top = mHeader.getMeasuredHeight() + (mHeaderOffset != null ? mHeaderOffset : 0);
} else {
top = mClippingToPadding ? mPaddingTop : 0;
}
int childCount = mList.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = mList.getChildAt(i);
if (child instanceof WrapperView) {
WrapperView wrapperViewChild = (WrapperView) child;
if (wrapperViewChild.hasHeader()) {
View childHeader = wrapperViewChild.mHeader;
if (wrapperViewChild.getTop() < top) {
if (childHeader.getVisibility() != View.INVISIBLE) {
childHeader.setVisibility(View.INVISIBLE);
}
} else {
if (childHeader.getVisibility() != View.VISIBLE) {
childHeader.setVisibility(View.VISIBLE);
}
}
}
}
}
}
// Wrapper around setting the header offset in different ways depending on
// the API version
@SuppressLint("NewApi")
private void setHeaderOffet(int offset) {
if (mHeaderOffset == null || mHeaderOffset != offset) {
mHeaderOffset = offset;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mHeader.setTranslationY(mHeaderOffset);
} else {
MarginLayoutParams params = (MarginLayoutParams) mHeader.getLayoutParams();
params.topMargin = mHeaderOffset;
mHeader.setLayoutParams(params);
}
}
}
private class AdapterWrapperDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
clearHeader();
}
@Override
public void onInvalidated() {
clearHeader();
}
}
private class WrapperListScrollListener implements OnScrollListener {
@Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
if (mOnScrollListenerDelegate != null) {
mOnScrollListenerDelegate.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
}
updateOrClearHeader(mList.getFixedFirstVisibleItem());
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
if (mOnScrollListenerDelegate != null) {
mOnScrollListenerDelegate.onScrollStateChanged(view, scrollState);
}
}
}
private class WrapperViewListLifeCycleListener implements LifeCycleListener {
@Override
public void onDispatchDrawOccurred(Canvas canvas) {
// onScroll is not called often at all before froyo
// therefor we need to update the header here as well.
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.FROYO) {
updateOrClearHeader(mList.getFixedFirstVisibleItem());
}
if (mHeader != null) {
if (mClippingToPadding) {
canvas.save();
canvas.clipRect(0, mPaddingTop, getRight(), getBottom());
drawChild(canvas, mHeader, 0);
canvas.restore();
} else {
drawChild(canvas, mHeader, 0);
}
}
}
}
private class AdapterWrapperHeaderClickHandler implements AdapterWrapper.OnHeaderClickListener {
@Override
public void onHeaderClick(View header, int itemPosition, long headerId) {
mOnHeaderClickListener.onHeaderClick(StickyListHeadersListView.this, header, itemPosition, headerId, false);
}
}
private boolean isStartOfSection(int position) {
return position == 0 || mAdapter.getHeaderId(position) == mAdapter.getHeaderId(position - 1);
}
private int getHeaderOverlap(int position) {
boolean isStartOfSection = isStartOfSection(position);
if (!isStartOfSection) {
View header = mAdapter.getView(position, null, mList);
final int width = getWidth();
final int parentWidthMeasureSpec = MeasureSpec.makeMeasureSpec(width, MeasureSpec.EXACTLY);
final int parentHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
measureChild(header, parentWidthMeasureSpec, parentHeightMeasureSpec);
return header.getMeasuredHeight();
}
return 0;
}
/* ---------- StickyListHeaders specific API ---------- */
public void setAreHeadersSticky(boolean areHeadersSticky) {
mAreHeadersSticky = areHeadersSticky;
if (!areHeadersSticky) {
clearHeader();
} else {
updateOrClearHeader(mList.getFixedFirstVisibleItem());
}
// invalidating the list will trigger dispatchDraw()
mList.invalidate();
}
public boolean areHeadersSticky() {
return mAreHeadersSticky;
}
/**
* Use areHeadersSticky() method instead
*/
@Deprecated
public boolean getAreHeadersSticky() {
return areHeadersSticky();
}
public void setDrawingListUnderStickyHeader(boolean drawingListUnderStickyHeader) {
mIsDrawingListUnderStickyHeader = drawingListUnderStickyHeader;
// reset the top clipping length
mList.setTopClippingLength(0);
}
public boolean isDrawingListUnderStickyHeader() {
return mIsDrawingListUnderStickyHeader;
}
public void setOnHeaderClickListener(OnHeaderClickListener onHeaderClickListener) {
mOnHeaderClickListener = onHeaderClickListener;
if (mAdapter != null) {
if (mOnHeaderClickListener != null) {
mAdapter.setOnHeaderClickListener(new AdapterWrapperHeaderClickHandler());
} else {
mAdapter.setOnHeaderClickListener(null);
}
}
}
public View getListChildAt(int index) {
return mList.getChildAt(index);
}
public int getListChildCount() {
return mList.getChildCount();
}
/**
* Use the method with extreme caution!!
* Changing any values on the underlying ListView might break everything.
*
* @return the ListView backing this view.
*/
public ListView getWrappedList() {
return mList;
}
/* ---------- ListView delegate methods ---------- */
public void setAdapter(StickyListHeadersAdapter adapter) {
if (adapter == null) {
mList.setAdapter(null);
clearHeader();
return;
}
if (mAdapter != null) {
mAdapter.unregisterDataSetObserver(mDataSetObserver);
}
if (adapter instanceof SectionIndexer) {
mAdapter = new SectionIndexerAdapterWrapper(getContext(), adapter);
} else {
mAdapter = new AdapterWrapper(getContext(), adapter);
}
mDataSetObserver = new AdapterWrapperDataSetObserver();
mAdapter.registerDataSetObserver(mDataSetObserver);
if (mOnHeaderClickListener != null) {
mAdapter.setOnHeaderClickListener(new AdapterWrapperHeaderClickHandler());
} else {
mAdapter.setOnHeaderClickListener(null);
}
mAdapter.setDivider(mDivider, mDividerHeight);
mList.setAdapter(mAdapter);
clearHeader();
}
public StickyListHeadersAdapter getAdapter() {
return mAdapter == null ? null : mAdapter.mDelegate;
}
public void setDivider(Drawable divider) {
mDivider = divider;
if (mAdapter != null) {
mAdapter.setDivider(mDivider, mDividerHeight);
}
}
public void setDividerHeight(int dividerHeight) {
mDividerHeight = dividerHeight;
if (mAdapter != null) {
mAdapter.setDivider(mDivider, mDividerHeight);
}
}
public Drawable getDivider() {
return mDivider;
}
public int getDividerHeight() {
return mDividerHeight;
}
public void setOnScrollListener(OnScrollListener onScrollListener) {
mOnScrollListenerDelegate = onScrollListener;
}
public void setOnItemClickListener(OnItemClickListener listener) {
mList.setOnItemClickListener(listener);
}
public void addHeaderView(View v) {
mList.addHeaderView(v);
}
public void removeHeaderView(View v) {
mList.removeHeaderView(v);
}
public int getHeaderViewsCount() {
return mList.getHeaderViewsCount();
}
public void addFooterView(View v) {
mList.addFooterView(v);
}
public void removeFooterView(View v) {
mList.removeFooterView(v);
}
public int getFooterViewsCount() {
return mList.getFooterViewsCount();
}
public void setEmptyView(View v) {
mList.setEmptyView(v);
}
public View getEmptyView() {
return mList.getEmptyView();
}
@TargetApi(Build.VERSION_CODES.FROYO)
public void smoothScrollBy(int distance, int duration) {
requireSdkVersion(Build.VERSION_CODES.FROYO);
mList.smoothScrollBy(distance, duration);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void smoothScrollByOffset(int offset) {
requireSdkVersion(Build.VERSION_CODES.HONEYCOMB);
mList.smoothScrollByOffset(offset);
}
@TargetApi(Build.VERSION_CODES.FROYO)
public void smoothScrollToPosition(int position) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {
mList.smoothScrollToPosition(position);
} else {
int offset = mAdapter == null ? 0 : getHeaderOverlap(position);
mList.smoothScrollToPositionFromTop(position, offset);
}
}
@TargetApi(Build.VERSION_CODES.FROYO)
public void smoothScrollToPosition(int position, int boundPosition) {
requireSdkVersion(Build.VERSION_CODES.FROYO);
mList.smoothScrollToPosition(position, boundPosition);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void smoothScrollToPositionFromTop(int position, int offset) {
requireSdkVersion(Build.VERSION_CODES.HONEYCOMB);
offset += mAdapter == null ? 0 : getHeaderOverlap(position);
mList.smoothScrollToPositionFromTop(position, offset);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public void smoothScrollToPositionFromTop(int position, int offset, int duration) {
requireSdkVersion(Build.VERSION_CODES.HONEYCOMB);
offset += mAdapter == null ? 0 : getHeaderOverlap(position);
mList.smoothScrollToPositionFromTop(position, offset, duration);
}
public void setSelection(int position) {
mList.setSelection(position);
}
public void setSelectionAfterHeaderView() {
mList.setSelectionAfterHeaderView();
}
public void setSelectionFromTop(int position, int y) {
mList.setSelectionFromTop(position, y);
}
public void setSelector(Drawable sel) {
mList.setSelector(sel);
}
public void setSelector(int resID) {
mList.setSelector(resID);
}
public int getFirstVisiblePosition() {
return mList.getFirstVisiblePosition();
}
public int getLastVisiblePosition() {
return mList.getLastVisiblePosition();
}
public void setChoiceMode(int choiceMode) {
mList.setChoiceMode(choiceMode);
}
public void setItemChecked(int position, boolean value) {
mList.setItemChecked(position, value);
}
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public int getCheckedItemCount() {
requireSdkVersion(Build.VERSION_CODES.HONEYCOMB);
return mList.getCheckedItemCount();
}
@TargetApi(Build.VERSION_CODES.FROYO)
public long[] getCheckedItemIds() {
requireSdkVersion(Build.VERSION_CODES.FROYO);
return mList.getCheckedItemIds();
}
public int getCheckedItemPosition() {
return mList.getCheckedItemPosition();
}
public SparseBooleanArray getCheckedItemPositions() {
return mList.getCheckedItemPositions();
}
public int getCount() {
return mList.getCount();
}
public Object getItemAtPosition(int position) {
return mList.getItemAtPosition(position);
}
public long getItemIdAtPosition(int position) {
return mList.getItemIdAtPosition(position);
}
@Override
public void setClipToPadding(boolean clipToPadding) {
if (mList != null) {
mList.setClipToPadding(clipToPadding);
}
mClippingToPadding = clipToPadding;
}
@Override
public void setPadding(int left, int top, int right, int bottom) {
mPaddingLeft = left;
mPaddingTop = top;
mPaddingRight = right;
mPaddingBottom = bottom;
// Set left/right paddings on the wrapper and top/bottom on the
// list to support the clip to padding flag
super.setPadding(left, 0, right, 0);
if (mList != null) {
mList.setPadding(0, top, 0, bottom);
}
}
@Override
public int getPaddingLeft() {
return mPaddingLeft;
}
@Override
public int getPaddingTop() {
return mPaddingTop;
}
@Override
public int getPaddingRight() {
return mPaddingRight;
}
@Override
public int getPaddingBottom() {
return mPaddingBottom;
}
public void setFastScrollEnabled(boolean fastScrollEnabled) {
mList.setFastScrollEnabled(fastScrollEnabled);
}
private void requireSdkVersion(int versionCode) {
if (Build.VERSION.SDK_INT < versionCode) {
throw new ApiLevelTooLowException(versionCode);
}
}
public int getPositionForView(View view){
return mList.getPositionForView(view);
}
}
| true | true | public StickyListHeadersListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Initialize the list
mList = new WrapperViewList(context);
mDivider = mList.getDivider();
mDividerHeight = mList.getDividerHeight();
// null out divider, dividers are handled by adapter so they look good
// with headers
mList.setDivider(null);
mList.setDividerHeight(0);
mList.setLifeCycleListener(new WrapperViewListLifeCycleListener());
mList.setOnScrollListener(new WrapperListScrollListener());
addView(mList);
if (attrs != null) {
TypedArray a = context.getTheme()
.obtainStyledAttributes(attrs, R.styleable.StickyListHeadersListView, 0, 0);
try {
// Android attributes
if (a.hasValue(R.styleable.StickyListHeadersListView_android_padding)) {
int padding = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_padding, 0);
mPaddingLeft = padding;
mPaddingTop = padding;
mPaddingRight = padding;
mPaddingBottom = padding;
} else {
mPaddingLeft = a
.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingLeft, 0);
mPaddingTop = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingTop, 0);
mPaddingRight = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingRight,
0);
mPaddingBottom = a.getDimensionPixelSize(
R.styleable.StickyListHeadersListView_android_paddingBottom, 0);
}
setPadding(mPaddingLeft, mPaddingTop, mPaddingRight, mPaddingBottom);
// Set clip to padding on the list and reset value to default on
// wrapper
mClippingToPadding = a.getBoolean(R.styleable.StickyListHeadersListView_android_clipToPadding, true);
super.setClipToPadding(true);
mList.setClipToPadding(mClippingToPadding);
// ListView attributes
mList.setFadingEdgeLength(a.getDimensionPixelSize(
R.styleable.StickyListHeadersListView_android_fadingEdgeLength,
mList.getVerticalFadingEdgeLength()));
final int fadingEdge = a.getInt(R.styleable.StickyListHeadersListView_android_requiresFadingEdge, 0);
if (fadingEdge == 0x00001000) {
mList.setVerticalFadingEdgeEnabled(false);
mList.setHorizontalFadingEdgeEnabled(true);
} else if (fadingEdge == 0x00002000) {
mList.setVerticalFadingEdgeEnabled(true);
mList.setHorizontalFadingEdgeEnabled(false);
} else {
mList.setVerticalFadingEdgeEnabled(false);
mList.setHorizontalFadingEdgeEnabled(false);
}
mList.setCacheColorHint(a.getColor(R.styleable.StickyListHeadersListView_android_cacheColorHint,
mList.getCacheColorHint()));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mList.setChoiceMode(a.getInt(R.styleable.StickyListHeadersListView_android_choiceMode,
mList.getChoiceMode()));
}
mList.setDrawSelectorOnTop(a.getBoolean(
R.styleable.StickyListHeadersListView_android_drawSelectorOnTop, false));
mList.setFastScrollEnabled(a.getBoolean(
R.styleable.StickyListHeadersListView_android_fastScrollEnabled, mList.isFastScrollEnabled()));
mList.setScrollBarStyle(a.getInt(R.styleable.StickyListHeadersListView_android_scrollbarStyle, 0));
final Drawable selector = a.getDrawable(R.styleable.StickyListHeadersListView_android_listSelector);
if (selector != null) {
mList.setSelector(selector);
}
mList.setScrollingCacheEnabled(a.getBoolean(
R.styleable.StickyListHeadersListView_android_scrollingCache, mList.isScrollingCacheEnabled()));
final Drawable divider = a.getDrawable(R.styleable.StickyListHeadersListView_android_divider);
if (divider != null) {
mDivider = divider;
}
mDividerHeight = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_dividerHeight, 0);
// StickyListHeaders attributes
mAreHeadersSticky = a.getBoolean(R.styleable.StickyListHeadersListView_hasStickyHeaders, true);
mIsDrawingListUnderStickyHeader = a.getBoolean(
R.styleable.StickyListHeadersListView_isDrawingListUnderStickyHeader, true);
} finally {
a.recycle();
}
}
}
| public StickyListHeadersListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// Initialize the list
mList = new WrapperViewList(context);
mDivider = mList.getDivider();
mDividerHeight = mList.getDividerHeight();
// null out divider, dividers are handled by adapter so they look good
// with headers
mList.setDivider(null);
mList.setDividerHeight(0);
mList.setLifeCycleListener(new WrapperViewListLifeCycleListener());
mList.setOnScrollListener(new WrapperListScrollListener());
addView(mList);
if (attrs != null) {
TypedArray a = context.getTheme()
.obtainStyledAttributes(attrs, R.styleable.StickyListHeadersListView, 0, 0);
try {
// Android attributes
if (a.hasValue(R.styleable.StickyListHeadersListView_android_padding)) {
int padding = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_padding, 0);
mPaddingLeft = padding;
mPaddingTop = padding;
mPaddingRight = padding;
mPaddingBottom = padding;
} else {
mPaddingLeft = a
.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingLeft, 0);
mPaddingTop = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingTop, 0);
mPaddingRight = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_paddingRight,
0);
mPaddingBottom = a.getDimensionPixelSize(
R.styleable.StickyListHeadersListView_android_paddingBottom, 0);
}
setPadding(mPaddingLeft, mPaddingTop, mPaddingRight, mPaddingBottom);
// Set clip to padding on the list and reset value to default on
// wrapper
mClippingToPadding = a.getBoolean(R.styleable.StickyListHeadersListView_android_clipToPadding, true);
super.setClipToPadding(true);
mList.setClipToPadding(mClippingToPadding);
// ListView attributes
mList.setFadingEdgeLength(a.getDimensionPixelSize(
R.styleable.StickyListHeadersListView_android_fadingEdgeLength,
mList.getVerticalFadingEdgeLength()));
final int fadingEdge = a.getInt(R.styleable.StickyListHeadersListView_android_requiresFadingEdge, 0);
if (fadingEdge == 0x00001000) {
mList.setVerticalFadingEdgeEnabled(false);
mList.setHorizontalFadingEdgeEnabled(true);
} else if (fadingEdge == 0x00002000) {
mList.setVerticalFadingEdgeEnabled(true);
mList.setHorizontalFadingEdgeEnabled(false);
} else {
mList.setVerticalFadingEdgeEnabled(false);
mList.setHorizontalFadingEdgeEnabled(false);
}
mList.setCacheColorHint(a.getColor(R.styleable.StickyListHeadersListView_android_cacheColorHint,
mList.getCacheColorHint()));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mList.setChoiceMode(a.getInt(R.styleable.StickyListHeadersListView_android_choiceMode,
mList.getChoiceMode()));
}
mList.setDrawSelectorOnTop(a.getBoolean(
R.styleable.StickyListHeadersListView_android_drawSelectorOnTop, false));
mList.setFastScrollEnabled(a.getBoolean(
R.styleable.StickyListHeadersListView_android_fastScrollEnabled, mList.isFastScrollEnabled()));
mList.setScrollBarStyle(a.getInt(R.styleable.StickyListHeadersListView_android_scrollbarStyle, 0));
final Drawable selector = a.getDrawable(R.styleable.StickyListHeadersListView_android_listSelector);
if (selector != null) {
mList.setSelector(selector);
}
mList.setScrollingCacheEnabled(a.getBoolean(
R.styleable.StickyListHeadersListView_android_scrollingCache, mList.isScrollingCacheEnabled()));
final Drawable divider = a.getDrawable(R.styleable.StickyListHeadersListView_android_divider);
if (divider != null) {
mDivider = divider;
}
mDividerHeight = a.getDimensionPixelSize(R.styleable.StickyListHeadersListView_android_dividerHeight, mDividerHeight);
// StickyListHeaders attributes
mAreHeadersSticky = a.getBoolean(R.styleable.StickyListHeadersListView_hasStickyHeaders, true);
mIsDrawingListUnderStickyHeader = a.getBoolean(
R.styleable.StickyListHeadersListView_isDrawingListUnderStickyHeader, true);
} finally {
a.recycle();
}
}
}
|
diff --git a/src/org/mariotaku/twidere/util/TwidereLinkify.java b/src/org/mariotaku/twidere/util/TwidereLinkify.java
index 78050d71..931b5265 100644
--- a/src/org/mariotaku/twidere/util/TwidereLinkify.java
+++ b/src/org/mariotaku/twidere/util/TwidereLinkify.java
@@ -1,515 +1,518 @@
/*
* Twidere - Twitter client for Android
*
* Copyright (C) 2012 Mariotaku Lee <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.mariotaku.twidere.util;
import static org.mariotaku.twidere.util.Utils.getAllAvailableImage;
import static org.mariotaku.twidere.util.Utils.matcherEnd;
import static org.mariotaku.twidere.util.Utils.matcherGroup;
import static org.mariotaku.twidere.util.Utils.matcherStart;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.mariotaku.twidere.model.ImageSpec;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.method.LinkMovementMethod;
import android.text.method.MovementMethod;
import android.text.style.URLSpan;
import android.view.View;
import android.widget.TextView;
import com.twitter.Regex;
/**
* Linkify take a piece of text and a regular expression and turns all of the
* regex matches in the text into clickable links. This is particularly useful
* for matching things like email addresses, web urls, etc. and making them
* actionable.
*
* Alone with the pattern that is to be matched, a url scheme prefix is also
* required. Any pattern match that does not begin with the supplied scheme will
* have the scheme prepended to the matched text when the clickable url is
* created. For instance, if you are matching web urls you would supply the
* scheme <code>http://</code>. If the pattern matches example.com, which does
* not have a url scheme prefix, the supplied scheme will be prepended to create
* <code>http://example.com</code> when the clickable url link is created.
*/
public class TwidereLinkify {
public static final int LINK_TYPE_MENTION_LIST = 1;
public static final int LINK_TYPE_HASHTAG = 2;
public static final int LINK_TYPE_LINK_WITH_IMAGE_EXTENSION = 3;
public static final int LINK_TYPE_LINK = 4;
public static final int LINK_TYPE_ALL_AVAILABLE_IMAGE = 5;
public static final int LINK_TYPE_LIST = 6;
public static final int LINK_TYPE_CASHTAG = 7;
public static final int[] ALL_LINK_TYPES = new int[] { LINK_TYPE_MENTION_LIST, LINK_TYPE_HASHTAG,
LINK_TYPE_LINK_WITH_IMAGE_EXTENSION, LINK_TYPE_LINK, LINK_TYPE_ALL_AVAILABLE_IMAGE, LINK_TYPE_CASHTAG
};
public static final String SINA_WEIBO_IMAGES_AVAILABLE_SIZES = "(woriginal|large|thumbnail|bmiddle|mw600)";
public static final String AVAILABLE_URL_SCHEME_PREFIX = "(https?:\\/\\/)?";
public static final String AVAILABLE_IMAGE_SHUFFIX = "(png|jpeg|jpg|gif|bmp)";
private static final String STRING_PATTERN_TWITTER_IMAGES_DOMAIN = "(p|pbs)\\.twimg\\.com";
private static final String STRING_PATTERN_SINA_WEIBO_IMAGES_DOMAIN = "[\\w\\d]+\\.sinaimg\\.cn|[\\w\\d]+\\.sina\\.cn";
private static final String STRING_PATTERN_LOCKERZ_AND_PLIXI_DOMAIN = "plixi\\.com\\/p|lockerz\\.com\\/s";
private static final String STRING_PATTERN_INSTAGRAM_DOMAIN = "instagr\\.am|instagram\\.com";
private static final String STRING_PATTERN_TWITPIC_DOMAIN = "twitpic\\.com";
private static final String STRING_PATTERN_IMGLY_DOMAIN = "img\\.ly";
private static final String STRING_PATTERN_YFROG_DOMAIN = "yfrog\\.com";
private static final String STRING_PATTERN_TWITGOO_DOMAIN = "twitgoo\\.com";
private static final String STRING_PATTERN_MOBYPICTURE_DOMAIN = "moby\\.to";
private static final String STRING_PATTERN_IMGUR_DOMAIN = "imgur\\.com|i\\.imgur\\.com";
private static final String STRING_PATTERN_PHOTOZOU_DOMAIN = "photozou\\.jp";
private static final String STRING_PATTERN_IMAGES_NO_SCHEME = "[^:\\/\\/].+?\\." + AVAILABLE_IMAGE_SHUFFIX;
private static final String STRING_PATTERN_TWITTER_IMAGES_NO_SCHEME = STRING_PATTERN_TWITTER_IMAGES_DOMAIN
+ "(\\/media)?\\/([\\d\\w\\-_]+)\\.(png|jpeg|jpg|gif|bmp)";
private static final String STRING_PATTERN_SINA_WEIBO_IMAGES_NO_SCHEME = "("
+ STRING_PATTERN_SINA_WEIBO_IMAGES_DOMAIN + ")" + "\\/" + SINA_WEIBO_IMAGES_AVAILABLE_SIZES
+ "\\/(([\\d\\w]+)\\.(png|jpeg|jpg|gif|bmp))";
private static final String STRING_PATTERN_LOCKERZ_AND_PLIXI_NO_SCHEME = "("
+ STRING_PATTERN_LOCKERZ_AND_PLIXI_DOMAIN + ")" + "\\/(\\w+)\\/?";
private static final String STRING_PATTERN_INSTAGRAM_NO_SCHEME = "(" + STRING_PATTERN_INSTAGRAM_DOMAIN + ")"
+ "\\/p\\/([_\\-\\d\\w]+)\\/?";
private static final String STRING_PATTERN_TWITPIC_NO_SCHEME = STRING_PATTERN_TWITPIC_DOMAIN + "\\/([\\d\\w]+)\\/?";
private static final String STRING_PATTERN_IMGLY_NO_SCHEME = STRING_PATTERN_IMGLY_DOMAIN + "\\/([\\w\\d]+)\\/?";
private static final String STRING_PATTERN_YFROG_NO_SCHEME = STRING_PATTERN_YFROG_DOMAIN + "\\/([\\w\\d]+)\\/?";
private static final String STRING_PATTERN_TWITGOO_NO_SCHEME = STRING_PATTERN_TWITGOO_DOMAIN + "\\/([\\d\\w]+)\\/?";
private static final String STRING_PATTERN_MOBYPICTURE_NO_SCHEME = STRING_PATTERN_MOBYPICTURE_DOMAIN
+ "\\/([\\d\\w]+)\\/?";
private static final String STRING_PATTERN_IMGUR_NO_SCHEME = "(" + STRING_PATTERN_IMGUR_DOMAIN + ")"
+ "\\/([\\d\\w]+)((?-i)s|(?-i)l)?(\\." + AVAILABLE_IMAGE_SHUFFIX + ")?";
private static final String STRING_PATTERN_PHOTOZOU_NO_SCHEME = STRING_PATTERN_PHOTOZOU_DOMAIN
+ "\\/photo\\/show\\/([\\d]+)\\/([\\d]+)\\/?";
private static final String STRING_PATTERN_IMAGES = AVAILABLE_URL_SCHEME_PREFIX + STRING_PATTERN_IMAGES_NO_SCHEME;
private static final String STRING_PATTERN_TWITTER_IMAGES = AVAILABLE_URL_SCHEME_PREFIX
+ STRING_PATTERN_TWITTER_IMAGES_NO_SCHEME;
private static final String STRING_PATTERN_SINA_WEIBO_IMAGES = AVAILABLE_URL_SCHEME_PREFIX
+ STRING_PATTERN_SINA_WEIBO_IMAGES_NO_SCHEME;
private static final String STRING_PATTERN_LOCKERZ_AND_PLIXI = AVAILABLE_URL_SCHEME_PREFIX
+ STRING_PATTERN_LOCKERZ_AND_PLIXI_NO_SCHEME;
private static final String STRING_PATTERN_INSTAGRAM = AVAILABLE_URL_SCHEME_PREFIX
+ STRING_PATTERN_INSTAGRAM_NO_SCHEME;
private static final String STRING_PATTERN_TWITPIC = AVAILABLE_URL_SCHEME_PREFIX + STRING_PATTERN_TWITPIC_NO_SCHEME;
private static final String STRING_PATTERN_IMGLY = AVAILABLE_URL_SCHEME_PREFIX + STRING_PATTERN_IMGLY_NO_SCHEME;
private static final String STRING_PATTERN_YFROG = AVAILABLE_URL_SCHEME_PREFIX + STRING_PATTERN_YFROG_NO_SCHEME;
private static final String STRING_PATTERN_TWITGOO = AVAILABLE_URL_SCHEME_PREFIX + STRING_PATTERN_TWITGOO_NO_SCHEME;
private static final String STRING_PATTERN_MOBYPICTURE = AVAILABLE_URL_SCHEME_PREFIX
+ STRING_PATTERN_MOBYPICTURE_NO_SCHEME;
private static final String STRING_PATTERN_IMGUR = AVAILABLE_URL_SCHEME_PREFIX + STRING_PATTERN_IMGUR_NO_SCHEME;
private static final String STRING_PATTERN_PHOTOZOU = AVAILABLE_URL_SCHEME_PREFIX
+ STRING_PATTERN_PHOTOZOU_NO_SCHEME;
public static final Pattern PATTERN_ALL_AVAILABLE_IMAGES = Pattern.compile(AVAILABLE_URL_SCHEME_PREFIX + "("
+ STRING_PATTERN_IMAGES_NO_SCHEME + "|" + STRING_PATTERN_TWITTER_IMAGES_NO_SCHEME + "|"
+ STRING_PATTERN_SINA_WEIBO_IMAGES_NO_SCHEME + "|" + STRING_PATTERN_LOCKERZ_AND_PLIXI_NO_SCHEME + "|"
+ STRING_PATTERN_INSTAGRAM_NO_SCHEME + "|" + STRING_PATTERN_TWITPIC_NO_SCHEME + "|"
+ STRING_PATTERN_IMGLY_NO_SCHEME + "|" + STRING_PATTERN_YFROG_NO_SCHEME + "|"
+ STRING_PATTERN_TWITGOO_NO_SCHEME + "|" + STRING_PATTERN_MOBYPICTURE_NO_SCHEME + "|"
+ STRING_PATTERN_IMGUR_NO_SCHEME + "|" + STRING_PATTERN_PHOTOZOU_NO_SCHEME + ")", Pattern.CASE_INSENSITIVE);
public static final Pattern PATTERN_INLINE_PREVIEW_AVAILABLE_IMAGES_MATCH_ONLY = Pattern.compile(
AVAILABLE_URL_SCHEME_PREFIX + "(" + STRING_PATTERN_IMAGES_NO_SCHEME + "|"
+ STRING_PATTERN_TWITTER_IMAGES_DOMAIN + "|" + STRING_PATTERN_SINA_WEIBO_IMAGES_DOMAIN + "|"
+ STRING_PATTERN_LOCKERZ_AND_PLIXI_DOMAIN + "|" + STRING_PATTERN_INSTAGRAM_DOMAIN + "|"
+ STRING_PATTERN_TWITPIC_DOMAIN + "|" + STRING_PATTERN_IMGLY_DOMAIN + "|"
+ STRING_PATTERN_YFROG_DOMAIN + "|" + STRING_PATTERN_TWITGOO_DOMAIN + "|"
+ STRING_PATTERN_MOBYPICTURE_DOMAIN + "|" + STRING_PATTERN_IMGUR_DOMAIN + "|"
+ STRING_PATTERN_PHOTOZOU_DOMAIN + ")", Pattern.CASE_INSENSITIVE);
public static final Pattern PATTERN_PREVIEW_AVAILABLE_IMAGES_IN_HTML = Pattern.compile("<a href=\"("
+ AVAILABLE_URL_SCHEME_PREFIX + "(" + STRING_PATTERN_IMAGES_NO_SCHEME + "|"
+ STRING_PATTERN_TWITTER_IMAGES_NO_SCHEME + "|" + STRING_PATTERN_SINA_WEIBO_IMAGES_NO_SCHEME + "|"
+ STRING_PATTERN_LOCKERZ_AND_PLIXI_NO_SCHEME + "|" + STRING_PATTERN_INSTAGRAM_NO_SCHEME + "|"
+ STRING_PATTERN_TWITPIC_NO_SCHEME + "|" + STRING_PATTERN_IMGLY_NO_SCHEME + "|"
+ STRING_PATTERN_YFROG_NO_SCHEME + "|" + STRING_PATTERN_TWITGOO_NO_SCHEME + "|"
+ STRING_PATTERN_MOBYPICTURE_NO_SCHEME + "|" + STRING_PATTERN_IMGUR_NO_SCHEME + "|"
+ STRING_PATTERN_PHOTOZOU_NO_SCHEME + "))\">", Pattern.CASE_INSENSITIVE);
public static final int PREVIEW_AVAILABLE_IMAGES_IN_HTML_GROUP_LINK = 1;
public static final Pattern PATTERN_IMAGES = Pattern.compile(STRING_PATTERN_IMAGES, Pattern.CASE_INSENSITIVE);
public static final Pattern PATTERN_TWITTER_IMAGES = Pattern.compile(STRING_PATTERN_TWITTER_IMAGES,
Pattern.CASE_INSENSITIVE);
public static final Pattern PATTERN_SINA_WEIBO_IMAGES = Pattern.compile(STRING_PATTERN_SINA_WEIBO_IMAGES,
Pattern.CASE_INSENSITIVE);
public static final Pattern PATTERN_LOCKERZ_AND_PLIXI = Pattern.compile(STRING_PATTERN_LOCKERZ_AND_PLIXI,
Pattern.CASE_INSENSITIVE);
public static final Pattern PATTERN_INSTAGRAM = Pattern.compile(STRING_PATTERN_INSTAGRAM, Pattern.CASE_INSENSITIVE);
public static final int INSTAGRAM_GROUP_ID = 3;
public static final Pattern PATTERN_TWITPIC = Pattern.compile(STRING_PATTERN_TWITPIC, Pattern.CASE_INSENSITIVE);
public static final int TWITPIC_GROUP_ID = 2;
public static final Pattern PATTERN_IMGLY = Pattern.compile(STRING_PATTERN_IMGLY, Pattern.CASE_INSENSITIVE);
public static final int IMGLY_GROUP_ID = 2;
public static final Pattern PATTERN_YFROG = Pattern.compile(STRING_PATTERN_YFROG, Pattern.CASE_INSENSITIVE);
public static final int YFROG_GROUP_ID = 2;
public static final Pattern PATTERN_TWITGOO = Pattern.compile(STRING_PATTERN_TWITGOO, Pattern.CASE_INSENSITIVE);
public static final int TWITGOO_GROUP_ID = 2;
public static final Pattern PATTERN_MOBYPICTURE = Pattern.compile(STRING_PATTERN_MOBYPICTURE,
Pattern.CASE_INSENSITIVE);
public static final int MOBYPICTURE_GROUP_ID = 2;
public static final Pattern PATTERN_IMGUR = Pattern.compile(STRING_PATTERN_IMGUR, Pattern.CASE_INSENSITIVE);
public static final int IMGUR_GROUP_ID = 3;
public static final Pattern PATTERN_PHOTOZOU = Pattern.compile(STRING_PATTERN_PHOTOZOU, Pattern.CASE_INSENSITIVE);
public static final int PHOTOZOU_GROUP_ID = 3;
public static final String TWITTER_PROFILE_IMAGES_AVAILABLE_SIZES = "(bigger|normal|mini)";
private static final String STRING_PATTERN_TWITTER_PROFILE_IMAGES_NO_SCHEME = "([\\w\\d]+)\\.twimg\\.com\\/profile_images\\/([\\d\\w\\-_]+)\\/([\\d\\w\\-_]+)_"
+ TWITTER_PROFILE_IMAGES_AVAILABLE_SIZES + "(\\.?" + AVAILABLE_IMAGE_SHUFFIX + ")?";
private static final String STRING_PATTERN_TWITTER_PROFILE_IMAGES = AVAILABLE_URL_SCHEME_PREFIX
+ STRING_PATTERN_TWITTER_PROFILE_IMAGES_NO_SCHEME;
public static final Pattern PATTERN_TWITTER_PROFILE_IMAGES = Pattern.compile(STRING_PATTERN_TWITTER_PROFILE_IMAGES,
Pattern.CASE_INSENSITIVE);
private final TextView view;
private OnLinkClickListener mOnLinkClickListener;
/**
* Filters out web URL matches that occur after an at-sign (@). This is to
* prevent turning the domain name in an email address into a web link.
*/
public static final MatchFilter sUrlMatchFilter = new MatchFilter() {
@Override
public final boolean acceptMatch(final CharSequence s, final int start, final int end) {
if (start == 0) return true;
if (s.charAt(start - 1) == '@') return false;
return true;
}
};
public TwidereLinkify(final TextView view) {
this.view = view;
view.setMovementMethod(LinkMovementMethod.getInstance());
}
public final void addAllLinks() {
for (final int type : ALL_LINK_TYPES) {
addLinks(type);
}
}
/**
* Applies a regex to the text of a TextView turning the matches into links.
* If links are found then UrlSpans are applied to the link text match
* areas, and the movement method for the text is changed to
* LinkMovementMethod.
*
* @param description TextView whose text is to be marked-up with links
* @param pattern Regex pattern to be used for finding links
* @param scheme Url scheme string (eg <code>http://</code> to be prepended
* to the url of links that do not have a scheme specified in the
* link text
*/
public final void addLinks(final int type) {
final SpannableString string = SpannableString.valueOf(view.getText());
switch (type) {
case LINK_TYPE_MENTION_LIST: {
addMentionOrListLinks(string);
break;
}
case LINK_TYPE_HASHTAG: {
addHashtagLinks(string);
break;
}
case LINK_TYPE_LINK_WITH_IMAGE_EXTENSION: {
final URLSpan[] spans = string.getSpans(0, string.length(), URLSpan.class);
for (final URLSpan span : spans) {
final int start = string.getSpanStart(span);
final int end = string.getSpanEnd(span);
final String url = span.getURL();
if (PATTERN_IMAGES.matcher(url).matches()) {
string.removeSpan(span);
applyLink(url, start, end, string, LINK_TYPE_LINK_WITH_IMAGE_EXTENSION);
}
}
break;
}
case LINK_TYPE_LINK: {
final ArrayList<LinkSpec> links = new ArrayList<LinkSpec>();
gatherLinks(links, string, Patterns.WEB_URL, new String[] { "http://", "https://", "rtsp://" },
sUrlMatchFilter, null);
for (final LinkSpec link : links) {
final URLSpan[] spans = string.getSpans(link.start, link.end, URLSpan.class);
- if (spans == null || spans.length <= 0) {
- applyLink(link.url, link.start, link.end, string, LINK_TYPE_LINK);
+ if (spans != null) {
+ for (final URLSpan span : spans) {
+ string.removeSpan(span);
+ }
}
+ applyLink(link.url, link.start, link.end, string, LINK_TYPE_LINK);
}
break;
}
case LINK_TYPE_ALL_AVAILABLE_IMAGE: {
final URLSpan[] spans = string.getSpans(0, string.length(), URLSpan.class);
for (final URLSpan span : spans) {
final Matcher matcher = PATTERN_ALL_AVAILABLE_IMAGES.matcher(span.getURL());
if (matcher.matches()) {
final ImageSpec spec = getAllAvailableImage(matcher.group());
if (spec == null) {
break;
}
final int start = string.getSpanStart(span);
final int end = string.getSpanEnd(span);
final String url = spec.image_link;
string.removeSpan(span);
applyLink(url, start, end, string, LINK_TYPE_LINK_WITH_IMAGE_EXTENSION);
}
}
break;
}
case LINK_TYPE_CASHTAG: {
addCashtagLinks(string);
break;
}
default: {
return;
}
}
view.setText(string);
addLinkMovementMethod(view);
}
public OnLinkClickListener getmOnLinkClickListener() {
return mOnLinkClickListener;
}
public void setOnLinkClickListener(final OnLinkClickListener listener) {
mOnLinkClickListener = listener;
}
private final boolean addCashtagLinks(final Spannable spannable) {
boolean hasMatches = false;
final Matcher matcher = Regex.VALID_CASHTAG.matcher(spannable);
while (matcher.find()) {
final int start = matcherStart(matcher, Regex.VALID_CASHTAG_GROUP_CASHTAG_FULL);
final int end = matcherEnd(matcher, Regex.VALID_CASHTAG_GROUP_CASHTAG_FULL);
final String url = matcherGroup(matcher, Regex.VALID_CASHTAG_GROUP_TAG);
applyLink(url, start, end, spannable, LINK_TYPE_HASHTAG);
hasMatches = true;
}
return hasMatches;
}
private final boolean addHashtagLinks(final Spannable spannable) {
boolean hasMatches = false;
final Matcher matcher = Regex.VALID_HASHTAG.matcher(spannable);
while (matcher.find()) {
final int start = matcherStart(matcher, Regex.VALID_HASHTAG_GROUP_HASHTAG_FULL);
final int end = matcherEnd(matcher, Regex.VALID_HASHTAG_GROUP_HASHTAG_FULL);
final String url = matcherGroup(matcher, Regex.VALID_HASHTAG_GROUP_HASHTAG_FULL);
applyLink(url, start, end, spannable, LINK_TYPE_HASHTAG);
hasMatches = true;
}
return hasMatches;
}
private final boolean addMentionOrListLinks(final Spannable spannable) {
boolean hasMatches = false;
final Matcher matcher = Regex.VALID_MENTION_OR_LIST.matcher(spannable);
while (matcher.find()) {
final int start = matcherStart(matcher, Regex.VALID_MENTION_OR_LIST_GROUP_AT);
final int username_end = matcherEnd(matcher, Regex.VALID_MENTION_OR_LIST_GROUP_USERNAME);
final int list_start = matcherStart(matcher, Regex.VALID_MENTION_OR_LIST_GROUP_LIST);
final int list_end = matcherEnd(matcher, Regex.VALID_MENTION_OR_LIST_GROUP_LIST);
final String mention = matcherGroup(matcher, Regex.VALID_MENTION_OR_LIST_GROUP_USERNAME);
final String list = matcherGroup(matcher, Regex.VALID_MENTION_OR_LIST_GROUP_LIST);
applyLink(mention, start, username_end, spannable, LINK_TYPE_MENTION_LIST);
if (list_start >= 0 && list_end >= 0) {
applyLink(mention + "/" + list, list_start, list_end, spannable, LINK_TYPE_LIST);
}
hasMatches = true;
}
return hasMatches;
}
private final void applyLink(final String url, final int start, final int end, final Spannable text, final int type) {
final LinkSpan span = new LinkSpan(url, type, mOnLinkClickListener);
text.setSpan(span, start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
private static final void addLinkMovementMethod(final TextView t) {
final MovementMethod m = t.getMovementMethod();
if (m == null || !(m instanceof LinkMovementMethod)) {
if (t.getLinksClickable()) {
t.setMovementMethod(LinkMovementMethod.getInstance());
}
}
}
private static final void gatherLinks(final ArrayList<LinkSpec> links, final Spannable s, final Pattern pattern,
final String[] schemes, final MatchFilter matchFilter, final TransformFilter transformFilter) {
final Matcher m = pattern.matcher(s);
while (m.find()) {
final int start = m.start();
final int end = m.end();
if (matchFilter == null || matchFilter.acceptMatch(s, start, end)) {
final LinkSpec spec = new LinkSpec();
final String url = makeUrl(m.group(0), schemes, m, transformFilter);
spec.url = url;
spec.start = start;
spec.end = end;
links.add(spec);
}
}
}
private static final String makeUrl(String url, final String[] prefixes, final Matcher m,
final TransformFilter filter) {
if (filter != null) {
url = filter.transformUrl(m, url);
}
boolean hasPrefix = false;
final int length = prefixes.length;
for (int i = 0; i < length; i++) {
if (url.regionMatches(true, 0, prefixes[i], 0, prefixes[i].length())) {
hasPrefix = true;
// Fix capitalization if necessary
if (!url.regionMatches(false, 0, prefixes[i], 0, prefixes[i].length())) {
url = prefixes[i] + url.substring(prefixes[i].length());
}
break;
}
}
if (!hasPrefix) {
url = prefixes[0] + url;
}
return url;
}
/**
* MatchFilter enables client code to have more control over what is allowed
* to match and become a link, and what is not.
*
* For example: when matching web urls you would like things like
* http://www.example.com to match, as well as just example.com itelf.
* However, you would not want to match against the domain in
* [email protected]. So, when matching against a web url pattern you
* might also include a MatchFilter that disallows the match if it is
* immediately preceded by an at-sign (@).
*/
public interface MatchFilter {
/**
* Examines the character span matched by the pattern and determines if
* the match should be turned into an actionable link.
*
* @param s The body of text against which the pattern was matched
* @param start The index of the first character in s that was matched
* by the pattern - inclusive
* @param end The index of the last character in s that was matched -
* exclusive
*
* @return Whether this match should be turned into a link
*/
boolean acceptMatch(CharSequence s, int start, int end);
}
public interface OnLinkClickListener {
public void onLinkClick(String link, int type);
}
/**
* TransformFilter enables client code to have more control over how matched
* patterns are represented as URLs.
*
* For example: when converting a phone number such as (919) 555-1212 into a
* tel: URL the parentheses, white space, and hyphen need to be removed to
* produce tel:9195551212.
*/
public interface TransformFilter {
/**
* Examines the matched text and either passes it through or uses the
* data in the Matcher state to produce a replacement.
*
* @param match The regex matcher state that found this URL text
* @param url The text that was matched
*
* @return The transformed form of the URL
*/
String transformUrl(final Matcher match, String url);
}
static class LinkSpan extends URLSpan {
private final int type;
private final OnLinkClickListener listener;
public LinkSpan(final String url, final int type, final OnLinkClickListener listener) {
super(url);
this.type = type;
this.listener = listener;
}
@Override
public void onClick(final View widget) {
if (listener != null) {
listener.onLinkClick(getURL(), type);
}
}
}
}
class LinkSpec {
String url;
int start;
int end;
}
| false | true | public final void addLinks(final int type) {
final SpannableString string = SpannableString.valueOf(view.getText());
switch (type) {
case LINK_TYPE_MENTION_LIST: {
addMentionOrListLinks(string);
break;
}
case LINK_TYPE_HASHTAG: {
addHashtagLinks(string);
break;
}
case LINK_TYPE_LINK_WITH_IMAGE_EXTENSION: {
final URLSpan[] spans = string.getSpans(0, string.length(), URLSpan.class);
for (final URLSpan span : spans) {
final int start = string.getSpanStart(span);
final int end = string.getSpanEnd(span);
final String url = span.getURL();
if (PATTERN_IMAGES.matcher(url).matches()) {
string.removeSpan(span);
applyLink(url, start, end, string, LINK_TYPE_LINK_WITH_IMAGE_EXTENSION);
}
}
break;
}
case LINK_TYPE_LINK: {
final ArrayList<LinkSpec> links = new ArrayList<LinkSpec>();
gatherLinks(links, string, Patterns.WEB_URL, new String[] { "http://", "https://", "rtsp://" },
sUrlMatchFilter, null);
for (final LinkSpec link : links) {
final URLSpan[] spans = string.getSpans(link.start, link.end, URLSpan.class);
if (spans == null || spans.length <= 0) {
applyLink(link.url, link.start, link.end, string, LINK_TYPE_LINK);
}
}
break;
}
case LINK_TYPE_ALL_AVAILABLE_IMAGE: {
final URLSpan[] spans = string.getSpans(0, string.length(), URLSpan.class);
for (final URLSpan span : spans) {
final Matcher matcher = PATTERN_ALL_AVAILABLE_IMAGES.matcher(span.getURL());
if (matcher.matches()) {
final ImageSpec spec = getAllAvailableImage(matcher.group());
if (spec == null) {
break;
}
final int start = string.getSpanStart(span);
final int end = string.getSpanEnd(span);
final String url = spec.image_link;
string.removeSpan(span);
applyLink(url, start, end, string, LINK_TYPE_LINK_WITH_IMAGE_EXTENSION);
}
}
break;
}
case LINK_TYPE_CASHTAG: {
addCashtagLinks(string);
break;
}
default: {
return;
}
}
view.setText(string);
addLinkMovementMethod(view);
}
| public final void addLinks(final int type) {
final SpannableString string = SpannableString.valueOf(view.getText());
switch (type) {
case LINK_TYPE_MENTION_LIST: {
addMentionOrListLinks(string);
break;
}
case LINK_TYPE_HASHTAG: {
addHashtagLinks(string);
break;
}
case LINK_TYPE_LINK_WITH_IMAGE_EXTENSION: {
final URLSpan[] spans = string.getSpans(0, string.length(), URLSpan.class);
for (final URLSpan span : spans) {
final int start = string.getSpanStart(span);
final int end = string.getSpanEnd(span);
final String url = span.getURL();
if (PATTERN_IMAGES.matcher(url).matches()) {
string.removeSpan(span);
applyLink(url, start, end, string, LINK_TYPE_LINK_WITH_IMAGE_EXTENSION);
}
}
break;
}
case LINK_TYPE_LINK: {
final ArrayList<LinkSpec> links = new ArrayList<LinkSpec>();
gatherLinks(links, string, Patterns.WEB_URL, new String[] { "http://", "https://", "rtsp://" },
sUrlMatchFilter, null);
for (final LinkSpec link : links) {
final URLSpan[] spans = string.getSpans(link.start, link.end, URLSpan.class);
if (spans != null) {
for (final URLSpan span : spans) {
string.removeSpan(span);
}
}
applyLink(link.url, link.start, link.end, string, LINK_TYPE_LINK);
}
break;
}
case LINK_TYPE_ALL_AVAILABLE_IMAGE: {
final URLSpan[] spans = string.getSpans(0, string.length(), URLSpan.class);
for (final URLSpan span : spans) {
final Matcher matcher = PATTERN_ALL_AVAILABLE_IMAGES.matcher(span.getURL());
if (matcher.matches()) {
final ImageSpec spec = getAllAvailableImage(matcher.group());
if (spec == null) {
break;
}
final int start = string.getSpanStart(span);
final int end = string.getSpanEnd(span);
final String url = spec.image_link;
string.removeSpan(span);
applyLink(url, start, end, string, LINK_TYPE_LINK_WITH_IMAGE_EXTENSION);
}
}
break;
}
case LINK_TYPE_CASHTAG: {
addCashtagLinks(string);
break;
}
default: {
return;
}
}
view.setText(string);
addLinkMovementMethod(view);
}
|
diff --git a/tool/src/rimd/src/org/rikulo/rimd/RikuloLinkRenderer.java b/tool/src/rimd/src/org/rikulo/rimd/RikuloLinkRenderer.java
index e2a08eb..82a1a07 100755
--- a/tool/src/rimd/src/org/rikulo/rimd/RikuloLinkRenderer.java
+++ b/tool/src/rimd/src/org/rikulo/rimd/RikuloLinkRenderer.java
@@ -1,94 +1,94 @@
//Copyright (C) 2012 Potix Corporation. All Rights Reserved.
//History: Sat, July 07, 2012
// Author: tomyeh
package org.rikulo.rimd;
import org.pegdown.LinkRenderer;
import org.pegdown.ast.ExpLinkNode;
public class RikuloLinkRenderer extends LinkRenderer {
final Processor _proc;
RikuloLinkRenderer(Processor proc) {
_proc = proc;
}
public Rendering render(ExpLinkNode node, String text) {
String url = node.url;
boolean bApi = false, bDart = false;
if (url.startsWith("source:")) {
//source: [name](source:dir) or [name](source:lib:dir)
final int i = url.indexOf(':', 7);
final String lib = i >= 0 ? url.substring(7, i): null;
String dir = url.substring(i >= 0 ? i + 1: 7);
if (dir.length() > 0 && dir.charAt(dir.length() - 1) != '/')
dir += '/';
return new Rendering(
(lib != null ? _proc.libsource.replace("{lib}", lib): _proc.source) + dir + text,
"<code>" + text + "</code>");
} else if ((bApi = url.equals("api:")) || (bDart = url.equals("dart:"))
|| url.endsWith(":")) {
//package: [view](api:) or [html](dart:) or (el_impl)(el:)
final String lib = !bApi && !bDart ? url.substring(0, url.length() - 1): null;
final String urlPrefix = bApi ? _proc.api: bDart ? _proc.dartapi:
_proc.libapi.replace("{lib}", lib);
return new Rendering(urlPrefix + text.replace('/', '_') + ".html",
- "<code>" + text + "</code>");
+ "<code>" + (bDart ? "dart:" : "rikulo_" + text) + "</code>");
} else if ((bApi = url.startsWith("api:")) || (bDart = url.startsWith("dart:"))
|| url.indexOf(':') > 0) {
/* Link to a class: [ViewConfig](api:view/impl) or [CSSStyleDecalration](dart:html)
* Link to a method: [View.requestLayout()](api:view)
* Link to a getter: [View.width](api:view) or [View.width](api:view:get)
* Link to a setter: [View.width](api:view:set)
* Link to a global variable: [rootViews](api:view)
*/
int iColon = 0;
final String lib = !bApi && !bDart ? url.substring(0, iColon = url.indexOf(':')): null;
final String urlPrefix = bApi ? _proc.api: bDart ? _proc.dartapi:
_proc.libapi.replace("{lib}", lib);
boolean bGet = url.endsWith(":get"), bSet = !bGet && url.endsWith(":set");
if (bGet || bSet)
url = url.substring(0, url.length() - 4);
final String pkg = url.substring(bApi ? 4: bDart ? 5: iColon + 1).replace('/', '_');
int i = text.lastIndexOf('(');
// final boolean bMethod = i >= 0;
final String info = i >= 0 ? text.substring(0, i): text;
i = info.indexOf('.');
boolean bVar = i < 0 && Character.isLowerCase(text.charAt(0));
if (bVar)
return new Rendering(urlPrefix + pkg + ".html#" + info,
"<code>" + text + "</code>");
String mtd = i >= 0 ? info.substring(i + 1).trim(): null;
boolean bOp = mtd != null && mtd.startsWith("operator");
if (bOp) {
if (mtd.indexOf('[') > 0)
mtd = mtd.indexOf('=') > 0 ? "[]=": "[]";
else if (mtd.indexOf("==") > 0)
mtd = ":eq";
else if (mtd.indexOf('+') > 0)
mtd = ":add";
else if (mtd.indexOf('-') > 0)
mtd = ":sub";
else if (mtd.indexOf('*') > 0)
mtd = ":mul";
else if (mtd.indexOf('/') > 0)
mtd = ":div";
else
bOp = false;
}
final String clsnm = i >= 0 ?
info.substring(0, i) + ".html#"
+ mtd + (bSet ? "=": ""):
info + _proc.extension;
return new Rendering(urlPrefix + pkg + "/" + clsnm,
"<code>" + text + "</code>");
} else {
final int i = url.lastIndexOf(".md");
final char cc;
if (i >= 0 && ((i + 3) == url.length() || (cc=url.charAt(i + 3)) == '#' || cc == '?'))
return new Rendering(
url.substring(0, i+1) + "html" + url.substring(i + 3), text);
}
return super.render(node, text);
}
}
| true | true | public Rendering render(ExpLinkNode node, String text) {
String url = node.url;
boolean bApi = false, bDart = false;
if (url.startsWith("source:")) {
//source: [name](source:dir) or [name](source:lib:dir)
final int i = url.indexOf(':', 7);
final String lib = i >= 0 ? url.substring(7, i): null;
String dir = url.substring(i >= 0 ? i + 1: 7);
if (dir.length() > 0 && dir.charAt(dir.length() - 1) != '/')
dir += '/';
return new Rendering(
(lib != null ? _proc.libsource.replace("{lib}", lib): _proc.source) + dir + text,
"<code>" + text + "</code>");
} else if ((bApi = url.equals("api:")) || (bDart = url.equals("dart:"))
|| url.endsWith(":")) {
//package: [view](api:) or [html](dart:) or (el_impl)(el:)
final String lib = !bApi && !bDart ? url.substring(0, url.length() - 1): null;
final String urlPrefix = bApi ? _proc.api: bDart ? _proc.dartapi:
_proc.libapi.replace("{lib}", lib);
return new Rendering(urlPrefix + text.replace('/', '_') + ".html",
"<code>" + text + "</code>");
} else if ((bApi = url.startsWith("api:")) || (bDart = url.startsWith("dart:"))
|| url.indexOf(':') > 0) {
/* Link to a class: [ViewConfig](api:view/impl) or [CSSStyleDecalration](dart:html)
* Link to a method: [View.requestLayout()](api:view)
* Link to a getter: [View.width](api:view) or [View.width](api:view:get)
* Link to a setter: [View.width](api:view:set)
* Link to a global variable: [rootViews](api:view)
*/
int iColon = 0;
final String lib = !bApi && !bDart ? url.substring(0, iColon = url.indexOf(':')): null;
final String urlPrefix = bApi ? _proc.api: bDart ? _proc.dartapi:
_proc.libapi.replace("{lib}", lib);
boolean bGet = url.endsWith(":get"), bSet = !bGet && url.endsWith(":set");
if (bGet || bSet)
url = url.substring(0, url.length() - 4);
final String pkg = url.substring(bApi ? 4: bDart ? 5: iColon + 1).replace('/', '_');
int i = text.lastIndexOf('(');
// final boolean bMethod = i >= 0;
final String info = i >= 0 ? text.substring(0, i): text;
i = info.indexOf('.');
boolean bVar = i < 0 && Character.isLowerCase(text.charAt(0));
if (bVar)
return new Rendering(urlPrefix + pkg + ".html#" + info,
"<code>" + text + "</code>");
String mtd = i >= 0 ? info.substring(i + 1).trim(): null;
boolean bOp = mtd != null && mtd.startsWith("operator");
if (bOp) {
if (mtd.indexOf('[') > 0)
mtd = mtd.indexOf('=') > 0 ? "[]=": "[]";
else if (mtd.indexOf("==") > 0)
mtd = ":eq";
else if (mtd.indexOf('+') > 0)
mtd = ":add";
else if (mtd.indexOf('-') > 0)
mtd = ":sub";
else if (mtd.indexOf('*') > 0)
mtd = ":mul";
else if (mtd.indexOf('/') > 0)
mtd = ":div";
else
bOp = false;
}
final String clsnm = i >= 0 ?
info.substring(0, i) + ".html#"
+ mtd + (bSet ? "=": ""):
info + _proc.extension;
return new Rendering(urlPrefix + pkg + "/" + clsnm,
"<code>" + text + "</code>");
} else {
final int i = url.lastIndexOf(".md");
final char cc;
if (i >= 0 && ((i + 3) == url.length() || (cc=url.charAt(i + 3)) == '#' || cc == '?'))
return new Rendering(
url.substring(0, i+1) + "html" + url.substring(i + 3), text);
}
return super.render(node, text);
}
| public Rendering render(ExpLinkNode node, String text) {
String url = node.url;
boolean bApi = false, bDart = false;
if (url.startsWith("source:")) {
//source: [name](source:dir) or [name](source:lib:dir)
final int i = url.indexOf(':', 7);
final String lib = i >= 0 ? url.substring(7, i): null;
String dir = url.substring(i >= 0 ? i + 1: 7);
if (dir.length() > 0 && dir.charAt(dir.length() - 1) != '/')
dir += '/';
return new Rendering(
(lib != null ? _proc.libsource.replace("{lib}", lib): _proc.source) + dir + text,
"<code>" + text + "</code>");
} else if ((bApi = url.equals("api:")) || (bDart = url.equals("dart:"))
|| url.endsWith(":")) {
//package: [view](api:) or [html](dart:) or (el_impl)(el:)
final String lib = !bApi && !bDart ? url.substring(0, url.length() - 1): null;
final String urlPrefix = bApi ? _proc.api: bDart ? _proc.dartapi:
_proc.libapi.replace("{lib}", lib);
return new Rendering(urlPrefix + text.replace('/', '_') + ".html",
"<code>" + (bDart ? "dart:" : "rikulo_" + text) + "</code>");
} else if ((bApi = url.startsWith("api:")) || (bDart = url.startsWith("dart:"))
|| url.indexOf(':') > 0) {
/* Link to a class: [ViewConfig](api:view/impl) or [CSSStyleDecalration](dart:html)
* Link to a method: [View.requestLayout()](api:view)
* Link to a getter: [View.width](api:view) or [View.width](api:view:get)
* Link to a setter: [View.width](api:view:set)
* Link to a global variable: [rootViews](api:view)
*/
int iColon = 0;
final String lib = !bApi && !bDart ? url.substring(0, iColon = url.indexOf(':')): null;
final String urlPrefix = bApi ? _proc.api: bDart ? _proc.dartapi:
_proc.libapi.replace("{lib}", lib);
boolean bGet = url.endsWith(":get"), bSet = !bGet && url.endsWith(":set");
if (bGet || bSet)
url = url.substring(0, url.length() - 4);
final String pkg = url.substring(bApi ? 4: bDart ? 5: iColon + 1).replace('/', '_');
int i = text.lastIndexOf('(');
// final boolean bMethod = i >= 0;
final String info = i >= 0 ? text.substring(0, i): text;
i = info.indexOf('.');
boolean bVar = i < 0 && Character.isLowerCase(text.charAt(0));
if (bVar)
return new Rendering(urlPrefix + pkg + ".html#" + info,
"<code>" + text + "</code>");
String mtd = i >= 0 ? info.substring(i + 1).trim(): null;
boolean bOp = mtd != null && mtd.startsWith("operator");
if (bOp) {
if (mtd.indexOf('[') > 0)
mtd = mtd.indexOf('=') > 0 ? "[]=": "[]";
else if (mtd.indexOf("==") > 0)
mtd = ":eq";
else if (mtd.indexOf('+') > 0)
mtd = ":add";
else if (mtd.indexOf('-') > 0)
mtd = ":sub";
else if (mtd.indexOf('*') > 0)
mtd = ":mul";
else if (mtd.indexOf('/') > 0)
mtd = ":div";
else
bOp = false;
}
final String clsnm = i >= 0 ?
info.substring(0, i) + ".html#"
+ mtd + (bSet ? "=": ""):
info + _proc.extension;
return new Rendering(urlPrefix + pkg + "/" + clsnm,
"<code>" + text + "</code>");
} else {
final int i = url.lastIndexOf(".md");
final char cc;
if (i >= 0 && ((i + 3) == url.length() || (cc=url.charAt(i + 3)) == '#' || cc == '?'))
return new Rendering(
url.substring(0, i+1) + "html" + url.substring(i + 3), text);
}
return super.render(node, text);
}
|
diff --git a/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/issues/ActionPlansWidget.java b/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/issues/ActionPlansWidget.java
index f56b3017b8..6da3c1c362 100644
--- a/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/issues/ActionPlansWidget.java
+++ b/plugins/sonar-core-plugin/src/main/java/org/sonar/plugins/core/widgets/issues/ActionPlansWidget.java
@@ -1,37 +1,36 @@
/*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2013 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.plugins.core.widgets.issues;
import org.sonar.api.web.WidgetCategory;
import org.sonar.api.web.WidgetProperties;
import org.sonar.api.web.WidgetProperty;
import org.sonar.api.web.WidgetPropertyType;
import org.sonar.plugins.core.widgets.CoreWidget;
@WidgetCategory({"Action plans", "Issues"})
@WidgetProperties({
@WidgetProperty(key = "showResolvedIssues", type = WidgetPropertyType.BOOLEAN, defaultValue = "true")
})
public class ActionPlansWidget extends CoreWidget {
public ActionPlansWidget() {
-// super("issues_action_plans", "Issues action plans", "/org/sonar/plugins/core/widgets/issues/action_plans.html.erb");
- super("issues_action_plans", "Action plans", "/Users/julienlancelot/Dev/Sources/sonar/plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/issues/action_plans.html.erb");
+ super("issues_action_plans", "Issues action plans", "/org/sonar/plugins/core/widgets/issues/action_plans.html.erb");
}
}
| true | true | public ActionPlansWidget() {
// super("issues_action_plans", "Issues action plans", "/org/sonar/plugins/core/widgets/issues/action_plans.html.erb");
super("issues_action_plans", "Action plans", "/Users/julienlancelot/Dev/Sources/sonar/plugins/sonar-core-plugin/src/main/resources/org/sonar/plugins/core/widgets/issues/action_plans.html.erb");
}
| public ActionPlansWidget() {
super("issues_action_plans", "Issues action plans", "/org/sonar/plugins/core/widgets/issues/action_plans.html.erb");
}
|
diff --git a/parser/org/eclipse/cdt/internal/core/parser/scanner/ExpressionEvaluator.java b/parser/org/eclipse/cdt/internal/core/parser/scanner/ExpressionEvaluator.java
index 2bd913ee4..3cf380f04 100644
--- a/parser/org/eclipse/cdt/internal/core/parser/scanner/ExpressionEvaluator.java
+++ b/parser/org/eclipse/cdt/internal/core/parser/scanner/ExpressionEvaluator.java
@@ -1,406 +1,412 @@
/*******************************************************************************
* Copyright (c) 2004, 2008 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial implementation
* Markus Schorn (Wind River Systems)
* Bryan Wilkinson (QNX) - https://bugs.eclipse.org/bugs/show_bug.cgi?id=151207
* Anton Leherbauer (Wind River Systems)
*******************************************************************************/
package org.eclipse.cdt.internal.core.parser.scanner;
import java.util.ArrayList;
import org.eclipse.cdt.core.dom.ast.IASTName;
import org.eclipse.cdt.core.parser.IProblem;
import org.eclipse.cdt.core.parser.IToken;
import org.eclipse.cdt.core.parser.util.CharArrayMap;
/**
* Used to evaluate expressions in preprocessor directives.
*/
class ExpressionEvaluator {
static class EvalException extends Exception {
private int fProblemID;
private char[] fProblemArg;
public EvalException(int problemID, char[] problemArg) {
fProblemID= problemID;
fProblemArg= problemArg;
}
public int getProblemID() {
return fProblemID;
}
public char[] getProblemArg() {
return fProblemArg;
}
}
private Token fTokens;
private CharArrayMap<PreprocessorMacro> fDictionary;
private ArrayList<IASTName> fMacrosInDefinedExpressions= new ArrayList<IASTName>();
private LocationMap fLocationMap;
public boolean evaluate(TokenList condition, CharArrayMap<PreprocessorMacro> macroDictionary, LocationMap map) throws EvalException {
fTokens= condition.first();
fDictionary= macroDictionary;
fLocationMap= map;
fMacrosInDefinedExpressions.clear();
return expression() != 0;
}
public IASTName[] clearMacrosInDefinedExpression() {
IASTName[] result= fMacrosInDefinedExpressions.toArray(new IASTName[fMacrosInDefinedExpressions.size()]);
fMacrosInDefinedExpressions.clear();
return result;
}
private long expression() throws EvalException {
return conditionalExpression();
}
private long conditionalExpression() throws EvalException {
long r1 = logicalOrExpression();
if (LA() == IToken.tQUESTION) {
consume();
long r2 = expression();
if (LA() == IToken.tCOLON)
consume();
else {
throw new EvalException(IProblem.SCANNER_BAD_CONDITIONAL_EXPRESSION, null);
}
long r3 = conditionalExpression();
return r1 != 0 ? r2 : r3;
}
return r1;
}
private long logicalOrExpression() throws EvalException {
long r1 = logicalAndExpression();
while (LA() == IToken.tOR) {
consume();
long r2 = logicalAndExpression();
r1 = ((r1 != 0) || (r2 != 0)) ? 1 : 0;
}
return r1;
}
private long logicalAndExpression() throws EvalException {
long r1 = inclusiveOrExpression();
while (LA() == IToken.tAND) {
consume();
long r2 = inclusiveOrExpression();
r1 = ((r1 != 0) && (r2 != 0)) ? 1 : 0;
}
return r1;
}
private long inclusiveOrExpression() throws EvalException {
long r1 = exclusiveOrExpression();
while (LA() == IToken.tBITOR) {
consume();
long r2 = exclusiveOrExpression();
r1 = r1 | r2;
}
return r1;
}
private long exclusiveOrExpression() throws EvalException {
long r1 = andExpression();
while (LA() == IToken.tXOR) {
consume();
long r2 = andExpression();
r1 = r1 ^ r2;
}
return r1;
}
private long andExpression() throws EvalException {
long r1 = equalityExpression();
while (LA() == IToken.tAMPER) {
consume();
long r2 = equalityExpression();
r1 = r1 & r2;
}
return r1;
}
private long equalityExpression() throws EvalException {
long r1 = relationalExpression();
for (int t = LA(); t == IToken.tEQUAL || t == IToken.tNOTEQUAL; t = LA()) {
consume();
long r2 = relationalExpression();
if (t == IToken.tEQUAL)
r1 = (r1 == r2) ? 1 : 0;
else
// t == tNOTEQUAL
r1 = (r1 != r2) ? 1 : 0;
}
return r1;
}
private long relationalExpression() throws EvalException {
long r1 = shiftExpression();
for (int t = LA(); t == IToken.tLT || t == IToken.tLTEQUAL || t == IToken.tGT
|| t == IToken.tGTEQUAL || t == IToken.tASSIGN; t = LA()) {
consume();
long r2 = shiftExpression();
switch (t) {
case IToken.tLT:
r1 = (r1 < r2) ? 1 : 0;
break;
case IToken.tLTEQUAL:
r1 = (r1 <= r2) ? 1 : 0;
break;
case IToken.tGT:
r1 = (r1 > r2) ? 1 : 0;
break;
case IToken.tGTEQUAL:
r1 = (r1 >= r2) ? 1 : 0;
break;
case IToken.tASSIGN:
throw new EvalException(IProblem.SCANNER_ASSIGNMENT_NOT_ALLOWED, null);
}
}
return r1;
}
private long shiftExpression() throws EvalException {
long r1 = additiveExpression();
for (int t = LA(); t == IToken.tSHIFTL || t == IToken.tSHIFTR; t = LA()) {
consume();
long r2 = additiveExpression();
if (t == IToken.tSHIFTL)
r1 = r1 << r2;
else
// t == tSHIFTR
r1 = r1 >> r2;
}
return r1;
}
private long additiveExpression() throws EvalException {
long r1 = multiplicativeExpression();
for (int t = LA(); t == IToken.tPLUS || t == IToken.tMINUS; t = LA()) {
consume();
long r2 = multiplicativeExpression();
if (t == IToken.tPLUS)
r1 = r1 + r2;
else
// t == tMINUS
r1 = r1 - r2;
}
return r1;
}
private long multiplicativeExpression() throws EvalException {
long r1 = unaryExpression();
for (int t = LA(); t == IToken.tSTAR || t == IToken.tDIV || t == IToken.tMOD; t = LA()) {
consume();
long r2 = unaryExpression();
if (t == IToken.tSTAR)
r1 = r1 * r2;
else if (r2 != 0) {
if (t == IToken.tDIV)
r1 = r1 / r2;
else
r1 = r1 % r2; //tMOD
} else {
throw new EvalException(IProblem.SCANNER_DIVIDE_BY_ZERO, null);
}
}
return r1;
}
private long unaryExpression() throws EvalException {
switch (LA()) {
case IToken.tPLUS:
consume();
return unaryExpression();
case IToken.tMINUS:
consume();
return -unaryExpression();
case IToken.tNOT:
consume();
return unaryExpression() == 0 ? 1 : 0;
case IToken.tBITCOMPLEMENT:
consume();
return ~unaryExpression();
case IToken.tCHAR:
case IToken.tLCHAR:
case IToken.tINTEGER:
long val= getValue(fTokens);
consume();
return val;
+ case IToken.t_true:
+ consume();
+ return 1;
+ case IToken.t_false:
+ consume();
+ return 0;
case CPreprocessor.tDEFINED:
return handleDefined();
case IToken.tLPAREN:
consume();
long r1 = expression();
if (LA() == IToken.tRPAREN) {
consume();
return r1;
}
throw new EvalException(IProblem.SCANNER_MISSING_R_PAREN, null);
case IToken.tIDENTIFIER:
consume();
return 0;
default:
throw new EvalException(IProblem.SCANNER_EXPRESSION_SYNTAX_ERROR, null);
}
}
private long handleDefined() throws EvalException {
boolean parenthesis= false;
consume();
if (LA() == IToken.tLPAREN) {
parenthesis= true;
consume();
}
if (LA() != IToken.tIDENTIFIER) {
throw new EvalException(IProblem.SCANNER_ILLEGAL_IDENTIFIER, null);
}
PreprocessorMacro macro= fDictionary.get(fTokens.getCharImage());
if (macro != null) {
fMacrosInDefinedExpressions.add(fLocationMap.encounterDefinedExpression(macro, fTokens.getOffset(), fTokens.getEndOffset()));
}
int result= macro != null ? 1 : 0;
consume();
if (parenthesis) {
if (LA() != IToken.tRPAREN) {
throw new EvalException(IProblem.SCANNER_MISSING_R_PAREN, null);
}
consume();
}
return result;
}
private int LA() {
return fTokens.getType();
}
private void consume() {
fTokens= (Token) fTokens.getNext();
if (fTokens == null) {
fTokens= new Token(IToken.tEND_OF_INPUT, null, 0, 0);
}
}
long getValue(Token t) throws EvalException {
switch(t.getType()) {
case IToken.tCHAR:
return getChar(t.getCharImage(), 1);
case IToken.tLCHAR:
return getChar(t.getCharImage(), 2);
case IToken.tINTEGER:
return getNumber(t.getCharImage());
}
assert false;
return 1;
}
private long getNumber(char[] image) throws EvalException {
boolean isHex = false;
boolean isOctal = false;
int pos= 0;
if (image.length > 1) {
if (image[0] == '0') {
switch (image[++pos]) {
case 'x':
case 'X':
isHex = true;
++pos;
break;
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
isOctal = true;
++pos;
break;
}
}
}
if (isHex) {
return getNumber(image, 2, image.length, 16, IProblem.SCANNER_BAD_HEX_FORMAT);
}
if (isOctal) {
return getNumber(image, 1, image.length, 8, IProblem.SCANNER_BAD_OCTAL_FORMAT);
}
return getNumber(image, 0, image.length, 10, IProblem.SCANNER_BAD_DECIMAL_FORMAT);
}
private long getChar(char[] tokenImage, int i) throws EvalException {
if (i>=tokenImage.length) {
throw new EvalException(IProblem.SCANNER_BAD_CHARACTER, tokenImage);
}
final char c= tokenImage[i];
if (c != '\\') {
return c;
}
if (++i>=tokenImage.length) {
throw new EvalException(IProblem.SCANNER_BAD_CHARACTER, tokenImage);
}
final char d= tokenImage[i];
switch(d) {
case '\\': case '"': case '\'':
return d;
case 'a': return 7;
case 'b': return '\b';
case 'f': return '\f';
case 'n': return '\n';
case 'r': return '\r';
case 't': return '\t';
case 'v': return 0xb;
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7':
return getNumber(tokenImage, i+1, tokenImage.length-1, 8, IProblem.SCANNER_BAD_OCTAL_FORMAT);
case 'x': case 'u': case 'U':
return getNumber(tokenImage, i+1, tokenImage.length-1, 16, IProblem.SCANNER_BAD_HEX_FORMAT);
default:
throw new EvalException(IProblem.SCANNER_BAD_CHARACTER, tokenImage);
}
}
private long getNumber(char[] tokenImage, int from, int to, int base, int problemID) throws EvalException {
if (from == to) {
throw new EvalException(problemID, tokenImage);
}
long result= 0;
int i= from;
for (; i < to; i++) {
int digit= getDigit(tokenImage[i]);
if (digit >= base) {
break;
}
result= result*base + digit;
}
for (; i < to; i++) {
switch(tokenImage[i]) {
case 'u' : case 'l': case 'U': case 'L':
break;
default:
throw new EvalException(problemID, tokenImage);
}
}
return result;
}
private int getDigit(char c) {
switch(c) {
case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
return c-'0';
case 'a': case 'b': case 'c': case 'd': case 'e': case 'f':
return c-'a' + 10;
case 'A': case 'B': case 'C': case 'D': case 'E': case 'F':
return c-'A'+10;
}
return Integer.MAX_VALUE;
}
}
| true | true | private long unaryExpression() throws EvalException {
switch (LA()) {
case IToken.tPLUS:
consume();
return unaryExpression();
case IToken.tMINUS:
consume();
return -unaryExpression();
case IToken.tNOT:
consume();
return unaryExpression() == 0 ? 1 : 0;
case IToken.tBITCOMPLEMENT:
consume();
return ~unaryExpression();
case IToken.tCHAR:
case IToken.tLCHAR:
case IToken.tINTEGER:
long val= getValue(fTokens);
consume();
return val;
case CPreprocessor.tDEFINED:
return handleDefined();
case IToken.tLPAREN:
consume();
long r1 = expression();
if (LA() == IToken.tRPAREN) {
consume();
return r1;
}
throw new EvalException(IProblem.SCANNER_MISSING_R_PAREN, null);
case IToken.tIDENTIFIER:
consume();
return 0;
default:
throw new EvalException(IProblem.SCANNER_EXPRESSION_SYNTAX_ERROR, null);
}
}
| private long unaryExpression() throws EvalException {
switch (LA()) {
case IToken.tPLUS:
consume();
return unaryExpression();
case IToken.tMINUS:
consume();
return -unaryExpression();
case IToken.tNOT:
consume();
return unaryExpression() == 0 ? 1 : 0;
case IToken.tBITCOMPLEMENT:
consume();
return ~unaryExpression();
case IToken.tCHAR:
case IToken.tLCHAR:
case IToken.tINTEGER:
long val= getValue(fTokens);
consume();
return val;
case IToken.t_true:
consume();
return 1;
case IToken.t_false:
consume();
return 0;
case CPreprocessor.tDEFINED:
return handleDefined();
case IToken.tLPAREN:
consume();
long r1 = expression();
if (LA() == IToken.tRPAREN) {
consume();
return r1;
}
throw new EvalException(IProblem.SCANNER_MISSING_R_PAREN, null);
case IToken.tIDENTIFIER:
consume();
return 0;
default:
throw new EvalException(IProblem.SCANNER_EXPRESSION_SYNTAX_ERROR, null);
}
}
|
diff --git a/src/soot/toolkits/graph/ExceptionalUnitGraph.java b/src/soot/toolkits/graph/ExceptionalUnitGraph.java
index eba67db1..ec8a2d8f 100644
--- a/src/soot/toolkits/graph/ExceptionalUnitGraph.java
+++ b/src/soot/toolkits/graph/ExceptionalUnitGraph.java
@@ -1,854 +1,855 @@
/* Soot - a J*va Optimization Framework
* Copyright (C) 1999 Patrice Pominville, Raja Vallee-Rai
*
* 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.
*/
/*
* Modified by the Sable Research Group and others 1997-2004.
* See the 'credits' file distributed with Soot for the complete list of
* contributors. (Soot is distributed at http://www.sable.mcgill.ca/soot)
*/
package soot.toolkits.graph;
import soot.*;
import soot.util.*;
import java.util.*;
import soot.options.Options;
import soot.toolkits.exceptions.ThrowAnalysis;
import soot.toolkits.exceptions.UnitThrowAnalysis;
import soot.toolkits.exceptions.ThrowableSet;
import soot.baf.Inst;
import soot.baf.NewInst;
import soot.baf.StaticPutInst;
import soot.baf.StaticGetInst;
import soot.baf.ThrowInst;
import soot.jimple.Stmt;
import soot.jimple.ThrowStmt;
import soot.jimple.StaticFieldRef;
import soot.jimple.InvokeExpr;
import soot.jimple.NewExpr;
/**
* <p>Represents a CFG for a {@link Body} instance where the nodes are
* {@link Unit} instances, and where control flow associated with
* exceptions is taken into account.</p>
*
* <p>For every <tt>Unit</tt> which
* may throw an exception that could be caught by a {@link Trap} in
* the <tt>Body</tt>, there will be an edge from each of the
* excepting <tt>Unit</tt>'s predecessors to the <tt>Trap</tt>
* handler's first <tt>Unit</tt> (since any of those predecessors may have
* been the last <tt>Unit</tt> to complete execution before the
* handler). If the excepting <tt>Unit</tt> might have the side
* effect of changing some fields, then there will be an edge from
* the excepting <tt>Unit</tt> itself to its handlers, since the
* side effects might occur before the exception is raised. If the
* excepting <tt>Unit</tt> has no side effects, then parameters passed
* to the <tt>ExceptionalUnitGraph</tt> constructor determine whether
* or not there is an edge from the excepting <tt>Unit</tt> itself to
* the handler <tt>Unit</tt>.</p>
*/
public class ExceptionalUnitGraph extends UnitGraph
{
protected Map unitToUnexceptionalSuccs; // If there are no Traps within
protected Map unitToUnexceptionalPreds; // the method, these will be the
// same maps as unitToSuccs and
// unitToPreds.
protected Map unitToExceptionalSuccs; // These will be null if
protected Map unitToExceptionalPreds; // there are no Traps within
protected Map unitToExceptionDests; // the method,
protected ThrowAnalysis throwAnalysis; // This will be null unless there
// are no Traps within the
// method, in which case we
// keep the throwAnalysis around
// for getExceptionDests().
/**
* Constructs the graph from a given Body instance.
*
* @param body the <tt>Body</tt> from which to build a graph.
*
* @param throwAnalysis the source of information about the exceptions
* which each {@link Unit} may throw.
*
* @param omitExceptingUnitEdges indicates whether the CFG should
* omit edges to a handler from trapped
* <tt>Unit</tt>s which may throw an
* exception which the handler catches but
* which have no potential side effects.
* The CFG will contain edges to the handler
* from all predecessors of the
* <tt>Unit</tt>s which may throw a caught
* exception regardless of the setting for
* this parameter. If this parameter is
* <code>false</code>, there will also be
* edges to the handler from all the
* potentially excepting <tt>Unit</tt>s
* themselves. If this parameter is
* <code>true</code>, there will be edges to
* the handler from the excepting
* <tt>Unit</tt>s themselves only if they
* have potential side effects (or if they
* are themselves the predecessors of other
* potentially excepting <tt>Unit</tt>s).
* A setting of <code>true</code> produces
* CFGs which allow for more precise
* analyses, since a <tt>Unit</tt> without
* side effects has no effect on the
* computational state when it throws an
* exception. Use settings of
* <code>false</code> for compatibility with
* more conservative analyses, or to cater
* to conservative bytecode verifiers.
*/
public ExceptionalUnitGraph(Body body, ThrowAnalysis throwAnalysis,
boolean omitExceptingUnitEdges) {
super(body);
int size = unitChain.size();
Set trapsThatAreHeads = Collections.EMPTY_SET;
if(Options.v().time())
Timers.v().graphTimer.start();
unitToUnexceptionalSuccs = new HashMap(size * 2 + 1, 0.7f);
unitToUnexceptionalPreds = new HashMap(size * 2 + 1, 0.7f);
buildUnexceptionalEdges(unitToUnexceptionalSuccs,
unitToUnexceptionalPreds);
makeMappedListsUnmodifiable(unitToUnexceptionalSuccs);
makeMappedListsUnmodifiable(unitToUnexceptionalPreds);
if (body.getTraps().size() == 0) {
// No handlers, so all exceptional control flow exits the
// method.
unitToExceptionalSuccs = null;
unitToExceptionalPreds = null;
unitToSuccs = unitToUnexceptionalSuccs;
unitToPreds = unitToUnexceptionalPreds;
this.throwAnalysis = throwAnalysis; // Keep the throwAnalysis,
// for generating ThrowableSets
// on the fly.
} else {
unitToExceptionDests = buildExceptionDests(throwAnalysis);
unitToExceptionalSuccs =
new HashMap(unitToExceptionDests.size() * 2 + 1, 0.7f);
unitToExceptionalPreds =
new HashMap(body.getTraps().size() * 2 + 1, 0.7f);
trapsThatAreHeads = buildExceptionalEdges(unitToExceptionDests,
unitToExceptionalSuccs,
unitToExceptionalPreds,
omitExceptingUnitEdges);
makeMappedListsUnmodifiable(unitToExceptionalSuccs);
makeMappedListsUnmodifiable(unitToExceptionalPreds);
// We'll need separate maps for the combined
// exceptional and unexceptional edges:
unitToSuccs = combineMapValues(unitToUnexceptionalSuccs,
unitToExceptionalSuccs);
unitToPreds = combineMapValues(unitToUnexceptionalPreds,
unitToExceptionalPreds);
this.throwAnalysis = null; // We won't need throwAnalysis
// anymore, so don't save a reference
// that might keep its object live.
}
buildHeadsAndTails(trapsThatAreHeads);
if(Options.v().time())
Timers.v().graphTimer.end();
if (DEBUG)
soot.util.PhaseDumper.v().dumpGraph(this);
}
/**
* Constructs the graph from a given Body instance. This
* constructor variant uses a default value, provided by the
* {@link Options} class, for the
* <code>omitExceptingUnitEdges</code> parameter.
*
* @param body the {@link Body} from which to build a graph.
*
* @param throwAnalysis the source of information about the exceptions
* which each {@link Unit} may throw.
*
*/
public ExceptionalUnitGraph(Body body, ThrowAnalysis throwAnalysis) {
this(body, throwAnalysis, Options.v().omit_excepting_unit_edges());
}
/**
* Constructs the graph from a given Body instance, using the
* {@link Scene}'s default {@link ThrowAnalysis} to estimate the
* set of exceptions that each {@link Unit} might throw and a
* default value, provided by the {@link Options} class, for the
* <code>omitExceptingUnitEdges</code> parameter.
*
* @param body the <tt>Body</tt> from which to build a graph.
*
*/
public ExceptionalUnitGraph(Body body) {
this(body, Scene.v().getDefaultThrowAnalysis(),
Options.v().omit_excepting_unit_edges());
}
/**
* Utility method used in the construction of {@link UnitGraph}
* variants which include exceptional control flow. It determines
* the possible exceptions which each <tt>Unit</tt> might throw
* and the set of traps which might catch those exceptions.
*
* @param throwAnalysis The source of information about which
* exceptions each <tt>Unit</tt> may throw.
*
* @return A {@link Map} from <tt>Unit</tt>s to {@link Collection}s of
* {@link ExceptionDest}s. Each <tt>ExceptionDest</tt> associated
* with a <tt>Unit</tt> includes a {@link ThrowableSet} specifying
* exceptions that the <tt>Unit</tt> might throw and a
* {@link Trap} specifying the handler which catches those exceptions
* (if the <tt>Trap</tt> is <tt>null</tt>, those exceptions
* escape the method without being caught).
*/
protected Map buildExceptionDests(ThrowAnalysis throwAnalysis) {
// To add possible exception edges, we need to keep
// track of which traps are active as we iterate
// through the units of the body, and we need to check
// exceptions against active traps in the proper
// order, to ensure we choose the correct active trap
// when more than one of them can catch a particular
// exception type. Hence the trapTable array.
class TrapRecord {
Trap trap;
RefType caughtType;
boolean active;
TrapRecord(Trap trap, RefType caughtType) {
this.trap = trap;
this.caughtType = caughtType;
active = false;
}
}
TrapRecord[] trapTable = new TrapRecord[body.getTraps().size()];
int trapIndex = 0;
for (Iterator trapIt = body.getTraps().iterator();
trapIt.hasNext(); trapIndex++) {
Trap trap = (Trap) trapIt.next();
trapTable[trapIndex] = new TrapRecord(trap,
RefType.v(trap.getException()));
}
Map unitToExceptionDests = new HashMap(unitChain.size() * 2 + 1, 0.7f);
FastHierarchy hier = Scene.v().getOrMakeFastHierarchy();
// Encode the possible destinations of each Unit's
// exceptions in ExceptionDest objects.
for (Iterator unitIt = unitChain.iterator(); unitIt.hasNext(); ) {
Unit u = (Unit) unitIt.next();
// First, update the set of traps active for this Unit.
for (int i = 0; i < trapTable.length; i++) {
// Be sure to turn on traps before turning them off, so
// that degenerate traps where getBeginUnit() == getEndUnit()
// are never active. Obviously, I learned this the hard way!
if (trapTable[i].trap.getBeginUnit() == u) {
trapTable[i].active = true;
}
if (trapTable[i].trap.getEndUnit() == u) {
trapTable[i].active = false;
}
}
UnitDestsMap unitDests = new UnitDestsMap();
ThrowableSet thrownSet = throwAnalysis.mightThrow(u);
nextThrowable:
for (Iterator i = thrownSet.types().iterator(); i.hasNext(); ) {
RefLikeType thrown = (RefLikeType)i.next();
if (thrown instanceof RefType) {
RefType thrownType = (RefType)thrown;
for (int j = 0; j < trapTable.length; j++) {
if (trapTable[j].active) {
Trap trap = trapTable[j].trap;
RefType caughtType = trapTable[j].caughtType;
if (hier.canStoreType(thrownType, caughtType)) {
unitDests.add(trap, thrownType);
continue nextThrowable;
}
}
}
// If we get here, thrownType escapes the method.
unitDests.add(null, thrownType);
} else if (thrown instanceof AnySubType) {
AnySubType thrownType = (AnySubType) thrown;
RefType thrownBase = thrownType.getBase();
List alreadyCaught = new ArrayList();
// alreadyCaught serves to screen a special case
// (which is probably not worth screening) best
// illustrated with a concrete example: imagine
// that thrownBase is AnySubType(RuntimeException)
// and that we have two Traps, the first of
// which catches IndexOutOfBoundsException while
// the second catches ArrayIndexOutOfBounds-
// Exception. We use alreadyCaught to detect that
// the second Trap will never catch anything.
// (javac would warn you that the catch block is dead,
// but arbitrary bytecode could still include such
// dead handlers.)
for (int j = 0; j < trapTable.length; j++) {
if (trapTable[j].active) {
Trap trap = trapTable[j].trap;
RefType caughtType = trapTable[j].caughtType;
if (hier.canStoreType(thrownBase, caughtType)) {
// This trap catches all the types
// thrownType can represent.
unitDests.add(trap, AnySubType.v(thrownBase));
continue nextThrowable;
} else if (hier.canStoreType(caughtType, thrownBase)) {
// This trap catches some of the
// types thrownType can represent,
// unless it is being screened by a
// previous trap whose catch parameter
// is a supertype of this one's.
for (Iterator k = alreadyCaught.iterator();
k.hasNext(); ) {
RefType alreadyType = (RefType)k.next();
if (hier.canStoreType(caughtType, alreadyType)) {
continue nextThrowable;
}
}
unitDests.add(trap, AnySubType.v(caughtType));
alreadyCaught.add(caughtType);
// Do NOT continue to the nextThrowable,
// since the remaining traps might catch
// other subtypes of this thrownBase.
}
}
}
// At least some subtypes escape the method.
// We really should subtract any already caught
// subtypes from the representation of escaping
// exceptions, but there's no easy way to do so.
unitDests.add(null, thrownType);
} else {
// assertion failure.
throw new RuntimeException("UnitGraph(): ThrowableSet element " +
thrown.toString() +
" is neither a RefType nor an AnySubType.");
}
}
unitToExceptionDests.put(u, unitDests.values());
}
return unitToExceptionDests;
}
/** A utility class used to build the list of ExceptionDests for a
* given unit. It maps from
* {@link Trap}s to {@link ThrowableSet}s representing the exceptions
* thrown by the unit under consideration that are caught by that trap.
*/
private static class UnitDestsMap extends HashMap {
// We use leavesMethod in the unitDests map to represent the
// destination of exceptions which are not caught by any
// trap in the method. We can't use null, because it
// doesn't have a hashCode(). It is perhaps bad form to use
// Collections.EMPTY_LIST as the placeholder, but it is
// already used elsewhere in UnitGraph, and using EMPTY_LIST
// saves us from creating a dummy Trap that we would need to
// add to Singletons.
final static Object leavesMethod = Collections.EMPTY_LIST;
private ExceptionDest getDest(Trap trap) {
Object key = trap;
if (key == null) {
key = leavesMethod;
}
ExceptionDest dest = (ExceptionDest)this.get(key);
if (dest == null) {
dest = new ExceptionDest(trap, ThrowableSet.Manager.v().EMPTY);
this.put(key, dest);
}
return dest;
}
void add(Trap trap, RefType throwable) {
ExceptionDest dest = this.getDest(trap);
dest.throwables = dest.throwables.add(throwable);
}
void add(Trap trap, AnySubType throwable) {
ExceptionDest dest = this.getDest(trap);
dest.throwables = dest.throwables.add(throwable);
}
}
/**
* Method to compute the edges corresponding to exceptional
* control flow.
*
* @param unitToDests A <tt>Map</tt> from {@link Unit}s to
* {@link Collection}s of {@link ExceptionalUnitGraph.ExceptionDest ExceptionDest}s
* which represent the handlers that might catch
* exceptions thrown by the <tt>Unit</tt>. This is
* an ``in parameter''.
*
* @param unitToSuccs A <tt>Map</tt> from <tt>Unit</tt>s to
* {@link List}s of <tt>Unit</tt>s. This is an
* ``out parameter'';
* <tt>buildExceptionalEdges</tt> will add a
* mapping from every <tt>Unit</tt> in the body
* that may throw an exception that could be
* caught by a {@link Trap} in the body to a
* list of its exceptional successors.
*
* @param unitToPreds A <tt>Map</tt> from <tt>Unit</tt>s to
* <tt>List</tt>s of <tt>Unit</tt>s. This is an
* ``out parameter'';
* <tt>buildExceptionalEdges</tt> will add a
* mapping from each handler unit that may
* catch an exception to the list of
* <tt>Unit</tt>s whose exceptions it may
* catch.
* @param omitExceptingUnitEdges Indicates whether to omit
* exceptional edges from excepting units which
* lack side effects
*
* @return a {@link Set} of trap <tt>Unit</tt>s that might catch
* exceptions thrown by the first <tt>Unit</tt> in the {@link Body}
* associated with the graph being constructed.
* Such trap <tt>Unit</tt>s may need to be added to the
* list of heads (depending on your definition of heads),
* since they can be the first <tt>Unit</tt> in the
* <tt>Body</tt> which actually completes execution.
*/
protected Set buildExceptionalEdges(Map unitToDests,
Map unitToSuccs, Map unitToPreds,
boolean omitExceptingUnitEdges) {
Set trapsThatAreHeads = new ArraySet();
+ Unit entryPoint = (Unit) unitChain.getFirst();
// Add exceptional edges from each predecessor of units that
// throw exceptions to the handler that catches them. Add an
// additional edge from the thrower itself to the catcher if
// the thrower may have side effects.
for (Iterator it = unitToDests.entrySet().iterator();
it.hasNext(); ) {
Map.Entry entry = (Map.Entry) it.next();
Unit thrower = (Unit) entry.getKey();
Collection dests = (Collection) entry.getValue();
for (Iterator destIt = dests.iterator(); destIt.hasNext(); ) {
ExceptionDest dest = (ExceptionDest) destIt.next();
if (dest.trap() != null) {
Unit catcher = dest.trap().getHandlerUnit();
List throwersPreds = getUnexceptionalPredsOf(thrower);
- if (throwersPreds.size() == 0) {
+ if (thrower == entryPoint) {
trapsThatAreHeads.add(catcher);
} else {
for (Iterator j = throwersPreds.iterator();
j.hasNext(); ) {
Unit pred = (Unit) j.next();
addEdge(unitToSuccs, unitToPreds, pred, catcher);
}
}
if ((! omitExceptingUnitEdges) ||
thrower instanceof ThrowInst ||
thrower instanceof ThrowStmt ||
mightHaveSideEffects(thrower)) {
// An athrow instruction actually completes when
// it throws its argument exception, so we
// need to include an edge from it to avoid
// the throw being removed by dead code
// elimination.
addEdge(unitToSuccs, unitToPreds, thrower, catcher);
}
}
}
}
// Now we have to worry about transitive exceptional
// edges, when a handler might itself throw an exception
// that is caught within the method. For that we need a
// worklist containing CFG edges that lead to such a handler.
class CFGEdge {
Unit head; // If null, represents an edge to the handler
// from the fictitious "predecessor" of the
// very first unit in the chain. I.e., tail
// is a handler which might be reached as a
// result of an exception thrown by the
// first Unit in the Body.
Unit tail;
CFGEdge(Unit head, Unit tail) {
if (tail == null)
throw new RuntimeException("invalid CFGEdge("
+ head.toString() + ','
+ tail.toString() + ')');
this.head = head;
this.tail = tail;
}
public boolean equals(Object rhs) {
if (rhs == this) {
return true;
}
if (! (rhs instanceof CFGEdge)) {
return false;
}
CFGEdge rhsEdge = (CFGEdge) rhs;
return ((this.head == rhsEdge.head) &&
(this.tail == rhsEdge.tail));
}
public int hashCode() {
// Following Joshua Bloch's recipe in "Effective Java", Item 8:
int result = 17;
result = 37 * result + this.head.hashCode();
result = 37 * result + this.tail.hashCode();
return result;
}
}
LinkedList workList = new LinkedList();
for (Iterator trapIt = body.getTraps().iterator(); trapIt.hasNext(); ) {
Trap trap = (Trap) trapIt.next();
Unit handlerStart = trap.getHandlerUnit();
if (mightThrowToIntraproceduralCatcher(handlerStart)) {
List handlerPreds = getUnexceptionalPredsOf(handlerStart);
for (Iterator it = handlerPreds.iterator(); it.hasNext(); ) {
Unit pred = (Unit) it.next();
workList.addLast(new CFGEdge(pred, handlerStart));
}
handlerPreds = getExceptionalPredsOf(handlerStart);
for (Iterator it = handlerPreds.iterator(); it.hasNext(); ) {
Unit pred = (Unit) it.next();
workList.addLast(new CFGEdge(pred, handlerStart));
}
if (trapsThatAreHeads.contains(handlerStart)) {
workList.addLast(new CFGEdge(null, handlerStart));
}
}
}
// Now for every CFG edge that leads to a handler that may
// itself throw an exception catchable within the method, add
// edges from the head of that edge to the unit that catches
// the handler's exception.
while (workList.size() > 0) {
CFGEdge edgeToThrower = (CFGEdge) workList.removeFirst();
Unit pred = edgeToThrower.head;
Unit thrower = edgeToThrower.tail;
Collection throwerDests = getExceptionDests(thrower);
for (Iterator i = throwerDests.iterator(); i.hasNext(); ) {
ExceptionDest dest = (ExceptionDest) i.next();
if (dest.trap() != null) {
Unit handlerStart = dest.trap().getHandlerUnit();
boolean edgeAdded = false;
if (pred == null) {
if (! trapsThatAreHeads.contains(handlerStart)) {
trapsThatAreHeads.add(handlerStart);
edgeAdded = true;
}
} else {
if (! getExceptionalSuccsOf(pred).contains(handlerStart)) {
addEdge(unitToSuccs, unitToPreds, pred, handlerStart);
edgeAdded = true;
}
}
if (edgeAdded &&
mightThrowToIntraproceduralCatcher(handlerStart)) {
workList.addLast(new CFGEdge(pred, handlerStart));
}
}
}
}
return trapsThatAreHeads;
}
/**
* <p>Utility method for checking if a {@link Unit} might have side
* effects. It simply returns true for any unit which invokes a
* method directly or which might invoke static initializers
* indirectly (by creating a new object or by refering to a static
* field; see sections 2.17.4, 2.17.5, and 5.5 of the Java Virtual
* Machine Specification).</p>
*
* <tt>mightHaveSideEffects()</tt> is declared package-private so that
* it is available to unit tests that are part of this package.
*
* @param u The unit whose potential for side effects is to be checked.
*
* @return whether or not <code>u</code> has the potential for side effects.
*/
static boolean mightHaveSideEffects(Unit u) {
if (u instanceof Inst) {
Inst i = (Inst) u;
return (i.containsInvokeExpr() ||
(i instanceof StaticPutInst) ||
(i instanceof StaticGetInst) ||
(i instanceof NewInst));
} else if (u instanceof Stmt) {
for (Iterator it = u.getUseBoxes().iterator(); it.hasNext(); ) {
Value v = ((ValueBox)(it.next())).getValue();
if ((v instanceof StaticFieldRef) ||
(v instanceof InvokeExpr) ||
(v instanceof NewExpr)) {
return true;
}
}
}
return false;
}
/**
* Utility method for checking if a Unit might throw an exception which
* may be caught by a {@link Trap} within this method.
*
* @param u The unit for whose exceptions are to be checked
*
* @return whether or not <code>u</code> may throw an exception which may be
* caught by a <tt>Trap</tt> in this method,
*/
private boolean mightThrowToIntraproceduralCatcher(Unit u) {
Collection dests = getExceptionDests(u);
for (Iterator i = dests.iterator(); i.hasNext(); ) {
ExceptionDest dest = (ExceptionDest) i.next();
if (dest.trap() != null) {
return true;
}
}
return false;
}
/**
* Utility method, to be called only after the unitToPreds and
* unitToSuccs maps have been built. It defines the graph's set of
* heads to include the first {@link Unit} in the graph's body,
* together with all the <tt>Unit</tt>s in
* <tt>additionalHeads</tt>. It defines the graph's set of tails
* to include all <tt>Unit</tt>s which represent some sort of
* return bytecode or an athrow bytecode which may escape the method.
*/
private void buildHeadsAndTails(Set additionalHeads) {
List headList = new ArrayList(additionalHeads.size() + 1);
headList.addAll(additionalHeads);
Unit entryPoint = (Unit) unitChain.getFirst();
if (! headList.contains(entryPoint)) {
headList.add(entryPoint);
}
List tailList = new ArrayList();
for (Iterator it = unitChain.iterator(); it.hasNext(); ) {
Unit u = (Unit) it.next();
if (u instanceof soot.jimple.ReturnStmt ||
u instanceof soot.jimple.ReturnVoidStmt ||
u instanceof soot.baf.ReturnInst ||
u instanceof soot.baf.ReturnVoidInst) {
tailList.add(u);
} else if (u instanceof soot.jimple.ThrowStmt ||
u instanceof soot.baf.ThrowInst) {
Collection dests = getExceptionDests(u);
int escapeMethodCount = 0;
for (Iterator destIt = dests.iterator(); destIt.hasNext(); ) {
ExceptionDest dest = (ExceptionDest) destIt.next();
if (dest.trap() == null) {
escapeMethodCount++;
}
}
if (escapeMethodCount > 0) {
tailList.add(u);
}
}
}
tails = Collections.unmodifiableList(tailList);
heads = Collections.unmodifiableList(headList);
}
/**
* Returns a collection of
* {@link ExceptionalUnitGraph.ExceptionDest ExceptionDest}
* objects which represent how exceptions thrown by a specified
* unit will be handled.
*
* @param u The unit for which to provide exception information.
*
* @return a collection of <tt>ExceptionDest</tt> objects describing
* the traps, if any, which catch the exceptions
* which may be thrown by <CODE>u</CODE>.
*/
public Collection getExceptionDests(Unit u) {
Collection result = null;
if (unitToExceptionDests == null) {
// There are no traps in the method; all exceptions
// that the unit throws will escape the method.
result = new LinkedList();
result.add(new ExceptionDest(null, throwAnalysis.mightThrow(u)));
} else {
result = (Collection) unitToExceptionDests.get(u);
if(result == null)
throw new RuntimeException("Invalid unit " + u);
}
return result;
}
/**
* <p>Data structure to represent the fact that
* a given {@link Trap} will catch some subset of the exceptions
* which may be thrown by a given {@link Unit}.</p>
*
* <p>Note that these ``destinations'' are different from the
* edges in the CFG proper which are returned by
* <tt>getSuccsOf()</tt> and <tt>getPredsOf()</tt>. An edge from
* <CODE>a</CODE> to <CODE>b</CODE>) in the CFG represents the
* fact that after unit <CODE>a</CODE> executes (perhaps only
* partially, if it throws an exception after possibly producing a
* side effect), execution may proceed to unit <CODE>b</CODE>. An
* ExceptionDest from <CODE>a</CODE> to <CODE>b</CODE>, on the
* other hand, says that when <CODE>a</CODE> fails to complete at
* all, execution may proceed to unit <CODE>b</CODE> instead.</p>
*/
public static class ExceptionDest {
private Trap trap;
private ThrowableSet throwables;
protected ExceptionDest(Trap trap, ThrowableSet throwables) {
this.trap = trap;
this.throwables = throwables;
}
/**
* Returns the trap corresponding to this destination.
*
* @return either a {@link Trap} representing the handler that
* catches the exceptions, if there is such a handler within
* the method, or <CODE>null</CODE> if there is no such
* handler and the exceptions cause the method to terminate
* abruptly.
*/
public Trap trap() {
return trap;
}
/**
* Returns the exceptions thrown to this destination.
*
* @return a {@link ThrowableSet} representing
* the exceptions which may be caught by this {@link ExceptionalUnitGraph.ExceptionDest ExceptionDest}'s
* trap.
*/
public ThrowableSet throwables() {
return throwables;
}
/**
* Returns a string representation of this destination.
*
* @return a {@link String} representing this destination.
*/
public String toString() {
StringBuffer buf = new StringBuffer();
buf.append(throwables.toString());
buf.append(" -> ");
if (trap == null) {
buf.append("(escapes)");
} else {
buf.append(trap.toString());
}
return buf.toString();
}
}
public List getUnexceptionalPredsOf(Unit u) {
if (!unitToUnexceptionalPreds.containsKey(u))
throw new RuntimeException("Invalid unit " + u);
return (List) unitToUnexceptionalPreds.get(u);
}
public List getUnexceptionalSuccsOf(Unit u) {
if (!unitToUnexceptionalSuccs.containsKey(u))
throw new RuntimeException("Invalid unit " + u);
return (List) unitToUnexceptionalSuccs.get(u);
}
public List getExceptionalPredsOf(Unit u) {
if (unitToExceptionalPreds == null ||
(!unitToExceptionalPreds.containsKey(u))) {
return Collections.EMPTY_LIST;
} else {
return (List) unitToExceptionalPreds.get(u);
}
}
public List getExceptionalSuccsOf(Unit u) {
if (unitToExceptionalSuccs == null ||
(!unitToExceptionalSuccs.containsKey(u))) {
return Collections.EMPTY_LIST;
} else {
return (List) unitToExceptionalSuccs.get(u);
}
}
public String toString() {
Iterator it = unitChain.iterator();
StringBuffer buf = new StringBuffer();
while(it.hasNext()) {
Unit u = (Unit) it.next();
buf.append("// preds: "+getPredsOf(u)+"\n");
buf.append("// unexceptional preds: "+getUnexceptionalPredsOf(u)+"\n");
buf.append("// exceptional preds: "+getExceptionalPredsOf(u)+"\n");
buf.append(u.toString() + '\n');
buf.append("// exception destinations: "+getExceptionDests(u)+"\n");
buf.append("// unexceptional succs: "+getUnexceptionalPredsOf(u)+"\n");
buf.append("// exceptional succs: "+getExceptionalPredsOf(u)+"\n");
buf.append("// succs "+getSuccsOf(u)+"\n");
}
return buf.toString();
}
}
| false | true | protected Set buildExceptionalEdges(Map unitToDests,
Map unitToSuccs, Map unitToPreds,
boolean omitExceptingUnitEdges) {
Set trapsThatAreHeads = new ArraySet();
// Add exceptional edges from each predecessor of units that
// throw exceptions to the handler that catches them. Add an
// additional edge from the thrower itself to the catcher if
// the thrower may have side effects.
for (Iterator it = unitToDests.entrySet().iterator();
it.hasNext(); ) {
Map.Entry entry = (Map.Entry) it.next();
Unit thrower = (Unit) entry.getKey();
Collection dests = (Collection) entry.getValue();
for (Iterator destIt = dests.iterator(); destIt.hasNext(); ) {
ExceptionDest dest = (ExceptionDest) destIt.next();
if (dest.trap() != null) {
Unit catcher = dest.trap().getHandlerUnit();
List throwersPreds = getUnexceptionalPredsOf(thrower);
if (throwersPreds.size() == 0) {
trapsThatAreHeads.add(catcher);
} else {
for (Iterator j = throwersPreds.iterator();
j.hasNext(); ) {
Unit pred = (Unit) j.next();
addEdge(unitToSuccs, unitToPreds, pred, catcher);
}
}
if ((! omitExceptingUnitEdges) ||
thrower instanceof ThrowInst ||
thrower instanceof ThrowStmt ||
mightHaveSideEffects(thrower)) {
// An athrow instruction actually completes when
// it throws its argument exception, so we
// need to include an edge from it to avoid
// the throw being removed by dead code
// elimination.
addEdge(unitToSuccs, unitToPreds, thrower, catcher);
}
}
}
}
// Now we have to worry about transitive exceptional
// edges, when a handler might itself throw an exception
// that is caught within the method. For that we need a
// worklist containing CFG edges that lead to such a handler.
class CFGEdge {
Unit head; // If null, represents an edge to the handler
// from the fictitious "predecessor" of the
// very first unit in the chain. I.e., tail
// is a handler which might be reached as a
// result of an exception thrown by the
// first Unit in the Body.
Unit tail;
CFGEdge(Unit head, Unit tail) {
if (tail == null)
throw new RuntimeException("invalid CFGEdge("
+ head.toString() + ','
+ tail.toString() + ')');
this.head = head;
this.tail = tail;
}
public boolean equals(Object rhs) {
if (rhs == this) {
return true;
}
if (! (rhs instanceof CFGEdge)) {
return false;
}
CFGEdge rhsEdge = (CFGEdge) rhs;
return ((this.head == rhsEdge.head) &&
(this.tail == rhsEdge.tail));
}
public int hashCode() {
// Following Joshua Bloch's recipe in "Effective Java", Item 8:
int result = 17;
result = 37 * result + this.head.hashCode();
result = 37 * result + this.tail.hashCode();
return result;
}
}
LinkedList workList = new LinkedList();
for (Iterator trapIt = body.getTraps().iterator(); trapIt.hasNext(); ) {
Trap trap = (Trap) trapIt.next();
Unit handlerStart = trap.getHandlerUnit();
if (mightThrowToIntraproceduralCatcher(handlerStart)) {
List handlerPreds = getUnexceptionalPredsOf(handlerStart);
for (Iterator it = handlerPreds.iterator(); it.hasNext(); ) {
Unit pred = (Unit) it.next();
workList.addLast(new CFGEdge(pred, handlerStart));
}
handlerPreds = getExceptionalPredsOf(handlerStart);
for (Iterator it = handlerPreds.iterator(); it.hasNext(); ) {
Unit pred = (Unit) it.next();
workList.addLast(new CFGEdge(pred, handlerStart));
}
if (trapsThatAreHeads.contains(handlerStart)) {
workList.addLast(new CFGEdge(null, handlerStart));
}
}
}
// Now for every CFG edge that leads to a handler that may
// itself throw an exception catchable within the method, add
// edges from the head of that edge to the unit that catches
// the handler's exception.
while (workList.size() > 0) {
CFGEdge edgeToThrower = (CFGEdge) workList.removeFirst();
Unit pred = edgeToThrower.head;
Unit thrower = edgeToThrower.tail;
Collection throwerDests = getExceptionDests(thrower);
for (Iterator i = throwerDests.iterator(); i.hasNext(); ) {
ExceptionDest dest = (ExceptionDest) i.next();
if (dest.trap() != null) {
Unit handlerStart = dest.trap().getHandlerUnit();
boolean edgeAdded = false;
if (pred == null) {
if (! trapsThatAreHeads.contains(handlerStart)) {
trapsThatAreHeads.add(handlerStart);
edgeAdded = true;
}
} else {
if (! getExceptionalSuccsOf(pred).contains(handlerStart)) {
addEdge(unitToSuccs, unitToPreds, pred, handlerStart);
edgeAdded = true;
}
}
if (edgeAdded &&
mightThrowToIntraproceduralCatcher(handlerStart)) {
workList.addLast(new CFGEdge(pred, handlerStart));
}
}
}
}
return trapsThatAreHeads;
}
| protected Set buildExceptionalEdges(Map unitToDests,
Map unitToSuccs, Map unitToPreds,
boolean omitExceptingUnitEdges) {
Set trapsThatAreHeads = new ArraySet();
Unit entryPoint = (Unit) unitChain.getFirst();
// Add exceptional edges from each predecessor of units that
// throw exceptions to the handler that catches them. Add an
// additional edge from the thrower itself to the catcher if
// the thrower may have side effects.
for (Iterator it = unitToDests.entrySet().iterator();
it.hasNext(); ) {
Map.Entry entry = (Map.Entry) it.next();
Unit thrower = (Unit) entry.getKey();
Collection dests = (Collection) entry.getValue();
for (Iterator destIt = dests.iterator(); destIt.hasNext(); ) {
ExceptionDest dest = (ExceptionDest) destIt.next();
if (dest.trap() != null) {
Unit catcher = dest.trap().getHandlerUnit();
List throwersPreds = getUnexceptionalPredsOf(thrower);
if (thrower == entryPoint) {
trapsThatAreHeads.add(catcher);
} else {
for (Iterator j = throwersPreds.iterator();
j.hasNext(); ) {
Unit pred = (Unit) j.next();
addEdge(unitToSuccs, unitToPreds, pred, catcher);
}
}
if ((! omitExceptingUnitEdges) ||
thrower instanceof ThrowInst ||
thrower instanceof ThrowStmt ||
mightHaveSideEffects(thrower)) {
// An athrow instruction actually completes when
// it throws its argument exception, so we
// need to include an edge from it to avoid
// the throw being removed by dead code
// elimination.
addEdge(unitToSuccs, unitToPreds, thrower, catcher);
}
}
}
}
// Now we have to worry about transitive exceptional
// edges, when a handler might itself throw an exception
// that is caught within the method. For that we need a
// worklist containing CFG edges that lead to such a handler.
class CFGEdge {
Unit head; // If null, represents an edge to the handler
// from the fictitious "predecessor" of the
// very first unit in the chain. I.e., tail
// is a handler which might be reached as a
// result of an exception thrown by the
// first Unit in the Body.
Unit tail;
CFGEdge(Unit head, Unit tail) {
if (tail == null)
throw new RuntimeException("invalid CFGEdge("
+ head.toString() + ','
+ tail.toString() + ')');
this.head = head;
this.tail = tail;
}
public boolean equals(Object rhs) {
if (rhs == this) {
return true;
}
if (! (rhs instanceof CFGEdge)) {
return false;
}
CFGEdge rhsEdge = (CFGEdge) rhs;
return ((this.head == rhsEdge.head) &&
(this.tail == rhsEdge.tail));
}
public int hashCode() {
// Following Joshua Bloch's recipe in "Effective Java", Item 8:
int result = 17;
result = 37 * result + this.head.hashCode();
result = 37 * result + this.tail.hashCode();
return result;
}
}
LinkedList workList = new LinkedList();
for (Iterator trapIt = body.getTraps().iterator(); trapIt.hasNext(); ) {
Trap trap = (Trap) trapIt.next();
Unit handlerStart = trap.getHandlerUnit();
if (mightThrowToIntraproceduralCatcher(handlerStart)) {
List handlerPreds = getUnexceptionalPredsOf(handlerStart);
for (Iterator it = handlerPreds.iterator(); it.hasNext(); ) {
Unit pred = (Unit) it.next();
workList.addLast(new CFGEdge(pred, handlerStart));
}
handlerPreds = getExceptionalPredsOf(handlerStart);
for (Iterator it = handlerPreds.iterator(); it.hasNext(); ) {
Unit pred = (Unit) it.next();
workList.addLast(new CFGEdge(pred, handlerStart));
}
if (trapsThatAreHeads.contains(handlerStart)) {
workList.addLast(new CFGEdge(null, handlerStart));
}
}
}
// Now for every CFG edge that leads to a handler that may
// itself throw an exception catchable within the method, add
// edges from the head of that edge to the unit that catches
// the handler's exception.
while (workList.size() > 0) {
CFGEdge edgeToThrower = (CFGEdge) workList.removeFirst();
Unit pred = edgeToThrower.head;
Unit thrower = edgeToThrower.tail;
Collection throwerDests = getExceptionDests(thrower);
for (Iterator i = throwerDests.iterator(); i.hasNext(); ) {
ExceptionDest dest = (ExceptionDest) i.next();
if (dest.trap() != null) {
Unit handlerStart = dest.trap().getHandlerUnit();
boolean edgeAdded = false;
if (pred == null) {
if (! trapsThatAreHeads.contains(handlerStart)) {
trapsThatAreHeads.add(handlerStart);
edgeAdded = true;
}
} else {
if (! getExceptionalSuccsOf(pred).contains(handlerStart)) {
addEdge(unitToSuccs, unitToPreds, pred, handlerStart);
edgeAdded = true;
}
}
if (edgeAdded &&
mightThrowToIntraproceduralCatcher(handlerStart)) {
workList.addLast(new CFGEdge(pred, handlerStart));
}
}
}
}
return trapsThatAreHeads;
}
|
diff --git a/src/main/java/com/authdb/util/Config.java b/src/main/java/com/authdb/util/Config.java
index eb0a521..917fba2 100644
--- a/src/main/java/com/authdb/util/Config.java
+++ b/src/main/java/com/authdb/util/Config.java
@@ -1,357 +1,357 @@
/**
(C) Copyright 2011 CraftFire <[email protected]>
Contex <[email protected]>, Wulfspider <[email protected]>
This work is licensed under the Creative Commons Attribution-NonCommercial-NoDerivs 3.0 Unported License.
To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-nd/3.0/
or send a letter to Creative Commons, 171 Second Street, Suite 300, San Francisco, California, 94105, USA.
**/
package com.authdb.util;
import java.io.File;
import org.bukkit.util.config.Configuration;
//import com.ensifera.animosity.craftirc.CraftIRC;
public class Config {
public static boolean database_ison, authdb_enabled = true;
public static boolean has_badcharacters;
public static boolean hasForumBoard,capitalization;
public static boolean hasBackpack = false, hasBukkitContrib = false, hasSpout = false, hasBuildr = false;
public static boolean onlineMode = true;
public static boolean database_keepalive;
public static String database_type, database_username,database_password,database_port,database_host,database_database,dbDb;
public static boolean autoupdate_enable,debug_enable,usagestats_enabled,logging_enabled;
public static String language, logformat;
public static String script_name,script_version,script_salt,script_tableprefix;
public static boolean script_updatestatus;
public static String custom_table,custom_userfield,custom_passfield,custom_encryption,custom_emailfield;
public static boolean custom_enabled,custom_autocreate,custom_salt, custom_emailrequired;
public static boolean register_enabled,register_force;
public static String register_delay_length,register_delay_time,register_timeout_length,register_timeout_time,register_show_length,register_show_time;
public static int register_delay,register_timeout,register_show;
public static boolean login_enabled;
public static String login_method,login_tries,login_action,login_delay_length,login_delay_time,login_timeout_length,login_timeout_time,login_show_length,login_show_time;
public static int login_delay,login_timeout,login_show;
public static boolean link_enabled,link_rename;
public static boolean unlink_enabled,unlink_rename;
public static String username_minimum,username_maximum;
public static String password_minimum,password_maximum;
public static boolean session_protect, session_enabled;
public static String session_time,session_thelength,session_start;
public static int session_length;
public static boolean guests_commands,guests_movement,guests_inventory,guests_drop,guests_pickup,guests_health,guests_mobdamage,guests_interact,guests_build,guests_destroy,guests_chat,guests_mobtargeting,guests_pvp;
public static boolean protection_notify, protection_freeze;
public static int protection_notify_delay, protection_freeze_delay;
public static String protection_notify_delay_time, protection_notify_delay_length, protection_freeze_delay_time, protection_freeze_delay_length;
public static String filter_action,filter_username,filter_password,filter_whitelist="";
public static boolean geoip_enabled;
public static boolean CraftIRC_enabled;
public static String CraftIRC_tag,CraftIRC_prefix;
public static boolean CraftIRC_messages_enabled,CraftIRC_messages_welcome_enabled,CraftIRC_messages_register_enabled,CraftIRC_messages_unregister_enabled,CraftIRC_messages_login_enabled,CraftIRC_messages_email_enabled,CraftIRC_messages_username_enabled,CraftIRC_messages_password_enabled,CraftIRC_messages_idle_enabled;
public static String commands_user_register,commands_user_link,commands_user_unlink,commands_user_login,commands_user_logout;
public static String commands_admin_login, commands_admin_logout, commands_admin_reload;
public static String aliases_user_register,aliases_user_link,aliases_user_unlink,aliases_user_login,aliases_user_logout;
public static String aliases_admin_login, aliases_admin_logout, aliases_admin_reload;
public static Configuration template = null;
public Config(String config, String directory, String filename) {
template = new Configuration(new File(directory, filename));
template.load();
if (config.equalsIgnoreCase("basic")) {
language = getConfigString("plugin.language", "English");
autoupdate_enable = getConfigBoolean("plugin.autoupdate", true);
debug_enable = getConfigBoolean("plugin.debugmode", false);
usagestats_enabled = getConfigBoolean("plugin.usagestats", true);
logformat = getConfigString("plugin.logformat", "yyyy-MM-dd");
logging_enabled = getConfigBoolean("plugin.logging", true);
database_type = getConfigString("database.type", "mysql");
database_username = getConfigString("database.username", "root");
database_password = getConfigString("database.password", "");
database_port = getConfigString("database.port", "3306");
database_host = getConfigString("database.host", "localhost");
database_database = getConfigString("database.name", "forum");
database_keepalive = getConfigBoolean("database.keepalive", false);
dbDb = "jdbc:mysql://" + database_host + ":" + database_port + "/" + database_database;
script_name = getConfigString("script.name", "phpbb").toLowerCase();
script_version = getConfigString("script.version", "3.0.8");
script_tableprefix = getConfigString("script.tableprefix", "");
script_updatestatus = getConfigBoolean("script.updatestatus", true);
script_salt = getConfigString("script.salt", "");
} else if (config.equalsIgnoreCase("advanced")) {
custom_enabled = getConfigBoolean("customdb.enabled", false);
custom_autocreate = getConfigBoolean("customdb.autocreate", true);
custom_emailrequired = getConfigBoolean("customdb.emailrequired", false);
custom_table = getConfigString("customdb.table", "authdb_users");
custom_userfield = getConfigString("customdb.userfield", "username");
custom_passfield = getConfigString("customdb.passfield", "password");
custom_emailfield = getConfigString("customdb.emailfield", "email");
custom_encryption = getConfigString("customdb.encryption", "md5").toLowerCase();
register_enabled = getConfigBoolean("register.enabled", true);
register_force = getConfigBoolean("register.force", true);
register_delay_length = Util.split(getConfigString("register.delay", "4 seconds"), " ")[0];
register_delay_time = Util.split(getConfigString("register.delay", "4 seconds"), " ")[1];
register_delay = Util.toTicks(register_delay_time,register_delay_length);
register_show_length = Util.split(getConfigString("register.show", "10 seconds"), " ")[0];
register_show_time = Util.split(getConfigString("register.show", "10 seconds"), " ")[1];
register_show = Util.toSeconds(register_show_time,register_show_length);
register_timeout_length = Util.split(getConfigString("register.timeout", "3 minutes"), " ")[0];
register_timeout_time = Util.split(getConfigString("register.timeout", "3 minutes"), " ")[1];
register_timeout = Util.toTicks(register_timeout_time,register_timeout_length);
login_method = getConfigString("login.method", "prompt");
login_tries = getConfigString("login.tries", "3");
login_action = Util.getAction(getConfigString("filter.action", "kick").toLowerCase());
login_delay_length = Util.split(getConfigString("login.delay", "4 seconds"), " ")[0];
login_delay_time = Util.split(getConfigString("login.delay", "4 seconds"), " ")[1];
login_delay = Util.toTicks(login_delay_time,login_delay_length);
login_show_length = Util.split(getConfigString("login.show", "10 seconds"), " ")[0];
login_show_time = Util.split(getConfigString("login.show", "10 seconds"), " ")[1];
login_show = Util.toSeconds(login_show_time,login_show_length);
login_timeout_length = Util.split(getConfigString("login.timeout", "3 minutes"), " ")[0];
login_timeout_time = Util.split(getConfigString("login.timeout", "3 minutes"), " ")[1];
login_timeout = Util.toTicks(login_timeout_time,login_timeout_length);
link_enabled = getConfigBoolean("link.enabled", true);
link_rename = getConfigBoolean("link.rename", true);
unlink_enabled = getConfigBoolean("unlink.enabled", true);
unlink_rename = getConfigBoolean("unlink.rename", true);
username_minimum = getConfigString("username.minimum", "3");
username_maximum = getConfigString("username.maximum", "16");
password_minimum = getConfigString("password.minimum", "6");
password_maximum = getConfigString("password.maximum", "16");
session_enabled = getConfigBoolean("session.enabled", false);
session_protect = getConfigBoolean("session.protect", true);
session_thelength = Util.split(getConfigString("session.length", "1 hour"), " ")[0];
session_time = Util.split(getConfigString("session.length", "1 hour"), " ")[1];
session_length = Util.toSeconds(session_time,session_thelength);
session_start = Util.checkSessionStart(getConfigString("session.start", "login"));
guests_commands = getConfigBoolean("guest.commands", false);
guests_movement = getConfigBoolean("guest.movement", false);
guests_inventory = getConfigBoolean("guest.inventory", false);
guests_drop = getConfigBoolean("guest.drop", false);
guests_pickup = getConfigBoolean("guest.pickup", false);
guests_health = getConfigBoolean("guest.health", false);
guests_mobdamage = getConfigBoolean("guest.mobdamage", false);
guests_interact = getConfigBoolean("guest.interactions", false);
guests_build = getConfigBoolean("guest.building", false);
guests_destroy = getConfigBoolean("guest.destruction", false);
guests_chat = getConfigBoolean("guest.chat", false);
guests_mobtargeting = getConfigBoolean("guest.mobtargeting", false);
guests_pvp = getConfigBoolean("guest.pvp", false);
protection_freeze = getConfigBoolean("protection.freeze.enabled", true);
protection_freeze_delay_length = Util.split(getConfigString("protection.freeze.delay", "2 seconds"), " ")[0];
protection_freeze_delay_time = Util.split(getConfigString("protection.freeze.delay", "2 seconds"), " ")[1];
protection_freeze_delay = Util.toSeconds(protection_freeze_delay_time, protection_freeze_delay_length);
protection_notify = getConfigBoolean("protection.notify.enabled", true);
protection_notify_delay_length = Util.split(getConfigString("protection.notify.delay", "3 seconds"), " ")[0];
protection_notify_delay_time = Util.split(getConfigString("protection.notify.delay", "3 seconds"), " ")[1];
protection_notify_delay = Util.toSeconds(protection_notify_delay_time, protection_notify_delay_length);
filter_action = Util.getAction(getConfigString("filter.action", "kick").toLowerCase());
filter_username = getConfigString("filter.username", "`~!@#$%^&*()-= + {[]}|\\:;\"<,>.?/");
- filter_password = getConfigString("filter.password", "&");
+ filter_password = getConfigString("filter.password", "$&\"\\");
filter_whitelist= getConfigString("filter.whitelist", "");
} else if (config.equalsIgnoreCase("plugins")) {
CraftIRC_enabled = getConfigBoolean("CraftIRC.enabled", true);
CraftIRC_tag = getConfigString("CraftIRC.tag", "admin");
CraftIRC_prefix = getConfigString("CraftIRC.prefix", "%b%%green%[{PLUGIN}]%k%%b%");
/*
CraftIRC_messages_enabled = getConfigBoolean("CraftIRC.messages.enabled", true);
CraftIRC_messages_welcome_enabled = getConfigBoolean("CraftIRC.messages.welcome", true);
CraftIRC_messages_register_enabled = getConfigBoolean("CraftIRC.messages.register", true);
CraftIRC_messages_unregister_enabled = getConfigBoolean("CraftIRC.messages.unregister", true);
CraftIRC_messages_login_enabled = getConfigBoolean("CraftIRC.messages.login", true);
CraftIRC_messages_email_enabled = getConfigBoolean("CraftIRC.messages.email", true);
CraftIRC_messages_username_enabled = getConfigBoolean("CraftIRC.messages.username", true);
CraftIRC_messages_password_enabled = getConfigBoolean("CraftIRC.messages.password", true);
CraftIRC_messages_idle_enabled = getConfigBoolean("CraftIRC.messages.idle", true);
*/
} else if (config.equalsIgnoreCase("messages")) {
Messages.time_millisecond = Config.getConfigString("Core.time.millisecond.", "millisecond");
Messages.time_milliseconds = Config.getConfigString("Core.time.milliseconds", "milliseconds");
Messages.time_second = Config.getConfigString("Core.time.second.", "second");
Messages.time_seconds = Config.getConfigString("Core.time.seconds", "seconds");
Messages.time_minute = Config.getConfigString("Core.time.minute.", "minute");
Messages.time_minutes = Config.getConfigString("Core.time.minutes", "minutes");
Messages.time_hour = Config.getConfigString("Core.time.hour.", "hour");
Messages.time_hours = Config.getConfigString("Core.time.hours", "hours");
Messages.time_day = Config.getConfigString("Core.time.day", "day");
Messages.time_days = Config.getConfigString("Core.time.days", "days");
Messages.AuthDB_message_reload_success = Config.getConfigString("Core.reload.success", "AuthDB has successfully reloaded!");
Messages.AuthDB_message_database_failure = Config.getConfigString("Core.database.failure", "{RED}database connection failed! Access is denied! Contact admin.");
Messages.AuthDB_message_register_welcome = (String)Config.getConfigString("Core.register.welcome", "{YELLOW}Welcome {WHITE}guest{YELLOW}! Please use {REGISTERCMD} password email");
Messages.AuthDB_message_register_success = Config.getConfigString("Core.register.success", "{RED}You have been registered!");
Messages.AuthDB_message_register_failure = Config.getConfigString("Core.register.failure", "{RED}Registration failed!");
Messages.AuthDB_message_register_offline = Config.getConfigString("Core.register.offline", "{RED}Database is unavailable. Unable to verify password!");
Messages.AuthDB_message_register_exists = Config.getConfigString("Core.register.exists", "{RED}You are already registered!");
Messages.AuthDB_message_register_disabled = Config.getConfigString("Core.register.disabled", "{RED}Registration not allowed!");
Messages.AuthDB_message_register_usage = Config.getConfigString("Core.register.usage", "{RED}Correct usage is: /register password email");
Messages.AuthDB_message_register_timeout = Config.getConfigString("Core.register.timeout", "Kicked because you failed to register within {REGISTERTIMEOUT}.");
Messages.AuthDB_message_unregister_success = Config.getConfigString("Core.unregister.success", "{BRIGHTGREEN}Unregistered successfully!");
Messages.AuthDB_message_unregister_failure = Config.getConfigString("Core.unregister.failure", "{RED}An error occurred while unregistering!");
Messages.AuthDB_message_unregister_usage = Config.getConfigString("Core.unregister.usage", "{RED}Correct usage is: /unregister password");
Messages.AuthDB_message_logout_success = Config.getConfigString("Core.logout.success", "Successfully logged out!");
Messages.AuthDB_message_logout_failure = Config.getConfigString("Core.logout.failure", "You are not logged in!");
Messages.AuthDB_message_logout_admin = Config.getConfigString("Core.logout.admin", "You have been logged out by an admin.");
Messages.AuthDB_message_logout_admin_success = Config.getConfigString("Core.logout.adminsuccess", "Successfully logged out player, {PLAYER}.");
Messages.AuthDB_message_logout_admin_failure = Config.getConfigString("Core.logout.adminfailure", "You cannot logout player, {PLAYER}! That player is not logged in");
Messages.AuthDB_message_logout_admin_notfound = Config.getConfigString("Core.logout.adminnotfound", "Could not find player, {PLAYER}! Please try again.");
Messages.AuthDB_message_logout_usage = Config.getConfigString("Core.logout.usage", "{YELLOW}Correct usage is: {WHITE}{LOGOUTCMD}");
Messages.AuthDB_message_login_normal = Config.getConfigString("Core.login.normal", "{YELLOW}Welcome back {WHITE}{PLAYER}{YELLOW}! Please use /login password");
Messages.AuthDB_message_login_prompt = Config.getConfigString("Core.login.prompt", "{WHITE}Welcome {TEAL}{PLAYER}{WHITE}! Please enter your password:");
Messages.AuthDB_message_login_success = Config.getConfigString("Core.login.success", "{BRIGHTGREEN}Password accepted. Welcome!");
Messages.AuthDB_message_login_failure = Config.getConfigString("Core.login.failure", "{RED}Password incorrect, please try again.");
Messages.AuthDB_message_login_offline = Config.getConfigString("Core.login.offline", "{RED}Database is unavailable. Unable to verify password!");
Messages.AuthDB_message_login_authorized = Config.getConfigString("Core.login.authorized", "{BRIGHTGREEN}You are already logged in!");
Messages.AuthDB_message_login_notregistered = Config.getConfigString("Core.login.notregistered", "{RED}You are not registred yet!");
Messages.AuthDB_message_login_timeout = Config.getConfigString("Core.login.timeout", "Kicked because you failed to login within {LOGINTIMEOUT}.");
Messages.AuthDB_message_login_admin = Config.getConfigString("Core.login.admin", "You have been logged in by an admin.");
Messages.AuthDB_message_login_admin_success = Config.getConfigString("Core.login.admin.success", "Successfully logged in player, {PLAYER}.");
Messages.AuthDB_message_login_admin_failure = Config.getConfigString("Core.login.adminfailure", "You cannot login player {PLAYER}! That player is already logged in.");
Messages.AuthDB_message_login_admin_notfound = Config.getConfigString("Core.login.adminnotfound", "Could not find player, {PLAYER}! Please try again.");
Messages.AuthDB_message_login_usage = Config.getConfigString("Core.login.usage", "{RED}Correct usage is: /login password");
Messages.AuthDB_message_link_welcome = (String)Config.getConfigString("Core.link.welcome", "or {LINKCMD} otherusername password");
Messages.AuthDB_message_link_success = Config.getConfigString("Core.link.success", "{BRIGHTGREEN}You have successfully linked!. You are now logged in");
Messages.AuthDB_message_link_failure = Config.getConfigString("Core.link.failure", "{RED}Error while linking!");
Messages.AuthDB_message_link_exists = Config.getConfigString("Core.link.exists", "{RED}You are already linked to a username!");
Messages.AuthDB_message_link_duplicate = Config.getConfigString("Core.link.duplicate", "{RED}Username is already linked to another player!");
Messages.AuthDB_message_link_registred = Config.getConfigString("Core.link.registred", "{RED}You cannot link as this username is already registered!");
Messages.AuthDB_message_link_invaliduser = Config.getConfigString("Core.link.invaliduser", "{RED}You cannot link with yourself!");
Messages.AuthDB_message_link_renamed = Config.getConfigString("Core.link.renamed", "{YELLOW}{PLAYER} has been renamed to {DISPLAYNAME}.");
Messages.AuthDB_message_link_usage = Config.getConfigString("Core.link.usage", "{RED}Correct usage is: /link otherusername password");
Messages.AuthDB_message_unlink_success = Config.getConfigString("Core.unlink.success", "{BRIGHTGREEN}You have successfully unlinked!");
Messages.AuthDB_message_unlink_failure = Config.getConfigString("Core.unlink.failure", "{RED}Error while unlinking!");
Messages.AuthDB_message_unlink_nonexist = Config.getConfigString("Core.unlink.nonexist", "{RED}You do not have a linked username!");
Messages.AuthDB_message_unlink_invaliduser = Config.getConfigString("Core.unlink.invaliduser", "{RED}Invalid linked username!");
Messages.AuthDB_message_unlink_invalidpass = Config.getConfigString("Core.unlink.invalidpass", "{RED}Invalid linked password!");
Messages.AuthDB_message_unlink_renamed = Config.getConfigString("Core.unlink.renamed", "{YELLOW}{DISPLAYNAME} has been renamed to {PLAYER}.");
Messages.AuthDB_message_unlink_usage = Config.getConfigString("Core.unlink.usage", "{RED}Correct usage is: /unlink otherusername password");
Messages.AuthDB_message_email_required = Config.getConfigString("Core.email.required", "{RED}Email required for registration!");
Messages.AuthDB_message_email_invalid = Config.getConfigString("Core.email.invalid", "{RED}Invalid email! Please try again!");
Messages.AuthDB_message_email_badcharacters = Config.getConfigString("Core.email.badcharacters", "{RED}Email contains bad characters! {BADCHARACTERS}!");
Messages.AuthDB_message_filter_renamed = Config.getConfigString("Core.filter.renamed", "{RED}{PLAYER} renamed to {PLAYERNEW} due to bad characters: {USERBADCHARACTERS}.");
Messages.AuthDB_message_filter_username = Config.getConfigString("Core.filter.username", "{RED}Username contains bad characters: {USERBADCHARACTERS}!");
Messages.AuthDB_message_filter_password = Config.getConfigString("Core.filter.password", "{RED}Password contains bad characters: {PASSBADCHARACTERS}!");
Messages.AuthDB_message_filter_whitelist = Config.getConfigString("Core.filter.whitelist", "{BRIGHTGREEN}{PLAYER} is on the filter {WHITE}whitelist{BRIGHTGREEN}, bypassing restrictions!");
Messages.AuthDB_message_username_minimum = Config.getConfigString("Core.username.minimum", "{RED}Your username does not meet the minimum requirement of {USERMIN} characters!");
Messages.AuthDB_message_username_maximum = Config.getConfigString("Core.username.maximum", "{RED}Your username does not meet the maximum requirement of {USERMAX} characters!");
Messages.AuthDB_message_password_minimum = Config.getConfigString("Core.password.minimum", "{RED}Your password does not meet the minimum requirement of {PASSMIN} characters!");
Messages.AuthDB_message_password_maximum = Config.getConfigString("Core.password.maximum", "{RED}Your password does not meet the maximum requirement of {PASSMAX} characters!");
Messages.AuthDB_message_password_success = Config.getConfigString("Core.password.success", "{BRIGHTGREEN}Password changed successfully!");
Messages.AuthDB_message_password_failure = Config.getConfigString("Core.password.failure", "{RED}Error! Password change failed!");
Messages.AuthDB_message_password_notregistered = Config.getConfigString("Core.password.notregistered", "{RED}Register first!");
Messages.AuthDB_message_password_usage = Config.getConfigString("Core.password.usage", "{RED}Correct usage is: /password oldpassword password");
Messages.AuthDB_message_session_valid = Config.getConfigString("Core.session.valid", "{BRIGHTGREEN}Hey, I remember you! You are logged in!");
Messages.AuthDB_message_session_protected = Config.getConfigString("Core.session.protected", "{RED}Sorry, a player with that name is already logged in on this server.");
Messages.AuthDB_message_protection_denied = Config.getConfigString("Core.protection.denied", "You do not have permission to use that command.");
Messages.AuthDB_message_protection_notauthorized = Config.getConfigString("Core.protection.notauthorized", "{RED}You are not authorized to do that!");
Messages.CraftIRC_message_status_join = Config.getConfigString("Plugins.CraftIRC.status.join", "{PLAYER} has joined the server.");
Messages.CraftIRC_message_status_quit = Config.getConfigString("Plugins.CraftIRC.status.quit", "{PLAYER} has quit the server.");
Messages.CraftIRC_message_register_success = Config.getConfigString("Plugins.CraftIRC.register.success", "{PLAYER} just registered successfully!");
Messages.CraftIRC_message_register_failure = Config.getConfigString("Plugins.CraftIRC.register.failure", "{PLAYER} had some errors while registering!");
Messages.CraftIRC_message_register_registered = Config.getConfigString("Plugins.CraftIRC.register.registered", "{PLAYER} had a lapse in memory and tried to register again.");
Messages.CraftIRC_message_password_success = Config.getConfigString("Plugins.CraftIRC.password.success", "{PLAYER} logged in successfully!");
Messages.CraftIRC_message_password_failure = Config.getConfigString("Plugins.CraftIRC.password.failure", "{PLAYER} tried to login with the wrong password!");
Messages.CraftIRC_message_idle_kicked = Config.getConfigString("Plugins.CraftIRC.idle.kicked", "{PLAYER} was kicked due to bad characters in username!");
Messages.CraftIRC_message_idle_whitelist = Config.getConfigString("Plugins.CraftIRC.idle.whitelist", "{PLAYER} is on the on bad characters whitelist, bypassing restictions!");
Messages.CraftIRC_message_filter_renamed = Config.getConfigString("Plugins.CraftIRC.filter.renamed", "{PLAYER} renamed to {PLAYERNEW} due to bad characters.");
Messages.CraftIRC_message_filter_kicked = Config.getConfigString("Plugins.CraftIRC.filter.kicked", "{PLAYER} was kicked due to bad characters in username!");
Messages.CraftIRC_message_filter_whitelist = Config.getConfigString("Plugins.CraftIRC.filter.whitelist", "{PLAYER} is on the on bad characters whitelist, bypassing restictions!");
} else if (config.equalsIgnoreCase("commands")) {
commands_user_register = Config.getConfigString("Core.commands.user.register", "/register");
commands_user_link = Config.getConfigString("Core.commands.user.link", "/link");
commands_user_unlink = Config.getConfigString("Core.commands.user.unlink", "/unlink");
commands_user_login = Config.getConfigString("Core.commands.user.login", "/login");
commands_user_logout = Config.getConfigString("Core.commands.user.logout", "/logout");
commands_admin_login = Config.getConfigString("Core.commands.admin.login", "/authdb login");
commands_admin_logout = Config.getConfigString("Core.commands.admin.logout", "/authdb logout");
commands_admin_reload = Config.getConfigString("Core.commands.admin.reload", "/authdb reload");
aliases_user_register = Config.getConfigString("Core.aliases.user.register", "/r");
aliases_user_link = Config.getConfigString("Core.aliases.user.link", "/li");
aliases_user_unlink = Config.getConfigString("Core.aliases.user.unlink", "/ul");
aliases_user_login = Config.getConfigString("Core.aliases.user.login", "/l");
aliases_user_logout = Config.getConfigString("Core.aliases.user.logout", "/lo");
- aliases_admin_login = Config.getConfigString("Core.aliases.admin.login", "/ar");
- aliases_admin_logout = Config.getConfigString("Core.aliases.admin.logout", "/ar");
+ aliases_admin_login = Config.getConfigString("Core.aliases.admin.login", "/al");
+ aliases_admin_logout = Config.getConfigString("Core.aliases.admin.logout", "/alo");
aliases_admin_reload = Config.getConfigString("Core.aliases.admin.reload", "/ar");
}
}
public static String getConfigString(String key, String defaultvalue) {
return template.getString(key, defaultvalue);
}
public static boolean getConfigBoolean(String key, boolean defaultvalue) {
return template.getBoolean(key, defaultvalue);
}
public void deleteConfigValue(String key) {
template.removeProperty(key);
}
public String raw(String key, String line) {
return template.getString(key, line);
}
public void save(String key, String line) {
template.setProperty(key, line);
}
}
| false | true | public Config(String config, String directory, String filename) {
template = new Configuration(new File(directory, filename));
template.load();
if (config.equalsIgnoreCase("basic")) {
language = getConfigString("plugin.language", "English");
autoupdate_enable = getConfigBoolean("plugin.autoupdate", true);
debug_enable = getConfigBoolean("plugin.debugmode", false);
usagestats_enabled = getConfigBoolean("plugin.usagestats", true);
logformat = getConfigString("plugin.logformat", "yyyy-MM-dd");
logging_enabled = getConfigBoolean("plugin.logging", true);
database_type = getConfigString("database.type", "mysql");
database_username = getConfigString("database.username", "root");
database_password = getConfigString("database.password", "");
database_port = getConfigString("database.port", "3306");
database_host = getConfigString("database.host", "localhost");
database_database = getConfigString("database.name", "forum");
database_keepalive = getConfigBoolean("database.keepalive", false);
dbDb = "jdbc:mysql://" + database_host + ":" + database_port + "/" + database_database;
script_name = getConfigString("script.name", "phpbb").toLowerCase();
script_version = getConfigString("script.version", "3.0.8");
script_tableprefix = getConfigString("script.tableprefix", "");
script_updatestatus = getConfigBoolean("script.updatestatus", true);
script_salt = getConfigString("script.salt", "");
} else if (config.equalsIgnoreCase("advanced")) {
custom_enabled = getConfigBoolean("customdb.enabled", false);
custom_autocreate = getConfigBoolean("customdb.autocreate", true);
custom_emailrequired = getConfigBoolean("customdb.emailrequired", false);
custom_table = getConfigString("customdb.table", "authdb_users");
custom_userfield = getConfigString("customdb.userfield", "username");
custom_passfield = getConfigString("customdb.passfield", "password");
custom_emailfield = getConfigString("customdb.emailfield", "email");
custom_encryption = getConfigString("customdb.encryption", "md5").toLowerCase();
register_enabled = getConfigBoolean("register.enabled", true);
register_force = getConfigBoolean("register.force", true);
register_delay_length = Util.split(getConfigString("register.delay", "4 seconds"), " ")[0];
register_delay_time = Util.split(getConfigString("register.delay", "4 seconds"), " ")[1];
register_delay = Util.toTicks(register_delay_time,register_delay_length);
register_show_length = Util.split(getConfigString("register.show", "10 seconds"), " ")[0];
register_show_time = Util.split(getConfigString("register.show", "10 seconds"), " ")[1];
register_show = Util.toSeconds(register_show_time,register_show_length);
register_timeout_length = Util.split(getConfigString("register.timeout", "3 minutes"), " ")[0];
register_timeout_time = Util.split(getConfigString("register.timeout", "3 minutes"), " ")[1];
register_timeout = Util.toTicks(register_timeout_time,register_timeout_length);
login_method = getConfigString("login.method", "prompt");
login_tries = getConfigString("login.tries", "3");
login_action = Util.getAction(getConfigString("filter.action", "kick").toLowerCase());
login_delay_length = Util.split(getConfigString("login.delay", "4 seconds"), " ")[0];
login_delay_time = Util.split(getConfigString("login.delay", "4 seconds"), " ")[1];
login_delay = Util.toTicks(login_delay_time,login_delay_length);
login_show_length = Util.split(getConfigString("login.show", "10 seconds"), " ")[0];
login_show_time = Util.split(getConfigString("login.show", "10 seconds"), " ")[1];
login_show = Util.toSeconds(login_show_time,login_show_length);
login_timeout_length = Util.split(getConfigString("login.timeout", "3 minutes"), " ")[0];
login_timeout_time = Util.split(getConfigString("login.timeout", "3 minutes"), " ")[1];
login_timeout = Util.toTicks(login_timeout_time,login_timeout_length);
link_enabled = getConfigBoolean("link.enabled", true);
link_rename = getConfigBoolean("link.rename", true);
unlink_enabled = getConfigBoolean("unlink.enabled", true);
unlink_rename = getConfigBoolean("unlink.rename", true);
username_minimum = getConfigString("username.minimum", "3");
username_maximum = getConfigString("username.maximum", "16");
password_minimum = getConfigString("password.minimum", "6");
password_maximum = getConfigString("password.maximum", "16");
session_enabled = getConfigBoolean("session.enabled", false);
session_protect = getConfigBoolean("session.protect", true);
session_thelength = Util.split(getConfigString("session.length", "1 hour"), " ")[0];
session_time = Util.split(getConfigString("session.length", "1 hour"), " ")[1];
session_length = Util.toSeconds(session_time,session_thelength);
session_start = Util.checkSessionStart(getConfigString("session.start", "login"));
guests_commands = getConfigBoolean("guest.commands", false);
guests_movement = getConfigBoolean("guest.movement", false);
guests_inventory = getConfigBoolean("guest.inventory", false);
guests_drop = getConfigBoolean("guest.drop", false);
guests_pickup = getConfigBoolean("guest.pickup", false);
guests_health = getConfigBoolean("guest.health", false);
guests_mobdamage = getConfigBoolean("guest.mobdamage", false);
guests_interact = getConfigBoolean("guest.interactions", false);
guests_build = getConfigBoolean("guest.building", false);
guests_destroy = getConfigBoolean("guest.destruction", false);
guests_chat = getConfigBoolean("guest.chat", false);
guests_mobtargeting = getConfigBoolean("guest.mobtargeting", false);
guests_pvp = getConfigBoolean("guest.pvp", false);
protection_freeze = getConfigBoolean("protection.freeze.enabled", true);
protection_freeze_delay_length = Util.split(getConfigString("protection.freeze.delay", "2 seconds"), " ")[0];
protection_freeze_delay_time = Util.split(getConfigString("protection.freeze.delay", "2 seconds"), " ")[1];
protection_freeze_delay = Util.toSeconds(protection_freeze_delay_time, protection_freeze_delay_length);
protection_notify = getConfigBoolean("protection.notify.enabled", true);
protection_notify_delay_length = Util.split(getConfigString("protection.notify.delay", "3 seconds"), " ")[0];
protection_notify_delay_time = Util.split(getConfigString("protection.notify.delay", "3 seconds"), " ")[1];
protection_notify_delay = Util.toSeconds(protection_notify_delay_time, protection_notify_delay_length);
filter_action = Util.getAction(getConfigString("filter.action", "kick").toLowerCase());
filter_username = getConfigString("filter.username", "`~!@#$%^&*()-= + {[]}|\\:;\"<,>.?/");
filter_password = getConfigString("filter.password", "&");
filter_whitelist= getConfigString("filter.whitelist", "");
} else if (config.equalsIgnoreCase("plugins")) {
CraftIRC_enabled = getConfigBoolean("CraftIRC.enabled", true);
CraftIRC_tag = getConfigString("CraftIRC.tag", "admin");
CraftIRC_prefix = getConfigString("CraftIRC.prefix", "%b%%green%[{PLUGIN}]%k%%b%");
/*
CraftIRC_messages_enabled = getConfigBoolean("CraftIRC.messages.enabled", true);
CraftIRC_messages_welcome_enabled = getConfigBoolean("CraftIRC.messages.welcome", true);
CraftIRC_messages_register_enabled = getConfigBoolean("CraftIRC.messages.register", true);
CraftIRC_messages_unregister_enabled = getConfigBoolean("CraftIRC.messages.unregister", true);
CraftIRC_messages_login_enabled = getConfigBoolean("CraftIRC.messages.login", true);
CraftIRC_messages_email_enabled = getConfigBoolean("CraftIRC.messages.email", true);
CraftIRC_messages_username_enabled = getConfigBoolean("CraftIRC.messages.username", true);
CraftIRC_messages_password_enabled = getConfigBoolean("CraftIRC.messages.password", true);
CraftIRC_messages_idle_enabled = getConfigBoolean("CraftIRC.messages.idle", true);
*/
} else if (config.equalsIgnoreCase("messages")) {
Messages.time_millisecond = Config.getConfigString("Core.time.millisecond.", "millisecond");
Messages.time_milliseconds = Config.getConfigString("Core.time.milliseconds", "milliseconds");
Messages.time_second = Config.getConfigString("Core.time.second.", "second");
Messages.time_seconds = Config.getConfigString("Core.time.seconds", "seconds");
Messages.time_minute = Config.getConfigString("Core.time.minute.", "minute");
Messages.time_minutes = Config.getConfigString("Core.time.minutes", "minutes");
Messages.time_hour = Config.getConfigString("Core.time.hour.", "hour");
Messages.time_hours = Config.getConfigString("Core.time.hours", "hours");
Messages.time_day = Config.getConfigString("Core.time.day", "day");
Messages.time_days = Config.getConfigString("Core.time.days", "days");
Messages.AuthDB_message_reload_success = Config.getConfigString("Core.reload.success", "AuthDB has successfully reloaded!");
Messages.AuthDB_message_database_failure = Config.getConfigString("Core.database.failure", "{RED}database connection failed! Access is denied! Contact admin.");
Messages.AuthDB_message_register_welcome = (String)Config.getConfigString("Core.register.welcome", "{YELLOW}Welcome {WHITE}guest{YELLOW}! Please use {REGISTERCMD} password email");
Messages.AuthDB_message_register_success = Config.getConfigString("Core.register.success", "{RED}You have been registered!");
Messages.AuthDB_message_register_failure = Config.getConfigString("Core.register.failure", "{RED}Registration failed!");
Messages.AuthDB_message_register_offline = Config.getConfigString("Core.register.offline", "{RED}Database is unavailable. Unable to verify password!");
Messages.AuthDB_message_register_exists = Config.getConfigString("Core.register.exists", "{RED}You are already registered!");
Messages.AuthDB_message_register_disabled = Config.getConfigString("Core.register.disabled", "{RED}Registration not allowed!");
Messages.AuthDB_message_register_usage = Config.getConfigString("Core.register.usage", "{RED}Correct usage is: /register password email");
Messages.AuthDB_message_register_timeout = Config.getConfigString("Core.register.timeout", "Kicked because you failed to register within {REGISTERTIMEOUT}.");
Messages.AuthDB_message_unregister_success = Config.getConfigString("Core.unregister.success", "{BRIGHTGREEN}Unregistered successfully!");
Messages.AuthDB_message_unregister_failure = Config.getConfigString("Core.unregister.failure", "{RED}An error occurred while unregistering!");
Messages.AuthDB_message_unregister_usage = Config.getConfigString("Core.unregister.usage", "{RED}Correct usage is: /unregister password");
Messages.AuthDB_message_logout_success = Config.getConfigString("Core.logout.success", "Successfully logged out!");
Messages.AuthDB_message_logout_failure = Config.getConfigString("Core.logout.failure", "You are not logged in!");
Messages.AuthDB_message_logout_admin = Config.getConfigString("Core.logout.admin", "You have been logged out by an admin.");
Messages.AuthDB_message_logout_admin_success = Config.getConfigString("Core.logout.adminsuccess", "Successfully logged out player, {PLAYER}.");
Messages.AuthDB_message_logout_admin_failure = Config.getConfigString("Core.logout.adminfailure", "You cannot logout player, {PLAYER}! That player is not logged in");
Messages.AuthDB_message_logout_admin_notfound = Config.getConfigString("Core.logout.adminnotfound", "Could not find player, {PLAYER}! Please try again.");
Messages.AuthDB_message_logout_usage = Config.getConfigString("Core.logout.usage", "{YELLOW}Correct usage is: {WHITE}{LOGOUTCMD}");
Messages.AuthDB_message_login_normal = Config.getConfigString("Core.login.normal", "{YELLOW}Welcome back {WHITE}{PLAYER}{YELLOW}! Please use /login password");
Messages.AuthDB_message_login_prompt = Config.getConfigString("Core.login.prompt", "{WHITE}Welcome {TEAL}{PLAYER}{WHITE}! Please enter your password:");
Messages.AuthDB_message_login_success = Config.getConfigString("Core.login.success", "{BRIGHTGREEN}Password accepted. Welcome!");
Messages.AuthDB_message_login_failure = Config.getConfigString("Core.login.failure", "{RED}Password incorrect, please try again.");
Messages.AuthDB_message_login_offline = Config.getConfigString("Core.login.offline", "{RED}Database is unavailable. Unable to verify password!");
Messages.AuthDB_message_login_authorized = Config.getConfigString("Core.login.authorized", "{BRIGHTGREEN}You are already logged in!");
Messages.AuthDB_message_login_notregistered = Config.getConfigString("Core.login.notregistered", "{RED}You are not registred yet!");
Messages.AuthDB_message_login_timeout = Config.getConfigString("Core.login.timeout", "Kicked because you failed to login within {LOGINTIMEOUT}.");
Messages.AuthDB_message_login_admin = Config.getConfigString("Core.login.admin", "You have been logged in by an admin.");
Messages.AuthDB_message_login_admin_success = Config.getConfigString("Core.login.admin.success", "Successfully logged in player, {PLAYER}.");
Messages.AuthDB_message_login_admin_failure = Config.getConfigString("Core.login.adminfailure", "You cannot login player {PLAYER}! That player is already logged in.");
Messages.AuthDB_message_login_admin_notfound = Config.getConfigString("Core.login.adminnotfound", "Could not find player, {PLAYER}! Please try again.");
Messages.AuthDB_message_login_usage = Config.getConfigString("Core.login.usage", "{RED}Correct usage is: /login password");
Messages.AuthDB_message_link_welcome = (String)Config.getConfigString("Core.link.welcome", "or {LINKCMD} otherusername password");
Messages.AuthDB_message_link_success = Config.getConfigString("Core.link.success", "{BRIGHTGREEN}You have successfully linked!. You are now logged in");
Messages.AuthDB_message_link_failure = Config.getConfigString("Core.link.failure", "{RED}Error while linking!");
Messages.AuthDB_message_link_exists = Config.getConfigString("Core.link.exists", "{RED}You are already linked to a username!");
Messages.AuthDB_message_link_duplicate = Config.getConfigString("Core.link.duplicate", "{RED}Username is already linked to another player!");
Messages.AuthDB_message_link_registred = Config.getConfigString("Core.link.registred", "{RED}You cannot link as this username is already registered!");
Messages.AuthDB_message_link_invaliduser = Config.getConfigString("Core.link.invaliduser", "{RED}You cannot link with yourself!");
Messages.AuthDB_message_link_renamed = Config.getConfigString("Core.link.renamed", "{YELLOW}{PLAYER} has been renamed to {DISPLAYNAME}.");
Messages.AuthDB_message_link_usage = Config.getConfigString("Core.link.usage", "{RED}Correct usage is: /link otherusername password");
Messages.AuthDB_message_unlink_success = Config.getConfigString("Core.unlink.success", "{BRIGHTGREEN}You have successfully unlinked!");
Messages.AuthDB_message_unlink_failure = Config.getConfigString("Core.unlink.failure", "{RED}Error while unlinking!");
Messages.AuthDB_message_unlink_nonexist = Config.getConfigString("Core.unlink.nonexist", "{RED}You do not have a linked username!");
Messages.AuthDB_message_unlink_invaliduser = Config.getConfigString("Core.unlink.invaliduser", "{RED}Invalid linked username!");
Messages.AuthDB_message_unlink_invalidpass = Config.getConfigString("Core.unlink.invalidpass", "{RED}Invalid linked password!");
Messages.AuthDB_message_unlink_renamed = Config.getConfigString("Core.unlink.renamed", "{YELLOW}{DISPLAYNAME} has been renamed to {PLAYER}.");
Messages.AuthDB_message_unlink_usage = Config.getConfigString("Core.unlink.usage", "{RED}Correct usage is: /unlink otherusername password");
Messages.AuthDB_message_email_required = Config.getConfigString("Core.email.required", "{RED}Email required for registration!");
Messages.AuthDB_message_email_invalid = Config.getConfigString("Core.email.invalid", "{RED}Invalid email! Please try again!");
Messages.AuthDB_message_email_badcharacters = Config.getConfigString("Core.email.badcharacters", "{RED}Email contains bad characters! {BADCHARACTERS}!");
Messages.AuthDB_message_filter_renamed = Config.getConfigString("Core.filter.renamed", "{RED}{PLAYER} renamed to {PLAYERNEW} due to bad characters: {USERBADCHARACTERS}.");
Messages.AuthDB_message_filter_username = Config.getConfigString("Core.filter.username", "{RED}Username contains bad characters: {USERBADCHARACTERS}!");
Messages.AuthDB_message_filter_password = Config.getConfigString("Core.filter.password", "{RED}Password contains bad characters: {PASSBADCHARACTERS}!");
Messages.AuthDB_message_filter_whitelist = Config.getConfigString("Core.filter.whitelist", "{BRIGHTGREEN}{PLAYER} is on the filter {WHITE}whitelist{BRIGHTGREEN}, bypassing restrictions!");
Messages.AuthDB_message_username_minimum = Config.getConfigString("Core.username.minimum", "{RED}Your username does not meet the minimum requirement of {USERMIN} characters!");
Messages.AuthDB_message_username_maximum = Config.getConfigString("Core.username.maximum", "{RED}Your username does not meet the maximum requirement of {USERMAX} characters!");
Messages.AuthDB_message_password_minimum = Config.getConfigString("Core.password.minimum", "{RED}Your password does not meet the minimum requirement of {PASSMIN} characters!");
Messages.AuthDB_message_password_maximum = Config.getConfigString("Core.password.maximum", "{RED}Your password does not meet the maximum requirement of {PASSMAX} characters!");
Messages.AuthDB_message_password_success = Config.getConfigString("Core.password.success", "{BRIGHTGREEN}Password changed successfully!");
Messages.AuthDB_message_password_failure = Config.getConfigString("Core.password.failure", "{RED}Error! Password change failed!");
Messages.AuthDB_message_password_notregistered = Config.getConfigString("Core.password.notregistered", "{RED}Register first!");
Messages.AuthDB_message_password_usage = Config.getConfigString("Core.password.usage", "{RED}Correct usage is: /password oldpassword password");
Messages.AuthDB_message_session_valid = Config.getConfigString("Core.session.valid", "{BRIGHTGREEN}Hey, I remember you! You are logged in!");
Messages.AuthDB_message_session_protected = Config.getConfigString("Core.session.protected", "{RED}Sorry, a player with that name is already logged in on this server.");
Messages.AuthDB_message_protection_denied = Config.getConfigString("Core.protection.denied", "You do not have permission to use that command.");
Messages.AuthDB_message_protection_notauthorized = Config.getConfigString("Core.protection.notauthorized", "{RED}You are not authorized to do that!");
Messages.CraftIRC_message_status_join = Config.getConfigString("Plugins.CraftIRC.status.join", "{PLAYER} has joined the server.");
Messages.CraftIRC_message_status_quit = Config.getConfigString("Plugins.CraftIRC.status.quit", "{PLAYER} has quit the server.");
Messages.CraftIRC_message_register_success = Config.getConfigString("Plugins.CraftIRC.register.success", "{PLAYER} just registered successfully!");
Messages.CraftIRC_message_register_failure = Config.getConfigString("Plugins.CraftIRC.register.failure", "{PLAYER} had some errors while registering!");
Messages.CraftIRC_message_register_registered = Config.getConfigString("Plugins.CraftIRC.register.registered", "{PLAYER} had a lapse in memory and tried to register again.");
Messages.CraftIRC_message_password_success = Config.getConfigString("Plugins.CraftIRC.password.success", "{PLAYER} logged in successfully!");
Messages.CraftIRC_message_password_failure = Config.getConfigString("Plugins.CraftIRC.password.failure", "{PLAYER} tried to login with the wrong password!");
Messages.CraftIRC_message_idle_kicked = Config.getConfigString("Plugins.CraftIRC.idle.kicked", "{PLAYER} was kicked due to bad characters in username!");
Messages.CraftIRC_message_idle_whitelist = Config.getConfigString("Plugins.CraftIRC.idle.whitelist", "{PLAYER} is on the on bad characters whitelist, bypassing restictions!");
Messages.CraftIRC_message_filter_renamed = Config.getConfigString("Plugins.CraftIRC.filter.renamed", "{PLAYER} renamed to {PLAYERNEW} due to bad characters.");
Messages.CraftIRC_message_filter_kicked = Config.getConfigString("Plugins.CraftIRC.filter.kicked", "{PLAYER} was kicked due to bad characters in username!");
Messages.CraftIRC_message_filter_whitelist = Config.getConfigString("Plugins.CraftIRC.filter.whitelist", "{PLAYER} is on the on bad characters whitelist, bypassing restictions!");
} else if (config.equalsIgnoreCase("commands")) {
commands_user_register = Config.getConfigString("Core.commands.user.register", "/register");
commands_user_link = Config.getConfigString("Core.commands.user.link", "/link");
commands_user_unlink = Config.getConfigString("Core.commands.user.unlink", "/unlink");
commands_user_login = Config.getConfigString("Core.commands.user.login", "/login");
commands_user_logout = Config.getConfigString("Core.commands.user.logout", "/logout");
commands_admin_login = Config.getConfigString("Core.commands.admin.login", "/authdb login");
commands_admin_logout = Config.getConfigString("Core.commands.admin.logout", "/authdb logout");
commands_admin_reload = Config.getConfigString("Core.commands.admin.reload", "/authdb reload");
aliases_user_register = Config.getConfigString("Core.aliases.user.register", "/r");
aliases_user_link = Config.getConfigString("Core.aliases.user.link", "/li");
aliases_user_unlink = Config.getConfigString("Core.aliases.user.unlink", "/ul");
aliases_user_login = Config.getConfigString("Core.aliases.user.login", "/l");
aliases_user_logout = Config.getConfigString("Core.aliases.user.logout", "/lo");
aliases_admin_login = Config.getConfigString("Core.aliases.admin.login", "/ar");
aliases_admin_logout = Config.getConfigString("Core.aliases.admin.logout", "/ar");
aliases_admin_reload = Config.getConfigString("Core.aliases.admin.reload", "/ar");
}
}
| public Config(String config, String directory, String filename) {
template = new Configuration(new File(directory, filename));
template.load();
if (config.equalsIgnoreCase("basic")) {
language = getConfigString("plugin.language", "English");
autoupdate_enable = getConfigBoolean("plugin.autoupdate", true);
debug_enable = getConfigBoolean("plugin.debugmode", false);
usagestats_enabled = getConfigBoolean("plugin.usagestats", true);
logformat = getConfigString("plugin.logformat", "yyyy-MM-dd");
logging_enabled = getConfigBoolean("plugin.logging", true);
database_type = getConfigString("database.type", "mysql");
database_username = getConfigString("database.username", "root");
database_password = getConfigString("database.password", "");
database_port = getConfigString("database.port", "3306");
database_host = getConfigString("database.host", "localhost");
database_database = getConfigString("database.name", "forum");
database_keepalive = getConfigBoolean("database.keepalive", false);
dbDb = "jdbc:mysql://" + database_host + ":" + database_port + "/" + database_database;
script_name = getConfigString("script.name", "phpbb").toLowerCase();
script_version = getConfigString("script.version", "3.0.8");
script_tableprefix = getConfigString("script.tableprefix", "");
script_updatestatus = getConfigBoolean("script.updatestatus", true);
script_salt = getConfigString("script.salt", "");
} else if (config.equalsIgnoreCase("advanced")) {
custom_enabled = getConfigBoolean("customdb.enabled", false);
custom_autocreate = getConfigBoolean("customdb.autocreate", true);
custom_emailrequired = getConfigBoolean("customdb.emailrequired", false);
custom_table = getConfigString("customdb.table", "authdb_users");
custom_userfield = getConfigString("customdb.userfield", "username");
custom_passfield = getConfigString("customdb.passfield", "password");
custom_emailfield = getConfigString("customdb.emailfield", "email");
custom_encryption = getConfigString("customdb.encryption", "md5").toLowerCase();
register_enabled = getConfigBoolean("register.enabled", true);
register_force = getConfigBoolean("register.force", true);
register_delay_length = Util.split(getConfigString("register.delay", "4 seconds"), " ")[0];
register_delay_time = Util.split(getConfigString("register.delay", "4 seconds"), " ")[1];
register_delay = Util.toTicks(register_delay_time,register_delay_length);
register_show_length = Util.split(getConfigString("register.show", "10 seconds"), " ")[0];
register_show_time = Util.split(getConfigString("register.show", "10 seconds"), " ")[1];
register_show = Util.toSeconds(register_show_time,register_show_length);
register_timeout_length = Util.split(getConfigString("register.timeout", "3 minutes"), " ")[0];
register_timeout_time = Util.split(getConfigString("register.timeout", "3 minutes"), " ")[1];
register_timeout = Util.toTicks(register_timeout_time,register_timeout_length);
login_method = getConfigString("login.method", "prompt");
login_tries = getConfigString("login.tries", "3");
login_action = Util.getAction(getConfigString("filter.action", "kick").toLowerCase());
login_delay_length = Util.split(getConfigString("login.delay", "4 seconds"), " ")[0];
login_delay_time = Util.split(getConfigString("login.delay", "4 seconds"), " ")[1];
login_delay = Util.toTicks(login_delay_time,login_delay_length);
login_show_length = Util.split(getConfigString("login.show", "10 seconds"), " ")[0];
login_show_time = Util.split(getConfigString("login.show", "10 seconds"), " ")[1];
login_show = Util.toSeconds(login_show_time,login_show_length);
login_timeout_length = Util.split(getConfigString("login.timeout", "3 minutes"), " ")[0];
login_timeout_time = Util.split(getConfigString("login.timeout", "3 minutes"), " ")[1];
login_timeout = Util.toTicks(login_timeout_time,login_timeout_length);
link_enabled = getConfigBoolean("link.enabled", true);
link_rename = getConfigBoolean("link.rename", true);
unlink_enabled = getConfigBoolean("unlink.enabled", true);
unlink_rename = getConfigBoolean("unlink.rename", true);
username_minimum = getConfigString("username.minimum", "3");
username_maximum = getConfigString("username.maximum", "16");
password_minimum = getConfigString("password.minimum", "6");
password_maximum = getConfigString("password.maximum", "16");
session_enabled = getConfigBoolean("session.enabled", false);
session_protect = getConfigBoolean("session.protect", true);
session_thelength = Util.split(getConfigString("session.length", "1 hour"), " ")[0];
session_time = Util.split(getConfigString("session.length", "1 hour"), " ")[1];
session_length = Util.toSeconds(session_time,session_thelength);
session_start = Util.checkSessionStart(getConfigString("session.start", "login"));
guests_commands = getConfigBoolean("guest.commands", false);
guests_movement = getConfigBoolean("guest.movement", false);
guests_inventory = getConfigBoolean("guest.inventory", false);
guests_drop = getConfigBoolean("guest.drop", false);
guests_pickup = getConfigBoolean("guest.pickup", false);
guests_health = getConfigBoolean("guest.health", false);
guests_mobdamage = getConfigBoolean("guest.mobdamage", false);
guests_interact = getConfigBoolean("guest.interactions", false);
guests_build = getConfigBoolean("guest.building", false);
guests_destroy = getConfigBoolean("guest.destruction", false);
guests_chat = getConfigBoolean("guest.chat", false);
guests_mobtargeting = getConfigBoolean("guest.mobtargeting", false);
guests_pvp = getConfigBoolean("guest.pvp", false);
protection_freeze = getConfigBoolean("protection.freeze.enabled", true);
protection_freeze_delay_length = Util.split(getConfigString("protection.freeze.delay", "2 seconds"), " ")[0];
protection_freeze_delay_time = Util.split(getConfigString("protection.freeze.delay", "2 seconds"), " ")[1];
protection_freeze_delay = Util.toSeconds(protection_freeze_delay_time, protection_freeze_delay_length);
protection_notify = getConfigBoolean("protection.notify.enabled", true);
protection_notify_delay_length = Util.split(getConfigString("protection.notify.delay", "3 seconds"), " ")[0];
protection_notify_delay_time = Util.split(getConfigString("protection.notify.delay", "3 seconds"), " ")[1];
protection_notify_delay = Util.toSeconds(protection_notify_delay_time, protection_notify_delay_length);
filter_action = Util.getAction(getConfigString("filter.action", "kick").toLowerCase());
filter_username = getConfigString("filter.username", "`~!@#$%^&*()-= + {[]}|\\:;\"<,>.?/");
filter_password = getConfigString("filter.password", "$&\"\\");
filter_whitelist= getConfigString("filter.whitelist", "");
} else if (config.equalsIgnoreCase("plugins")) {
CraftIRC_enabled = getConfigBoolean("CraftIRC.enabled", true);
CraftIRC_tag = getConfigString("CraftIRC.tag", "admin");
CraftIRC_prefix = getConfigString("CraftIRC.prefix", "%b%%green%[{PLUGIN}]%k%%b%");
/*
CraftIRC_messages_enabled = getConfigBoolean("CraftIRC.messages.enabled", true);
CraftIRC_messages_welcome_enabled = getConfigBoolean("CraftIRC.messages.welcome", true);
CraftIRC_messages_register_enabled = getConfigBoolean("CraftIRC.messages.register", true);
CraftIRC_messages_unregister_enabled = getConfigBoolean("CraftIRC.messages.unregister", true);
CraftIRC_messages_login_enabled = getConfigBoolean("CraftIRC.messages.login", true);
CraftIRC_messages_email_enabled = getConfigBoolean("CraftIRC.messages.email", true);
CraftIRC_messages_username_enabled = getConfigBoolean("CraftIRC.messages.username", true);
CraftIRC_messages_password_enabled = getConfigBoolean("CraftIRC.messages.password", true);
CraftIRC_messages_idle_enabled = getConfigBoolean("CraftIRC.messages.idle", true);
*/
} else if (config.equalsIgnoreCase("messages")) {
Messages.time_millisecond = Config.getConfigString("Core.time.millisecond.", "millisecond");
Messages.time_milliseconds = Config.getConfigString("Core.time.milliseconds", "milliseconds");
Messages.time_second = Config.getConfigString("Core.time.second.", "second");
Messages.time_seconds = Config.getConfigString("Core.time.seconds", "seconds");
Messages.time_minute = Config.getConfigString("Core.time.minute.", "minute");
Messages.time_minutes = Config.getConfigString("Core.time.minutes", "minutes");
Messages.time_hour = Config.getConfigString("Core.time.hour.", "hour");
Messages.time_hours = Config.getConfigString("Core.time.hours", "hours");
Messages.time_day = Config.getConfigString("Core.time.day", "day");
Messages.time_days = Config.getConfigString("Core.time.days", "days");
Messages.AuthDB_message_reload_success = Config.getConfigString("Core.reload.success", "AuthDB has successfully reloaded!");
Messages.AuthDB_message_database_failure = Config.getConfigString("Core.database.failure", "{RED}database connection failed! Access is denied! Contact admin.");
Messages.AuthDB_message_register_welcome = (String)Config.getConfigString("Core.register.welcome", "{YELLOW}Welcome {WHITE}guest{YELLOW}! Please use {REGISTERCMD} password email");
Messages.AuthDB_message_register_success = Config.getConfigString("Core.register.success", "{RED}You have been registered!");
Messages.AuthDB_message_register_failure = Config.getConfigString("Core.register.failure", "{RED}Registration failed!");
Messages.AuthDB_message_register_offline = Config.getConfigString("Core.register.offline", "{RED}Database is unavailable. Unable to verify password!");
Messages.AuthDB_message_register_exists = Config.getConfigString("Core.register.exists", "{RED}You are already registered!");
Messages.AuthDB_message_register_disabled = Config.getConfigString("Core.register.disabled", "{RED}Registration not allowed!");
Messages.AuthDB_message_register_usage = Config.getConfigString("Core.register.usage", "{RED}Correct usage is: /register password email");
Messages.AuthDB_message_register_timeout = Config.getConfigString("Core.register.timeout", "Kicked because you failed to register within {REGISTERTIMEOUT}.");
Messages.AuthDB_message_unregister_success = Config.getConfigString("Core.unregister.success", "{BRIGHTGREEN}Unregistered successfully!");
Messages.AuthDB_message_unregister_failure = Config.getConfigString("Core.unregister.failure", "{RED}An error occurred while unregistering!");
Messages.AuthDB_message_unregister_usage = Config.getConfigString("Core.unregister.usage", "{RED}Correct usage is: /unregister password");
Messages.AuthDB_message_logout_success = Config.getConfigString("Core.logout.success", "Successfully logged out!");
Messages.AuthDB_message_logout_failure = Config.getConfigString("Core.logout.failure", "You are not logged in!");
Messages.AuthDB_message_logout_admin = Config.getConfigString("Core.logout.admin", "You have been logged out by an admin.");
Messages.AuthDB_message_logout_admin_success = Config.getConfigString("Core.logout.adminsuccess", "Successfully logged out player, {PLAYER}.");
Messages.AuthDB_message_logout_admin_failure = Config.getConfigString("Core.logout.adminfailure", "You cannot logout player, {PLAYER}! That player is not logged in");
Messages.AuthDB_message_logout_admin_notfound = Config.getConfigString("Core.logout.adminnotfound", "Could not find player, {PLAYER}! Please try again.");
Messages.AuthDB_message_logout_usage = Config.getConfigString("Core.logout.usage", "{YELLOW}Correct usage is: {WHITE}{LOGOUTCMD}");
Messages.AuthDB_message_login_normal = Config.getConfigString("Core.login.normal", "{YELLOW}Welcome back {WHITE}{PLAYER}{YELLOW}! Please use /login password");
Messages.AuthDB_message_login_prompt = Config.getConfigString("Core.login.prompt", "{WHITE}Welcome {TEAL}{PLAYER}{WHITE}! Please enter your password:");
Messages.AuthDB_message_login_success = Config.getConfigString("Core.login.success", "{BRIGHTGREEN}Password accepted. Welcome!");
Messages.AuthDB_message_login_failure = Config.getConfigString("Core.login.failure", "{RED}Password incorrect, please try again.");
Messages.AuthDB_message_login_offline = Config.getConfigString("Core.login.offline", "{RED}Database is unavailable. Unable to verify password!");
Messages.AuthDB_message_login_authorized = Config.getConfigString("Core.login.authorized", "{BRIGHTGREEN}You are already logged in!");
Messages.AuthDB_message_login_notregistered = Config.getConfigString("Core.login.notregistered", "{RED}You are not registred yet!");
Messages.AuthDB_message_login_timeout = Config.getConfigString("Core.login.timeout", "Kicked because you failed to login within {LOGINTIMEOUT}.");
Messages.AuthDB_message_login_admin = Config.getConfigString("Core.login.admin", "You have been logged in by an admin.");
Messages.AuthDB_message_login_admin_success = Config.getConfigString("Core.login.admin.success", "Successfully logged in player, {PLAYER}.");
Messages.AuthDB_message_login_admin_failure = Config.getConfigString("Core.login.adminfailure", "You cannot login player {PLAYER}! That player is already logged in.");
Messages.AuthDB_message_login_admin_notfound = Config.getConfigString("Core.login.adminnotfound", "Could not find player, {PLAYER}! Please try again.");
Messages.AuthDB_message_login_usage = Config.getConfigString("Core.login.usage", "{RED}Correct usage is: /login password");
Messages.AuthDB_message_link_welcome = (String)Config.getConfigString("Core.link.welcome", "or {LINKCMD} otherusername password");
Messages.AuthDB_message_link_success = Config.getConfigString("Core.link.success", "{BRIGHTGREEN}You have successfully linked!. You are now logged in");
Messages.AuthDB_message_link_failure = Config.getConfigString("Core.link.failure", "{RED}Error while linking!");
Messages.AuthDB_message_link_exists = Config.getConfigString("Core.link.exists", "{RED}You are already linked to a username!");
Messages.AuthDB_message_link_duplicate = Config.getConfigString("Core.link.duplicate", "{RED}Username is already linked to another player!");
Messages.AuthDB_message_link_registred = Config.getConfigString("Core.link.registred", "{RED}You cannot link as this username is already registered!");
Messages.AuthDB_message_link_invaliduser = Config.getConfigString("Core.link.invaliduser", "{RED}You cannot link with yourself!");
Messages.AuthDB_message_link_renamed = Config.getConfigString("Core.link.renamed", "{YELLOW}{PLAYER} has been renamed to {DISPLAYNAME}.");
Messages.AuthDB_message_link_usage = Config.getConfigString("Core.link.usage", "{RED}Correct usage is: /link otherusername password");
Messages.AuthDB_message_unlink_success = Config.getConfigString("Core.unlink.success", "{BRIGHTGREEN}You have successfully unlinked!");
Messages.AuthDB_message_unlink_failure = Config.getConfigString("Core.unlink.failure", "{RED}Error while unlinking!");
Messages.AuthDB_message_unlink_nonexist = Config.getConfigString("Core.unlink.nonexist", "{RED}You do not have a linked username!");
Messages.AuthDB_message_unlink_invaliduser = Config.getConfigString("Core.unlink.invaliduser", "{RED}Invalid linked username!");
Messages.AuthDB_message_unlink_invalidpass = Config.getConfigString("Core.unlink.invalidpass", "{RED}Invalid linked password!");
Messages.AuthDB_message_unlink_renamed = Config.getConfigString("Core.unlink.renamed", "{YELLOW}{DISPLAYNAME} has been renamed to {PLAYER}.");
Messages.AuthDB_message_unlink_usage = Config.getConfigString("Core.unlink.usage", "{RED}Correct usage is: /unlink otherusername password");
Messages.AuthDB_message_email_required = Config.getConfigString("Core.email.required", "{RED}Email required for registration!");
Messages.AuthDB_message_email_invalid = Config.getConfigString("Core.email.invalid", "{RED}Invalid email! Please try again!");
Messages.AuthDB_message_email_badcharacters = Config.getConfigString("Core.email.badcharacters", "{RED}Email contains bad characters! {BADCHARACTERS}!");
Messages.AuthDB_message_filter_renamed = Config.getConfigString("Core.filter.renamed", "{RED}{PLAYER} renamed to {PLAYERNEW} due to bad characters: {USERBADCHARACTERS}.");
Messages.AuthDB_message_filter_username = Config.getConfigString("Core.filter.username", "{RED}Username contains bad characters: {USERBADCHARACTERS}!");
Messages.AuthDB_message_filter_password = Config.getConfigString("Core.filter.password", "{RED}Password contains bad characters: {PASSBADCHARACTERS}!");
Messages.AuthDB_message_filter_whitelist = Config.getConfigString("Core.filter.whitelist", "{BRIGHTGREEN}{PLAYER} is on the filter {WHITE}whitelist{BRIGHTGREEN}, bypassing restrictions!");
Messages.AuthDB_message_username_minimum = Config.getConfigString("Core.username.minimum", "{RED}Your username does not meet the minimum requirement of {USERMIN} characters!");
Messages.AuthDB_message_username_maximum = Config.getConfigString("Core.username.maximum", "{RED}Your username does not meet the maximum requirement of {USERMAX} characters!");
Messages.AuthDB_message_password_minimum = Config.getConfigString("Core.password.minimum", "{RED}Your password does not meet the minimum requirement of {PASSMIN} characters!");
Messages.AuthDB_message_password_maximum = Config.getConfigString("Core.password.maximum", "{RED}Your password does not meet the maximum requirement of {PASSMAX} characters!");
Messages.AuthDB_message_password_success = Config.getConfigString("Core.password.success", "{BRIGHTGREEN}Password changed successfully!");
Messages.AuthDB_message_password_failure = Config.getConfigString("Core.password.failure", "{RED}Error! Password change failed!");
Messages.AuthDB_message_password_notregistered = Config.getConfigString("Core.password.notregistered", "{RED}Register first!");
Messages.AuthDB_message_password_usage = Config.getConfigString("Core.password.usage", "{RED}Correct usage is: /password oldpassword password");
Messages.AuthDB_message_session_valid = Config.getConfigString("Core.session.valid", "{BRIGHTGREEN}Hey, I remember you! You are logged in!");
Messages.AuthDB_message_session_protected = Config.getConfigString("Core.session.protected", "{RED}Sorry, a player with that name is already logged in on this server.");
Messages.AuthDB_message_protection_denied = Config.getConfigString("Core.protection.denied", "You do not have permission to use that command.");
Messages.AuthDB_message_protection_notauthorized = Config.getConfigString("Core.protection.notauthorized", "{RED}You are not authorized to do that!");
Messages.CraftIRC_message_status_join = Config.getConfigString("Plugins.CraftIRC.status.join", "{PLAYER} has joined the server.");
Messages.CraftIRC_message_status_quit = Config.getConfigString("Plugins.CraftIRC.status.quit", "{PLAYER} has quit the server.");
Messages.CraftIRC_message_register_success = Config.getConfigString("Plugins.CraftIRC.register.success", "{PLAYER} just registered successfully!");
Messages.CraftIRC_message_register_failure = Config.getConfigString("Plugins.CraftIRC.register.failure", "{PLAYER} had some errors while registering!");
Messages.CraftIRC_message_register_registered = Config.getConfigString("Plugins.CraftIRC.register.registered", "{PLAYER} had a lapse in memory and tried to register again.");
Messages.CraftIRC_message_password_success = Config.getConfigString("Plugins.CraftIRC.password.success", "{PLAYER} logged in successfully!");
Messages.CraftIRC_message_password_failure = Config.getConfigString("Plugins.CraftIRC.password.failure", "{PLAYER} tried to login with the wrong password!");
Messages.CraftIRC_message_idle_kicked = Config.getConfigString("Plugins.CraftIRC.idle.kicked", "{PLAYER} was kicked due to bad characters in username!");
Messages.CraftIRC_message_idle_whitelist = Config.getConfigString("Plugins.CraftIRC.idle.whitelist", "{PLAYER} is on the on bad characters whitelist, bypassing restictions!");
Messages.CraftIRC_message_filter_renamed = Config.getConfigString("Plugins.CraftIRC.filter.renamed", "{PLAYER} renamed to {PLAYERNEW} due to bad characters.");
Messages.CraftIRC_message_filter_kicked = Config.getConfigString("Plugins.CraftIRC.filter.kicked", "{PLAYER} was kicked due to bad characters in username!");
Messages.CraftIRC_message_filter_whitelist = Config.getConfigString("Plugins.CraftIRC.filter.whitelist", "{PLAYER} is on the on bad characters whitelist, bypassing restictions!");
} else if (config.equalsIgnoreCase("commands")) {
commands_user_register = Config.getConfigString("Core.commands.user.register", "/register");
commands_user_link = Config.getConfigString("Core.commands.user.link", "/link");
commands_user_unlink = Config.getConfigString("Core.commands.user.unlink", "/unlink");
commands_user_login = Config.getConfigString("Core.commands.user.login", "/login");
commands_user_logout = Config.getConfigString("Core.commands.user.logout", "/logout");
commands_admin_login = Config.getConfigString("Core.commands.admin.login", "/authdb login");
commands_admin_logout = Config.getConfigString("Core.commands.admin.logout", "/authdb logout");
commands_admin_reload = Config.getConfigString("Core.commands.admin.reload", "/authdb reload");
aliases_user_register = Config.getConfigString("Core.aliases.user.register", "/r");
aliases_user_link = Config.getConfigString("Core.aliases.user.link", "/li");
aliases_user_unlink = Config.getConfigString("Core.aliases.user.unlink", "/ul");
aliases_user_login = Config.getConfigString("Core.aliases.user.login", "/l");
aliases_user_logout = Config.getConfigString("Core.aliases.user.logout", "/lo");
aliases_admin_login = Config.getConfigString("Core.aliases.admin.login", "/al");
aliases_admin_logout = Config.getConfigString("Core.aliases.admin.logout", "/alo");
aliases_admin_reload = Config.getConfigString("Core.aliases.admin.reload", "/ar");
}
}
|
diff --git a/extension/eevolution/libero/src/main/java/org/eevolution/form/VOrderDistributionReceipt.java b/extension/eevolution/libero/src/main/java/org/eevolution/form/VOrderDistributionReceipt.java
index dd4a028..d460f4d 100644
--- a/extension/eevolution/libero/src/main/java/org/eevolution/form/VOrderDistributionReceipt.java
+++ b/extension/eevolution/libero/src/main/java/org/eevolution/form/VOrderDistributionReceipt.java
@@ -1,550 +1,549 @@
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* This program is free software; you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. 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., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* Copyright (C) 2003-2007 e-Evolution,SC. All Rights Reserved. *
* Contributor(s): [email protected] *
*****************************************************************************/
package org.eevolution.form;
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.PropertyChangeEvent;
import java.beans.VetoableChangeListener;
import java.math.BigDecimal;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Properties;
import java.util.logging.Level;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import org.adempiere.exceptions.AdempiereException;
import org.adempiere.plaf.AdempierePLAF;
import org.compiere.apps.ADialog;
import org.compiere.apps.ADialogDialog;
import org.compiere.apps.ConfirmPanel;
import org.compiere.apps.StatusBar;
import org.compiere.apps.form.FormFrame;
import org.compiere.apps.form.FormPanel;
import org.compiere.grid.ed.VDate;
import org.compiere.grid.ed.VLookup;
import org.compiere.minigrid.IDColumn;
import org.compiere.minigrid.MiniTable;
import org.compiere.model.MColumn;
import org.compiere.model.MLookup;
import org.compiere.model.MLookupFactory;
import org.compiere.model.MMovement;
import org.compiere.model.MMovementLine;
import org.compiere.model.MQuery;
import org.compiere.model.PrintInfo;
import org.compiere.plaf.CompiereColor;
import org.compiere.print.MPrintFormat;
import org.compiere.print.ReportEngine;
import org.compiere.print.Viewer;
import org.compiere.swing.CLabel;
import org.compiere.swing.CPanel;
import org.compiere.swing.CTabbedPane;
import org.compiere.swing.CTextPane;
import org.compiere.util.CLogger;
import org.compiere.util.DB;
import org.compiere.util.DisplayType;
import org.compiere.util.Env;
import org.compiere.util.Language;
import org.compiere.util.Msg;
import org.compiere.util.Trx;
import org.eevolution.model.MDDOrder;
import org.eevolution.model.MDDOrderLine;
/**
* Create Movement for Material Receipt from Distribution Order
*
* @author [email protected]
* @version $Id: VOrderDistributionReceipt,v 1.0
*/
public class VOrderDistributionReceipt extends CPanel
implements FormPanel, ActionListener, VetoableChangeListener,
ChangeListener, TableModelListener
{
/**
* Initialize Panel
* @param WindowNo window
* @param frame frame
*/
public void init (int WindowNo, FormFrame frame)
{
log.info("");
m_WindowNo = WindowNo;
m_frame = frame;
Env.setContext(Env.getCtx(), m_WindowNo, "IsSOTrx", "Y");
try
{
fillPicks();
jbInit();
dynInit();
frame.getContentPane().add(tabbedPane, BorderLayout.CENTER);
frame.getContentPane().add(statusBar, BorderLayout.SOUTH);
}
catch(Exception ex)
{
log.log(Level.SEVERE, "init", ex);
}
} // init
/** Window No */
private int m_WindowNo = 0;
/** FormFrame */
private FormFrame m_frame;
private boolean m_selectionActive = true;
private Object m_DD_Order_ID = null;
private Object m_MovementDate = null;
/** Logger */
private static CLogger log = CLogger.getCLogger(VOrderDistributionReceipt.class);
//
private CTabbedPane tabbedPane = new CTabbedPane();
private CPanel selPanel = new CPanel();
private CPanel selNorthPanel = new CPanel();
private BorderLayout selPanelLayout = new BorderLayout();
private CLabel lOrder = new CLabel();
private VLookup fOrder;
private VDate fMovementDate = new VDate("MovementDate", true, false, true, DisplayType.Date, "MovementDate");
private CLabel lMovementDate = new CLabel(Msg.translate(Env.getCtx(),"MovementDate"));
private FlowLayout northPanelLayout = new FlowLayout();
private ConfirmPanel confirmPanelSel = new ConfirmPanel(true);
private ConfirmPanel confirmPanelGen = new ConfirmPanel(false, true, false, false, false, false, true);
private StatusBar statusBar = new StatusBar();
private CPanel genPanel = new CPanel();
private BorderLayout genLayout = new BorderLayout();
private CTextPane info = new CTextPane();
private JScrollPane scrollPane = new JScrollPane();
private MiniTable miniTable = new MiniTable();
/** User selection */
private ArrayList<Integer> selection = null;
/**
* Static Init.
* <pre>
* selPanel (tabbed)
* fOrg, fBPartner
* scrollPane & miniTable
* genPanel
* info
* </pre>
* @throws Exception
*/
void jbInit() throws Exception
{
CompiereColor.setBackground(this);
//
selPanel.setLayout(selPanelLayout);
lOrder.setLabelFor(fOrder);
selNorthPanel.setLayout(northPanelLayout);
northPanelLayout.setAlignment(FlowLayout.LEFT);
tabbedPane.add(selPanel, Msg.getMsg(Env.getCtx(), "Select"));
selPanel.add(selNorthPanel, BorderLayout.NORTH);
selNorthPanel.add(lOrder, null);
selNorthPanel.add(fOrder, null);
selNorthPanel.add(lMovementDate, null);
selNorthPanel.add(fMovementDate, null);
selPanel.setName("selPanel");
selPanel.add(confirmPanelSel, BorderLayout.SOUTH);
selPanel.add(scrollPane, BorderLayout.CENTER);
scrollPane.getViewport().add(miniTable, null);
confirmPanelSel.addActionListener(this);
//
tabbedPane.add(genPanel, Msg.getMsg(Env.getCtx(), "Generate"));
genPanel.setLayout(genLayout);
genPanel.add(info, BorderLayout.CENTER);
genPanel.setEnabled(false);
info.setBackground(AdempierePLAF.getFieldBackground_Inactive());
info.setEditable(false);
genPanel.add(confirmPanelGen, BorderLayout.SOUTH);
confirmPanelGen.addActionListener(this);
} // jbInit
/**
* Fill Picks.
* Column_ID from C_Order
* @throws Exception if Lookups cannot be initialized
*/
private void fillPicks() throws Exception
{
Language language = Language.getLoginLanguage();
MLookup orderL = MLookupFactory.get(Env.getCtx(), m_WindowNo, MColumn.getColumn_ID(MDDOrder.Table_Name,MDDOrder.COLUMNNAME_DD_Order_ID) , DisplayType.Search , language , MDDOrder.COLUMNNAME_DD_Order_ID , 0 , false, "DocStatus='CO'");
fOrder = new VLookup (MDDOrder.COLUMNNAME_DD_Order_ID, true, false, true, orderL);
lOrder.setText(Msg.translate(Env.getCtx(), MDDOrder.COLUMNNAME_DD_Order_ID));
fOrder.addVetoableChangeListener(this);
Timestamp today = new Timestamp (System.currentTimeMillis());
m_MovementDate = today;
fMovementDate.setValue(today);
fMovementDate.addVetoableChangeListener(this);
} // fillPicks
/**
* Dynamic Init.
* - Create GridController & Panel
* - AD_Column_ID from C_Order
*/
private void dynInit()
{
// create Columns
miniTable.addColumn("DD_Order_ID");
miniTable.addColumn("QtyInTransit");
miniTable.addColumn("C_UOM_ID");
miniTable.addColumn("Value");
miniTable.addColumn("M_Product_ID");
miniTable.addColumn("M_WarehouseSource_ID");
//miniTable.addColumn("TotalLines");
//
miniTable.setMultiSelection(true);
miniTable.setRowSelectionAllowed(true);
// set details
miniTable.setColumnClass(0, IDColumn.class, false, " ");
miniTable.setColumnClass(1, BigDecimal.class, false, Msg.translate(Env.getCtx(), "QtyInTransit")); //Qty
miniTable.setColumnClass(2, String.class, true, Msg.translate(Env.getCtx(), "C_UOM_ID")); //UM
miniTable.setColumnClass(3, String.class, true, Msg.translate(Env.getCtx(), "M_Product_ID")); // Product
miniTable.setColumnClass(4, String.class, true, Msg.translate(Env.getCtx(), "Value")); // Line
miniTable.setColumnClass(5, String.class, true, Msg.translate(Env.getCtx(), "WarehouseSource"));
//miniTable.setColumnClass(6, BigDecimal.class, true, Msg.translate(Env.getCtx(), "TotalLines"));
//
miniTable.autoSize();
miniTable.getModel().addTableModelListener(this);
// Info
statusBar.setStatusLine(Msg.getMsg(Env.getCtx(), "InOutGenerateSel"));//@@
statusBar.setStatusDB(" ");
// Tabbed Pane Listener
tabbedPane.addChangeListener(this);
} // dynInit
/**
* Get SQL for Orders that needs to be shipped
* @return sql
*/
private String getOrderSQL()
{
// Create SQL
StringBuffer sql = new StringBuffer(
"SELECT ol.DD_OrderLine_ID, ol.QtyInTransit , uom.Name , p.Value ,p.Name , w.Name "
+ "FROM DD_OrderLine ol INNER JOIN DD_Order o ON (o.DD_Order_ID=ol.DD_Order_ID) INNER JOIN M_Product p ON (p.M_Product_ID=ol.M_Product_ID) "
+ " INNER JOIN C_UOM uom ON (uom.C_UOM_ID=ol.C_UOM_ID)"
+ " INNER JOIN M_Locator l ON (l.M_Locator_ID = ol.M_Locator_ID)"
+ " INNER JOIN M_Warehouse w ON (w.M_Warehouse_ID = l.M_Warehouse_ID)"
+ " WHERE o.DocStatus= 'CO' AND ol.QtyInTransit > 0 AND o.DD_Order_ID = ? ");
return sql.toString();
}
/**
* Query Info
*/
private void executeQuery()
{
log.info("");
String sql = "";
if (m_DD_Order_ID == null)
return;
sql = getOrderSQL();
log.fine(sql);
// reset table
int row = 0;
miniTable.setRowCount(row);
// Execute
try
{
PreparedStatement pstmt = DB.prepareStatement(sql.toString(), null);
pstmt.setInt(1, Integer.parseInt(m_DD_Order_ID.toString()));
ResultSet rs = pstmt.executeQuery();
//
while (rs.next())
{
// extend table
miniTable.setRowCount(row+1);
// set values
miniTable.setValueAt(new IDColumn(rs.getInt(1)), row, 0); // DD_Order_ID
miniTable.setValueAt(rs.getBigDecimal(2), row, 1); // QtyInTransit
miniTable.setValueAt(rs.getString(3), row, 2); // C_UOM_ID
miniTable.setValueAt(rs.getString(4), row, 4); // Value
miniTable.setValueAt(rs.getString(5), row, 3); // M_Product_ID
miniTable.setValueAt(rs.getString(6), row, 5); // WarehouseSource
//miniTable.setValueAt(rs.getBigDecimal(7), row, 6); // QtyBackOrder
// prepare next
row++;
}
rs.close();
pstmt.close();
}
catch (SQLException e)
{
log.log(Level.SEVERE, sql.toString(), e);
}
//
miniTable.autoSize();
// statusBar.setStatusDB(String.valueOf(miniTable.getRowCount()));
} // executeQuery
/**
* Dispose
*/
public void dispose()
{
if (m_frame != null)
m_frame.dispose();
m_frame = null;
} // dispose
/**
* Action Listener
* @param e event
*/
public void actionPerformed (ActionEvent e)
{
log.info("Cmd=" + e.getActionCommand());
//
if (e.getActionCommand().equals(ConfirmPanel.A_CANCEL))
{
dispose();
return;
}
//
saveSelection();
if (selection != null
&& selection.size() > 0
&& m_selectionActive // on selection tab
&& m_DD_Order_ID != null && m_MovementDate != null)
generateMovements ();
else
dispose();
} // actionPerformed
/**
* Vetoable Change Listener - requery
* @param e event
*/
public void vetoableChange(PropertyChangeEvent e)
{
log.info(e.getPropertyName() + "=" + e.getNewValue());
if (e.getPropertyName().equals("DD_Order_ID"))
m_DD_Order_ID = e.getNewValue();
if(e.getPropertyName().equals("MovementDate"))
m_MovementDate = e.getNewValue();
executeQuery();
} // vetoableChange
/**
* Change Listener (Tab changed)
* @param e event
*/
public void stateChanged (ChangeEvent e)
{
int index = tabbedPane.getSelectedIndex();
m_selectionActive = (index == 0);
} // stateChanged
/**
* Table Model Listener
* @param e event
*/
public void tableChanged(TableModelEvent e)
{
int rowsSelected = 0;
int rows = miniTable.getRowCount();
for (int i = 0; i < rows; i++)
{
IDColumn id = (IDColumn)miniTable.getValueAt(i, 0); // ID in column 0
if (id != null && id.isSelected())
rowsSelected++;
}
statusBar.setStatusDB(" " + rowsSelected + " ");
} // tableChanged
/**
* Save Selection & return selecion Query or ""
* @return where clause like C_Order_ID IN (...)
*/
private void saveSelection()
{
log.info("");
// ID selection may be pending
miniTable.editingStopped(new ChangeEvent(this));
// Array of Integers
ArrayList<Integer> results = new ArrayList<Integer>();
selection = null;
// Get selected entries
int rows = miniTable.getRowCount();
for (int i = 0; i < rows; i++)
{
IDColumn id = (IDColumn)miniTable.getValueAt(i, 0); // ID in column 0
// log.fine( "Row=" + i + " - " + id);
if (id != null && id.isSelected())
results.add(id.getRecord_ID());
}
if (results.size() == 0)
return;
log.config("Selected #" + results.size());
selection = results;
} // saveSelection
/**************************************************************************
* Generate Shipments
*/
private void generateMovements ()
{
log.info("DD_Order_ID=" + m_DD_Order_ID);
log.info("MovementDate" + m_MovementDate);
String trxName = Trx.createTrxName("IOG");
Trx trx = Trx.get(trxName, true); //trx needs to be committed too
m_selectionActive = false; // prevents from being called twice
statusBar.setStatusLine(Msg.translate(Env.getCtx(), "M_Movement_ID"));
statusBar.setStatusDB(String.valueOf(selection.size()));
if (selection.size() <= 0)
return;
Properties m_ctx = Env.getCtx();
Timestamp MovementDate = (Timestamp) m_MovementDate;
MDDOrder order = new MDDOrder(m_ctx , Integer.parseInt(m_DD_Order_ID.toString()), trxName);
MMovement movement = new MMovement(m_ctx , 0 , trxName);
movement.setDD_Order_ID(order.getDD_Order_ID());
movement.setAD_User_ID(order.getAD_User_ID());
movement.setPOReference(order.getPOReference());
- movement.setReversal_ID(order.getSalesRep_ID());
+ movement.setReversal_ID(0);
movement.setM_Shipper_ID(order.getM_Shipper_ID());
movement.setDescription(order.getDescription());
- //movement.setDateReceived(DateReceived);
movement.setC_BPartner_ID(order.getC_BPartner_ID());
movement.setC_BPartner_Location_ID(order.getC_BPartner_Location_ID());
movement.setAD_Org_ID(order.getAD_Org_ID());
movement.setAD_OrgTrx_ID(order.getAD_OrgTrx_ID());
movement.setAD_User_ID(order.getAD_User_ID());
movement.setC_Activity_ID(order.getC_Activity_ID());
movement.setC_Campaign_ID(order.getC_Campaign_ID());
movement.setC_Project_ID(order.getC_Project_ID());
movement.setMovementDate(MovementDate);
movement.setDeliveryRule(order.getDeliveryRule());
movement.setDeliveryViaRule(order.getDeliveryViaRule());
movement.setDocAction(MMovement.ACTION_Prepare);
movement.setDocStatus(MMovement.DOCSTATUS_Drafted);
if (!movement.save())
throw new AdempiereException("Can not save Inventory Move");
for (int i = 0 ; i < selection.size() ; i++ )
{
int DD_OrderLine_ID = selection.get(i);
MDDOrderLine oline = new MDDOrderLine(m_ctx, DD_OrderLine_ID, trxName);
MMovementLine line = new MMovementLine(movement);
line.setM_Product_ID(oline.getM_Product_ID());
BigDecimal QtyDeliver = (BigDecimal) miniTable.getValueAt(i, 1);
if(QtyDeliver == null | QtyDeliver.compareTo(oline.getQtyInTransit()) > 0)
throw new AdempiereException("Error in Qty");
line.setOrderLine(oline, QtyDeliver, true);
line.saveEx();
}
movement.completeIt();
movement.setDocAction(MMovement.ACTION_Complete);
movement.setDocStatus(MMovement.DOCACTION_Close);
movement.save();
trx.commit();
generateMovements_complete(movement);
//
} // generateMovements
/**
* Complete generating movements.
* @param movement
*/
private void generateMovements_complete (MMovement movement)
{
// Switch Tabs
tabbedPane.setSelectedIndex(1);
StringBuffer iText = new StringBuffer();
iText.append("<b>").append("")
.append("</b><br>")
.append(Msg.translate(Env.getCtx(), "DocumentNo") +" : " +movement.getDocumentNo())
// Shipments are generated depending on the Delivery Rule selection in the Order
.append("<br>")
.append("");
info.setText(iText.toString());
confirmPanelGen.getOKButton().setEnabled(false);
// OK to print shipments
if (ADialog.ask(m_WindowNo, this, "PrintShipments"))
{
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
int retValue = ADialogDialog.A_CANCEL; // see also ProcessDialog.printShipments/Invoices
do
{
MPrintFormat format = MPrintFormat.get(Env.getCtx(), MPrintFormat.getPrintFormat_ID("Inventory Move Hdr (Example)", MMovement.Table_ID, 0), false);
MQuery query = new MQuery(MMovement.Table_Name);
query.addRestriction(MMovement.COLUMNNAME_M_Movement_ID, MQuery.EQUAL, movement.getM_Movement_ID());
// Engine
PrintInfo info = new PrintInfo(MMovement.Table_Name,MMovement.Table_ID, movement.getM_Movement_ID());
ReportEngine re = new ReportEngine(Env.getCtx(), format, query, info);
re.print();
new Viewer(re);
ADialogDialog d = new ADialogDialog (m_frame,
Env.getHeader(Env.getCtx(), m_WindowNo),
Msg.getMsg(Env.getCtx(), "PrintoutOK?"),
JOptionPane.QUESTION_MESSAGE);
retValue = d.getReturnCode();
}
while (retValue == ADialogDialog.A_CANCEL);
setCursor(Cursor.getDefaultCursor());
} // OK to print shipments
//
confirmPanelGen.getOKButton().setEnabled(true);
} // generateMovement_complete
} // VOrderDistributionReceipt
| false | true | private void generateMovements ()
{
log.info("DD_Order_ID=" + m_DD_Order_ID);
log.info("MovementDate" + m_MovementDate);
String trxName = Trx.createTrxName("IOG");
Trx trx = Trx.get(trxName, true); //trx needs to be committed too
m_selectionActive = false; // prevents from being called twice
statusBar.setStatusLine(Msg.translate(Env.getCtx(), "M_Movement_ID"));
statusBar.setStatusDB(String.valueOf(selection.size()));
if (selection.size() <= 0)
return;
Properties m_ctx = Env.getCtx();
Timestamp MovementDate = (Timestamp) m_MovementDate;
MDDOrder order = new MDDOrder(m_ctx , Integer.parseInt(m_DD_Order_ID.toString()), trxName);
MMovement movement = new MMovement(m_ctx , 0 , trxName);
movement.setDD_Order_ID(order.getDD_Order_ID());
movement.setAD_User_ID(order.getAD_User_ID());
movement.setPOReference(order.getPOReference());
movement.setReversal_ID(order.getSalesRep_ID());
movement.setM_Shipper_ID(order.getM_Shipper_ID());
movement.setDescription(order.getDescription());
//movement.setDateReceived(DateReceived);
movement.setC_BPartner_ID(order.getC_BPartner_ID());
movement.setC_BPartner_Location_ID(order.getC_BPartner_Location_ID());
movement.setAD_Org_ID(order.getAD_Org_ID());
movement.setAD_OrgTrx_ID(order.getAD_OrgTrx_ID());
movement.setAD_User_ID(order.getAD_User_ID());
movement.setC_Activity_ID(order.getC_Activity_ID());
movement.setC_Campaign_ID(order.getC_Campaign_ID());
movement.setC_Project_ID(order.getC_Project_ID());
movement.setMovementDate(MovementDate);
movement.setDeliveryRule(order.getDeliveryRule());
movement.setDeliveryViaRule(order.getDeliveryViaRule());
movement.setDocAction(MMovement.ACTION_Prepare);
movement.setDocStatus(MMovement.DOCSTATUS_Drafted);
if (!movement.save())
throw new AdempiereException("Can not save Inventory Move");
for (int i = 0 ; i < selection.size() ; i++ )
{
int DD_OrderLine_ID = selection.get(i);
MDDOrderLine oline = new MDDOrderLine(m_ctx, DD_OrderLine_ID, trxName);
MMovementLine line = new MMovementLine(movement);
line.setM_Product_ID(oline.getM_Product_ID());
BigDecimal QtyDeliver = (BigDecimal) miniTable.getValueAt(i, 1);
if(QtyDeliver == null | QtyDeliver.compareTo(oline.getQtyInTransit()) > 0)
throw new AdempiereException("Error in Qty");
line.setOrderLine(oline, QtyDeliver, true);
line.saveEx();
}
movement.completeIt();
movement.setDocAction(MMovement.ACTION_Complete);
movement.setDocStatus(MMovement.DOCACTION_Close);
movement.save();
trx.commit();
generateMovements_complete(movement);
//
} // generateMovements
| private void generateMovements ()
{
log.info("DD_Order_ID=" + m_DD_Order_ID);
log.info("MovementDate" + m_MovementDate);
String trxName = Trx.createTrxName("IOG");
Trx trx = Trx.get(trxName, true); //trx needs to be committed too
m_selectionActive = false; // prevents from being called twice
statusBar.setStatusLine(Msg.translate(Env.getCtx(), "M_Movement_ID"));
statusBar.setStatusDB(String.valueOf(selection.size()));
if (selection.size() <= 0)
return;
Properties m_ctx = Env.getCtx();
Timestamp MovementDate = (Timestamp) m_MovementDate;
MDDOrder order = new MDDOrder(m_ctx , Integer.parseInt(m_DD_Order_ID.toString()), trxName);
MMovement movement = new MMovement(m_ctx , 0 , trxName);
movement.setDD_Order_ID(order.getDD_Order_ID());
movement.setAD_User_ID(order.getAD_User_ID());
movement.setPOReference(order.getPOReference());
movement.setReversal_ID(0);
movement.setM_Shipper_ID(order.getM_Shipper_ID());
movement.setDescription(order.getDescription());
movement.setC_BPartner_ID(order.getC_BPartner_ID());
movement.setC_BPartner_Location_ID(order.getC_BPartner_Location_ID());
movement.setAD_Org_ID(order.getAD_Org_ID());
movement.setAD_OrgTrx_ID(order.getAD_OrgTrx_ID());
movement.setAD_User_ID(order.getAD_User_ID());
movement.setC_Activity_ID(order.getC_Activity_ID());
movement.setC_Campaign_ID(order.getC_Campaign_ID());
movement.setC_Project_ID(order.getC_Project_ID());
movement.setMovementDate(MovementDate);
movement.setDeliveryRule(order.getDeliveryRule());
movement.setDeliveryViaRule(order.getDeliveryViaRule());
movement.setDocAction(MMovement.ACTION_Prepare);
movement.setDocStatus(MMovement.DOCSTATUS_Drafted);
if (!movement.save())
throw new AdempiereException("Can not save Inventory Move");
for (int i = 0 ; i < selection.size() ; i++ )
{
int DD_OrderLine_ID = selection.get(i);
MDDOrderLine oline = new MDDOrderLine(m_ctx, DD_OrderLine_ID, trxName);
MMovementLine line = new MMovementLine(movement);
line.setM_Product_ID(oline.getM_Product_ID());
BigDecimal QtyDeliver = (BigDecimal) miniTable.getValueAt(i, 1);
if(QtyDeliver == null | QtyDeliver.compareTo(oline.getQtyInTransit()) > 0)
throw new AdempiereException("Error in Qty");
line.setOrderLine(oline, QtyDeliver, true);
line.saveEx();
}
movement.completeIt();
movement.setDocAction(MMovement.ACTION_Complete);
movement.setDocStatus(MMovement.DOCACTION_Close);
movement.save();
trx.commit();
generateMovements_complete(movement);
//
} // generateMovements
|
diff --git a/java/src/com/android/inputmethod/keyboard/Key.java b/java/src/com/android/inputmethod/keyboard/Key.java
index 91e81f347..ed873a70d 100644
--- a/java/src/com/android/inputmethod/keyboard/Key.java
+++ b/java/src/com/android/inputmethod/keyboard/Key.java
@@ -1,727 +1,728 @@
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.android.inputmethod.keyboard;
import static com.android.inputmethod.keyboard.Keyboard.CODE_OUTPUT_TEXT;
import static com.android.inputmethod.keyboard.Keyboard.CODE_SHIFT;
import static com.android.inputmethod.keyboard.Keyboard.CODE_SWITCH_ALPHA_SYMBOL;
import static com.android.inputmethod.keyboard.Keyboard.CODE_UNSPECIFIED;
import static com.android.inputmethod.keyboard.internal.KeyboardIconsSet.ICON_UNDEFINED;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
import android.util.Xml;
import com.android.inputmethod.keyboard.internal.KeySpecParser;
import com.android.inputmethod.keyboard.internal.KeySpecParser.MoreKeySpec;
import com.android.inputmethod.keyboard.internal.KeyStyles.KeyStyle;
import com.android.inputmethod.keyboard.internal.KeyboardIconsSet;
import com.android.inputmethod.latin.R;
import com.android.inputmethod.latin.StringUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.util.Arrays;
import java.util.Locale;
/**
* Class for describing the position and characteristics of a single key in the keyboard.
*/
public class Key {
private static final String TAG = Key.class.getSimpleName();
/**
* The key code (unicode or custom code) that this key generates.
*/
public final int mCode;
public final int mAltCode;
/** Label to display */
public final String mLabel;
/** Hint label to display on the key in conjunction with the label */
public final String mHintLabel;
/** Flags of the label */
private final int mLabelFlags;
private static final int LABEL_FLAGS_ALIGN_LEFT = 0x01;
private static final int LABEL_FLAGS_ALIGN_RIGHT = 0x02;
private static final int LABEL_FLAGS_ALIGN_LEFT_OF_CENTER = 0x08;
private static final int LABEL_FLAGS_FONT_NORMAL = 0x10;
private static final int LABEL_FLAGS_FONT_MONO_SPACE = 0x20;
// Start of key text ratio enum values
private static final int LABEL_FLAGS_FOLLOW_KEY_TEXT_RATIO_MASK = 0x1C0;
private static final int LABEL_FLAGS_FOLLOW_KEY_LARGE_LETTER_RATIO = 0x40;
private static final int LABEL_FLAGS_FOLLOW_KEY_LETTER_RATIO = 0x80;
private static final int LABEL_FLAGS_FOLLOW_KEY_LABEL_RATIO = 0xC0;
private static final int LABEL_FLAGS_FOLLOW_KEY_LARGE_LABEL_RATIO = 0x100;
private static final int LABEL_FLAGS_FOLLOW_KEY_HINT_LABEL_RATIO = 0x140;
// End of key text ratio mask enum values
private static final int LABEL_FLAGS_HAS_POPUP_HINT = 0x200;
private static final int LABEL_FLAGS_HAS_SHIFTED_LETTER_HINT = 0x400;
private static final int LABEL_FLAGS_HAS_HINT_LABEL = 0x800;
private static final int LABEL_FLAGS_WITH_ICON_LEFT = 0x1000;
private static final int LABEL_FLAGS_WITH_ICON_RIGHT = 0x2000;
private static final int LABEL_FLAGS_AUTO_X_SCALE = 0x4000;
private static final int LABEL_FLAGS_PRESERVE_CASE = 0x8000;
private static final int LABEL_FLAGS_SHIFTED_LETTER_ACTIVATED = 0x10000;
private static final int LABEL_FLAGS_FROM_CUSTOM_ACTION_LABEL = 0x20000;
private static final int LABEL_FLAGS_DISABLE_HINT_LABEL = 0x40000000;
private static final int LABEL_FLAGS_DISABLE_ADDITIONAL_MORE_KEYS = 0x80000000;
/** Icon to display instead of a label. Icon takes precedence over a label */
private final int mIconId;
/** Icon for disabled state */
private final int mDisabledIconId;
/** Preview version of the icon, for the preview popup */
private final int mPreviewIconId;
/** Width of the key, not including the gap */
public final int mWidth;
/** Height of the key, not including the gap */
public final int mHeight;
/** The horizontal gap around this key */
public final int mHorizontalGap;
/** The vertical gap below this key */
public final int mVerticalGap;
/** The visual insets */
public final int mVisualInsetsLeft;
public final int mVisualInsetsRight;
/** X coordinate of the key in the keyboard layout */
public final int mX;
/** Y coordinate of the key in the keyboard layout */
public final int mY;
/** Hit bounding box of the key */
public final Rect mHitBox = new Rect();
/** Text to output when pressed. This can be multiple characters, like ".com" */
public final CharSequence mOutputText;
/** More keys */
public final MoreKeySpec[] mMoreKeys;
/** More keys column number and flags */
private final int mMoreKeysColumnAndFlags;
private static final int MORE_KEYS_COLUMN_MASK = 0x000000ff;
private static final int MORE_KEYS_FLAGS_FIXED_COLUMN_ORDER = 0x80000000;
private static final int MORE_KEYS_FLAGS_HAS_LABELS = 0x40000000;
private static final int MORE_KEYS_FLAGS_NEEDS_DIVIDERS = 0x20000000;
private static final int MORE_KEYS_FLAGS_EMBEDDED_MORE_KEY = 0x10000000;
private static final String MORE_KEYS_AUTO_COLUMN_ORDER = "!autoColumnOrder!";
private static final String MORE_KEYS_FIXED_COLUMN_ORDER = "!fixedColumnOrder!";
private static final String MORE_KEYS_HAS_LABELS = "!hasLabels!";
private static final String MORE_KEYS_NEEDS_DIVIDERS = "!needsDividers!";
private static final String MORE_KEYS_EMBEDDED_MORE_KEY = "!embeddedMoreKey!";
/** Background type that represents different key background visual than normal one. */
public final int mBackgroundType;
public static final int BACKGROUND_TYPE_NORMAL = 0;
public static final int BACKGROUND_TYPE_FUNCTIONAL = 1;
public static final int BACKGROUND_TYPE_ACTION = 2;
public static final int BACKGROUND_TYPE_STICKY_OFF = 3;
public static final int BACKGROUND_TYPE_STICKY_ON = 4;
private final int mActionFlags;
private static final int ACTION_FLAGS_IS_REPEATABLE = 0x01;
private static final int ACTION_FLAGS_NO_KEY_PREVIEW = 0x02;
private static final int ACTION_FLAGS_ALT_CODE_WHILE_TYPING = 0x04;
private static final int ACTION_FLAGS_ENABLE_LONG_PRESS = 0x08;
private final int mHashCode;
/** The current pressed state of this key */
private boolean mPressed;
/** Key is enabled and responds on press */
private boolean mEnabled = true;
/**
* This constructor is being used only for keys in more keys keyboard.
*/
public Key(Keyboard.Params params, MoreKeySpec moreKeySpec, int x, int y, int width, int height,
int labelFlags) {
this(params, moreKeySpec.mLabel, null, moreKeySpec.mIconId, moreKeySpec.mCode,
moreKeySpec.mOutputText, x, y, width, height, labelFlags);
}
/**
* This constructor is being used only for key in popup suggestions pane.
*/
public Key(Keyboard.Params params, String label, String hintLabel, int iconId,
int code, String outputText, int x, int y, int width, int height, int labelFlags) {
mHeight = height - params.mVerticalGap;
mHorizontalGap = params.mHorizontalGap;
mVerticalGap = params.mVerticalGap;
mVisualInsetsLeft = mVisualInsetsRight = 0;
mWidth = width - mHorizontalGap;
mHintLabel = hintLabel;
mLabelFlags = labelFlags;
mBackgroundType = BACKGROUND_TYPE_NORMAL;
mActionFlags = 0;
mMoreKeys = null;
mMoreKeysColumnAndFlags = 0;
mLabel = label;
mOutputText = outputText;
mCode = code;
mEnabled = (code != CODE_UNSPECIFIED);
mAltCode = CODE_UNSPECIFIED;
mIconId = iconId;
mDisabledIconId = ICON_UNDEFINED;
mPreviewIconId = ICON_UNDEFINED;
// Horizontal gap is divided equally to both sides of the key.
mX = x + mHorizontalGap / 2;
mY = y;
mHitBox.set(x, y, x + width + 1, y + height);
mHashCode = computeHashCode(this);
}
/**
* Create a key with the given top-left coordinate and extract its attributes from the XML
* parser.
* @param res resources associated with the caller's context
* @param params the keyboard building parameters.
* @param row the row that this key belongs to. row's x-coordinate will be the right edge of
* this key.
* @param parser the XML parser containing the attributes for this key
* @throws XmlPullParserException
*/
public Key(Resources res, Keyboard.Params params, Keyboard.Builder.Row row,
XmlPullParser parser) throws XmlPullParserException {
final float horizontalGap = isSpacer() ? 0 : params.mHorizontalGap;
final int keyHeight = row.mRowHeight;
mVerticalGap = params.mVerticalGap;
mHeight = keyHeight - mVerticalGap;
final TypedArray keyAttr = res.obtainAttributes(Xml.asAttributeSet(parser),
R.styleable.Keyboard_Key);
final KeyStyle style = params.mKeyStyles.getKeyStyle(keyAttr, parser);
final float keyXPos = row.getKeyX(keyAttr);
final float keyWidth = row.getKeyWidth(keyAttr, keyXPos);
final int keyYPos = row.getKeyY();
// Horizontal gap is divided equally to both sides of the key.
- mX = (int) (keyXPos + horizontalGap / 2);
+ mX = Math.round(keyXPos + horizontalGap / 2);
mY = keyYPos;
- mWidth = (int) (keyWidth - horizontalGap);
- mHorizontalGap = (int) horizontalGap;
- mHitBox.set((int)keyXPos, keyYPos, (int)(keyXPos + keyWidth) + 1, keyYPos + keyHeight);
+ mWidth = Math.round(keyWidth - horizontalGap);
+ mHorizontalGap = Math.round(horizontalGap);
+ mHitBox.set(Math.round(keyXPos), keyYPos, Math.round(keyXPos + keyWidth) + 1,
+ keyYPos + keyHeight);
// Update row to have current x coordinate.
row.setXPos(keyXPos + keyWidth);
mBackgroundType = style.getInt(keyAttr,
R.styleable.Keyboard_Key_backgroundType, BACKGROUND_TYPE_NORMAL);
- mVisualInsetsLeft = (int) Keyboard.Builder.getDimensionOrFraction(keyAttr,
- R.styleable.Keyboard_Key_visualInsetsLeft, params.mBaseWidth, 0);
- mVisualInsetsRight = (int) Keyboard.Builder.getDimensionOrFraction(keyAttr,
- R.styleable.Keyboard_Key_visualInsetsRight, params.mBaseWidth, 0);
+ mVisualInsetsLeft = Math.round(Keyboard.Builder.getDimensionOrFraction(keyAttr,
+ R.styleable.Keyboard_Key_visualInsetsLeft, params.mBaseWidth, 0));
+ mVisualInsetsRight = Math.round(Keyboard.Builder.getDimensionOrFraction(keyAttr,
+ R.styleable.Keyboard_Key_visualInsetsRight, params.mBaseWidth, 0));
mIconId = KeySpecParser.getIconId(style.getString(keyAttr,
R.styleable.Keyboard_Key_keyIcon));
mDisabledIconId = KeySpecParser.getIconId(style.getString(keyAttr,
R.styleable.Keyboard_Key_keyIconDisabled));
mPreviewIconId = KeySpecParser.getIconId(style.getString(keyAttr,
R.styleable.Keyboard_Key_keyIconPreview));
mLabelFlags = style.getFlag(keyAttr, R.styleable.Keyboard_Key_keyLabelFlags)
| row.getDefaultKeyLabelFlags();
final boolean needsToUpperCase = needsToUpperCase(mLabelFlags, params.mId.mElementId);
final Locale locale = params.mId.mLocale;
int actionFlags = style.getFlag(keyAttr, R.styleable.Keyboard_Key_keyActionFlags);
String[] moreKeys = style.getStringArray(keyAttr, R.styleable.Keyboard_Key_moreKeys);
int moreKeysColumn = style.getInt(keyAttr,
R.styleable.Keyboard_Key_maxMoreKeysColumn, params.mMaxMoreKeysKeyboardColumn);
int value;
if ((value = KeySpecParser.getIntValue(moreKeys, MORE_KEYS_AUTO_COLUMN_ORDER, -1)) > 0) {
moreKeysColumn = value & MORE_KEYS_COLUMN_MASK;
}
if ((value = KeySpecParser.getIntValue(moreKeys, MORE_KEYS_FIXED_COLUMN_ORDER, -1)) > 0) {
moreKeysColumn = MORE_KEYS_FLAGS_FIXED_COLUMN_ORDER | (value & MORE_KEYS_COLUMN_MASK);
}
if (KeySpecParser.getBooleanValue(moreKeys, MORE_KEYS_HAS_LABELS)) {
moreKeysColumn |= MORE_KEYS_FLAGS_HAS_LABELS;
}
if (KeySpecParser.getBooleanValue(moreKeys, MORE_KEYS_NEEDS_DIVIDERS)) {
moreKeysColumn |= MORE_KEYS_FLAGS_NEEDS_DIVIDERS;
}
if (KeySpecParser.getBooleanValue(moreKeys, MORE_KEYS_EMBEDDED_MORE_KEY)) {
moreKeysColumn |= MORE_KEYS_FLAGS_EMBEDDED_MORE_KEY;
}
mMoreKeysColumnAndFlags = moreKeysColumn;
final String[] additionalMoreKeys;
if ((mLabelFlags & LABEL_FLAGS_DISABLE_ADDITIONAL_MORE_KEYS) != 0) {
additionalMoreKeys = null;
} else {
additionalMoreKeys = style.getStringArray(keyAttr,
R.styleable.Keyboard_Key_additionalMoreKeys);
}
moreKeys = KeySpecParser.insertAdditionalMoreKeys(moreKeys, additionalMoreKeys);
if (moreKeys != null) {
actionFlags |= ACTION_FLAGS_ENABLE_LONG_PRESS;
mMoreKeys = new MoreKeySpec[moreKeys.length];
for (int i = 0; i < moreKeys.length; i++) {
mMoreKeys[i] = new MoreKeySpec(
moreKeys[i], needsToUpperCase, locale, params.mCodesSet);
}
} else {
mMoreKeys = null;
}
mActionFlags = actionFlags;
if ((mLabelFlags & LABEL_FLAGS_FROM_CUSTOM_ACTION_LABEL) != 0) {
mLabel = params.mId.mCustomActionLabel;
} else {
mLabel = KeySpecParser.toUpperCaseOfStringForLocale(style.getString(keyAttr,
R.styleable.Keyboard_Key_keyLabel), needsToUpperCase, locale);
}
if ((mLabelFlags & LABEL_FLAGS_DISABLE_HINT_LABEL) != 0) {
mHintLabel = null;
} else {
mHintLabel = KeySpecParser.toUpperCaseOfStringForLocale(style.getString(keyAttr,
R.styleable.Keyboard_Key_keyHintLabel), needsToUpperCase, locale);
}
String outputText = KeySpecParser.toUpperCaseOfStringForLocale(style.getString(keyAttr,
R.styleable.Keyboard_Key_keyOutputText), needsToUpperCase, locale);
final int code = KeySpecParser.parseCode(style.getString(keyAttr,
R.styleable.Keyboard_Key_code), params.mCodesSet, CODE_UNSPECIFIED);
// Choose the first letter of the label as primary code if not specified.
if (code == CODE_UNSPECIFIED && TextUtils.isEmpty(outputText)
&& !TextUtils.isEmpty(mLabel)) {
if (StringUtils.codePointCount(mLabel) == 1) {
// Use the first letter of the hint label if shiftedLetterActivated flag is
// specified.
if (hasShiftedLetterHint() && isShiftedLetterActivated()
&& !TextUtils.isEmpty(mHintLabel)) {
mCode = mHintLabel.codePointAt(0);
} else {
mCode = mLabel.codePointAt(0);
}
} else {
// In some locale and case, the character might be represented by multiple code
// points, such as upper case Eszett of German alphabet.
outputText = mLabel;
mCode = CODE_OUTPUT_TEXT;
}
} else if (code == CODE_UNSPECIFIED && outputText != null) {
if (StringUtils.codePointCount(outputText) == 1) {
mCode = outputText.codePointAt(0);
outputText = null;
} else {
mCode = CODE_OUTPUT_TEXT;
}
} else {
mCode = KeySpecParser.toUpperCaseOfCodeForLocale(code, needsToUpperCase, locale);
}
mOutputText = outputText;
mAltCode = KeySpecParser.toUpperCaseOfCodeForLocale(
KeySpecParser.parseCode(style.getString(keyAttr,
R.styleable.Keyboard_Key_altCode), params.mCodesSet, CODE_UNSPECIFIED),
needsToUpperCase, locale);
mHashCode = computeHashCode(this);
keyAttr.recycle();
if (hasShiftedLetterHint() && TextUtils.isEmpty(mHintLabel)) {
Log.w(TAG, "hasShiftedLetterHint specified without keyHintLabel: " + this);
}
}
private static boolean needsToUpperCase(int labelFlags, int keyboardElementId) {
if ((labelFlags & LABEL_FLAGS_PRESERVE_CASE) != 0) return false;
switch (keyboardElementId) {
case KeyboardId.ELEMENT_ALPHABET_MANUAL_SHIFTED:
case KeyboardId.ELEMENT_ALPHABET_AUTOMATIC_SHIFTED:
case KeyboardId.ELEMENT_ALPHABET_SHIFT_LOCKED:
case KeyboardId.ELEMENT_ALPHABET_SHIFT_LOCK_SHIFTED:
return true;
default:
return false;
}
}
private static int computeHashCode(Key key) {
return Arrays.hashCode(new Object[] {
key.mX,
key.mY,
key.mWidth,
key.mHeight,
key.mCode,
key.mLabel,
key.mHintLabel,
key.mIconId,
key.mBackgroundType,
Arrays.hashCode(key.mMoreKeys),
key.mOutputText,
key.mActionFlags,
key.mLabelFlags,
// Key can be distinguishable without the following members.
// key.mAltCode,
// key.mDisabledIconId,
// key.mPreviewIconId,
// key.mHorizontalGap,
// key.mVerticalGap,
// key.mVisualInsetLeft,
// key.mVisualInsetRight,
// key.mMaxMoreKeysColumn,
});
}
private boolean equals(Key o) {
if (this == o) return true;
return o.mX == mX
&& o.mY == mY
&& o.mWidth == mWidth
&& o.mHeight == mHeight
&& o.mCode == mCode
&& TextUtils.equals(o.mLabel, mLabel)
&& TextUtils.equals(o.mHintLabel, mHintLabel)
&& o.mIconId == mIconId
&& o.mBackgroundType == mBackgroundType
&& Arrays.equals(o.mMoreKeys, mMoreKeys)
&& TextUtils.equals(o.mOutputText, mOutputText)
&& o.mActionFlags == mActionFlags
&& o.mLabelFlags == mLabelFlags;
}
@Override
public int hashCode() {
return mHashCode;
}
@Override
public boolean equals(Object o) {
return o instanceof Key && equals((Key)o);
}
@Override
public String toString() {
return String.format("%s/%s %d,%d %dx%d %s/%s/%s",
Keyboard.printableCode(mCode), mLabel, mX, mY, mWidth, mHeight, mHintLabel,
KeyboardIconsSet.getIconName(mIconId), backgroundName(mBackgroundType));
}
private static String backgroundName(int backgroundType) {
switch (backgroundType) {
case BACKGROUND_TYPE_NORMAL: return "normal";
case BACKGROUND_TYPE_FUNCTIONAL: return "functional";
case BACKGROUND_TYPE_ACTION: return "action";
case BACKGROUND_TYPE_STICKY_OFF: return "stickyOff";
case BACKGROUND_TYPE_STICKY_ON: return "stickyOn";
default: return null;
}
}
public void markAsLeftEdge(Keyboard.Params params) {
mHitBox.left = params.mHorizontalEdgesPadding;
}
public void markAsRightEdge(Keyboard.Params params) {
mHitBox.right = params.mOccupiedWidth - params.mHorizontalEdgesPadding;
}
public void markAsTopEdge(Keyboard.Params params) {
mHitBox.top = params.mTopPadding;
}
public void markAsBottomEdge(Keyboard.Params params) {
mHitBox.bottom = params.mOccupiedHeight + params.mBottomPadding;
}
public final boolean isSpacer() {
return this instanceof Spacer;
}
public boolean isShift() {
return mCode == CODE_SHIFT;
}
public boolean isModifier() {
return mCode == CODE_SHIFT || mCode == CODE_SWITCH_ALPHA_SYMBOL;
}
public boolean isRepeatable() {
return (mActionFlags & ACTION_FLAGS_IS_REPEATABLE) != 0;
}
public boolean noKeyPreview() {
return (mActionFlags & ACTION_FLAGS_NO_KEY_PREVIEW) != 0;
}
public boolean altCodeWhileTyping() {
return (mActionFlags & ACTION_FLAGS_ALT_CODE_WHILE_TYPING) != 0;
}
public boolean isLongPressEnabled() {
// We need not start long press timer on the key which has activated shifted letter.
return (mActionFlags & ACTION_FLAGS_ENABLE_LONG_PRESS) != 0
&& (mLabelFlags & LABEL_FLAGS_SHIFTED_LETTER_ACTIVATED) == 0;
}
public Typeface selectTypeface(Typeface defaultTypeface) {
// TODO: Handle "bold" here too?
if ((mLabelFlags & LABEL_FLAGS_FONT_NORMAL) != 0) {
return Typeface.DEFAULT;
} else if ((mLabelFlags & LABEL_FLAGS_FONT_MONO_SPACE) != 0) {
return Typeface.MONOSPACE;
} else {
return defaultTypeface;
}
}
public int selectTextSize(int letterSize, int largeLetterSize, int labelSize,
int largeLabelSize, int hintLabelSize) {
switch (mLabelFlags & LABEL_FLAGS_FOLLOW_KEY_TEXT_RATIO_MASK) {
case LABEL_FLAGS_FOLLOW_KEY_LETTER_RATIO:
return letterSize;
case LABEL_FLAGS_FOLLOW_KEY_LARGE_LETTER_RATIO:
return largeLetterSize;
case LABEL_FLAGS_FOLLOW_KEY_LABEL_RATIO:
return labelSize;
case LABEL_FLAGS_FOLLOW_KEY_LARGE_LABEL_RATIO:
return largeLabelSize;
case LABEL_FLAGS_FOLLOW_KEY_HINT_LABEL_RATIO:
return hintLabelSize;
default: // No follow key ratio flag specified.
return StringUtils.codePointCount(mLabel) == 1 ? letterSize : labelSize;
}
}
public boolean isAlignLeft() {
return (mLabelFlags & LABEL_FLAGS_ALIGN_LEFT) != 0;
}
public boolean isAlignRight() {
return (mLabelFlags & LABEL_FLAGS_ALIGN_RIGHT) != 0;
}
public boolean isAlignLeftOfCenter() {
return (mLabelFlags & LABEL_FLAGS_ALIGN_LEFT_OF_CENTER) != 0;
}
public boolean hasPopupHint() {
return (mLabelFlags & LABEL_FLAGS_HAS_POPUP_HINT) != 0;
}
public boolean hasShiftedLetterHint() {
return (mLabelFlags & LABEL_FLAGS_HAS_SHIFTED_LETTER_HINT) != 0;
}
public boolean hasHintLabel() {
return (mLabelFlags & LABEL_FLAGS_HAS_HINT_LABEL) != 0;
}
public boolean hasLabelWithIconLeft() {
return (mLabelFlags & LABEL_FLAGS_WITH_ICON_LEFT) != 0;
}
public boolean hasLabelWithIconRight() {
return (mLabelFlags & LABEL_FLAGS_WITH_ICON_RIGHT) != 0;
}
public boolean needsXScale() {
return (mLabelFlags & LABEL_FLAGS_AUTO_X_SCALE) != 0;
}
public boolean isShiftedLetterActivated() {
return (mLabelFlags & LABEL_FLAGS_SHIFTED_LETTER_ACTIVATED) != 0;
}
public int getMoreKeysColumn() {
return mMoreKeysColumnAndFlags & MORE_KEYS_COLUMN_MASK;
}
public boolean isFixedColumnOrderMoreKeys() {
return (mMoreKeysColumnAndFlags & MORE_KEYS_FLAGS_FIXED_COLUMN_ORDER) != 0;
}
public boolean hasLabelsInMoreKeys() {
return (mMoreKeysColumnAndFlags & MORE_KEYS_FLAGS_HAS_LABELS) != 0;
}
public int getMoreKeyLabelFlags() {
return hasLabelsInMoreKeys()
? LABEL_FLAGS_FOLLOW_KEY_LABEL_RATIO
: LABEL_FLAGS_FOLLOW_KEY_LETTER_RATIO;
}
public boolean needsDividersInMoreKeys() {
return (mMoreKeysColumnAndFlags & MORE_KEYS_FLAGS_NEEDS_DIVIDERS) != 0;
}
public boolean hasEmbeddedMoreKey() {
return (mMoreKeysColumnAndFlags & MORE_KEYS_FLAGS_EMBEDDED_MORE_KEY) != 0;
}
public Drawable getIcon(KeyboardIconsSet iconSet, int alpha) {
final int iconId = mEnabled ? mIconId : mDisabledIconId;
final Drawable icon = iconSet.getIconDrawable(iconId);
if (icon != null) {
icon.setAlpha(alpha);
}
return icon;
}
public Drawable getPreviewIcon(KeyboardIconsSet iconSet) {
return mPreviewIconId != ICON_UNDEFINED
? iconSet.getIconDrawable(mPreviewIconId)
: iconSet.getIconDrawable(mIconId);
}
/**
* Informs the key that it has been pressed, in case it needs to change its appearance or
* state.
* @see #onReleased()
*/
public void onPressed() {
mPressed = true;
}
/**
* Informs the key that it has been released, in case it needs to change its appearance or
* state.
* @see #onPressed()
*/
public void onReleased() {
mPressed = false;
}
public boolean isEnabled() {
return mEnabled;
}
public void setEnabled(boolean enabled) {
mEnabled = enabled;
}
/**
* Detects if a point falls on this key.
* @param x the x-coordinate of the point
* @param y the y-coordinate of the point
* @return whether or not the point falls on the key. If the key is attached to an edge, it
* will assume that all points between the key and the edge are considered to be on the key.
* @see #markAsLeftEdge(Keyboard.Params) etc.
*/
public boolean isOnKey(int x, int y) {
return mHitBox.contains(x, y);
}
/**
* Returns the square of the distance to the nearest edge of the key and the given point.
* @param x the x-coordinate of the point
* @param y the y-coordinate of the point
* @return the square of the distance of the point from the nearest edge of the key
*/
public int squaredDistanceToEdge(int x, int y) {
final int left = mX;
final int right = left + mWidth;
final int top = mY;
final int bottom = top + mHeight;
final int edgeX = x < left ? left : (x > right ? right : x);
final int edgeY = y < top ? top : (y > bottom ? bottom : y);
final int dx = x - edgeX;
final int dy = y - edgeY;
return dx * dx + dy * dy;
}
private final static int[] KEY_STATE_NORMAL_HIGHLIGHT_ON = {
android.R.attr.state_checkable,
android.R.attr.state_checked
};
private final static int[] KEY_STATE_PRESSED_HIGHLIGHT_ON = {
android.R.attr.state_pressed,
android.R.attr.state_checkable,
android.R.attr.state_checked
};
private final static int[] KEY_STATE_NORMAL_HIGHLIGHT_OFF = {
android.R.attr.state_checkable
};
private final static int[] KEY_STATE_PRESSED_HIGHLIGHT_OFF = {
android.R.attr.state_pressed,
android.R.attr.state_checkable
};
private final static int[] KEY_STATE_NORMAL = {
};
private final static int[] KEY_STATE_PRESSED = {
android.R.attr.state_pressed
};
// functional normal state (with properties)
private static final int[] KEY_STATE_FUNCTIONAL_NORMAL = {
android.R.attr.state_single
};
// functional pressed state (with properties)
private static final int[] KEY_STATE_FUNCTIONAL_PRESSED = {
android.R.attr.state_single,
android.R.attr.state_pressed
};
// action normal state (with properties)
private static final int[] KEY_STATE_ACTIVE_NORMAL = {
android.R.attr.state_active
};
// action pressed state (with properties)
private static final int[] KEY_STATE_ACTIVE_PRESSED = {
android.R.attr.state_active,
android.R.attr.state_pressed
};
/**
* Returns the drawable state for the key, based on the current state and type of the key.
* @return the drawable state of the key.
* @see android.graphics.drawable.StateListDrawable#setState(int[])
*/
public int[] getCurrentDrawableState() {
switch (mBackgroundType) {
case BACKGROUND_TYPE_FUNCTIONAL:
return mPressed ? KEY_STATE_FUNCTIONAL_PRESSED : KEY_STATE_FUNCTIONAL_NORMAL;
case BACKGROUND_TYPE_ACTION:
return mPressed ? KEY_STATE_ACTIVE_PRESSED : KEY_STATE_ACTIVE_NORMAL;
case BACKGROUND_TYPE_STICKY_OFF:
return mPressed ? KEY_STATE_PRESSED_HIGHLIGHT_OFF : KEY_STATE_NORMAL_HIGHLIGHT_OFF;
case BACKGROUND_TYPE_STICKY_ON:
return mPressed ? KEY_STATE_PRESSED_HIGHLIGHT_ON : KEY_STATE_NORMAL_HIGHLIGHT_ON;
default: /* BACKGROUND_TYPE_NORMAL */
return mPressed ? KEY_STATE_PRESSED : KEY_STATE_NORMAL;
}
}
public static class Spacer extends Key {
public Spacer(Resources res, Keyboard.Params params, Keyboard.Builder.Row row,
XmlPullParser parser) throws XmlPullParserException {
super(res, params, row, parser);
}
/**
* This constructor is being used only for divider in more keys keyboard.
*/
protected Spacer(Keyboard.Params params, int x, int y, int width, int height) {
super(params, null, null, ICON_UNDEFINED, CODE_UNSPECIFIED,
null, x, y, width, height, 0);
}
}
}
| false | true | public Key(Resources res, Keyboard.Params params, Keyboard.Builder.Row row,
XmlPullParser parser) throws XmlPullParserException {
final float horizontalGap = isSpacer() ? 0 : params.mHorizontalGap;
final int keyHeight = row.mRowHeight;
mVerticalGap = params.mVerticalGap;
mHeight = keyHeight - mVerticalGap;
final TypedArray keyAttr = res.obtainAttributes(Xml.asAttributeSet(parser),
R.styleable.Keyboard_Key);
final KeyStyle style = params.mKeyStyles.getKeyStyle(keyAttr, parser);
final float keyXPos = row.getKeyX(keyAttr);
final float keyWidth = row.getKeyWidth(keyAttr, keyXPos);
final int keyYPos = row.getKeyY();
// Horizontal gap is divided equally to both sides of the key.
mX = (int) (keyXPos + horizontalGap / 2);
mY = keyYPos;
mWidth = (int) (keyWidth - horizontalGap);
mHorizontalGap = (int) horizontalGap;
mHitBox.set((int)keyXPos, keyYPos, (int)(keyXPos + keyWidth) + 1, keyYPos + keyHeight);
// Update row to have current x coordinate.
row.setXPos(keyXPos + keyWidth);
mBackgroundType = style.getInt(keyAttr,
R.styleable.Keyboard_Key_backgroundType, BACKGROUND_TYPE_NORMAL);
mVisualInsetsLeft = (int) Keyboard.Builder.getDimensionOrFraction(keyAttr,
R.styleable.Keyboard_Key_visualInsetsLeft, params.mBaseWidth, 0);
mVisualInsetsRight = (int) Keyboard.Builder.getDimensionOrFraction(keyAttr,
R.styleable.Keyboard_Key_visualInsetsRight, params.mBaseWidth, 0);
mIconId = KeySpecParser.getIconId(style.getString(keyAttr,
R.styleable.Keyboard_Key_keyIcon));
mDisabledIconId = KeySpecParser.getIconId(style.getString(keyAttr,
R.styleable.Keyboard_Key_keyIconDisabled));
mPreviewIconId = KeySpecParser.getIconId(style.getString(keyAttr,
R.styleable.Keyboard_Key_keyIconPreview));
mLabelFlags = style.getFlag(keyAttr, R.styleable.Keyboard_Key_keyLabelFlags)
| row.getDefaultKeyLabelFlags();
final boolean needsToUpperCase = needsToUpperCase(mLabelFlags, params.mId.mElementId);
final Locale locale = params.mId.mLocale;
int actionFlags = style.getFlag(keyAttr, R.styleable.Keyboard_Key_keyActionFlags);
String[] moreKeys = style.getStringArray(keyAttr, R.styleable.Keyboard_Key_moreKeys);
int moreKeysColumn = style.getInt(keyAttr,
R.styleable.Keyboard_Key_maxMoreKeysColumn, params.mMaxMoreKeysKeyboardColumn);
int value;
if ((value = KeySpecParser.getIntValue(moreKeys, MORE_KEYS_AUTO_COLUMN_ORDER, -1)) > 0) {
moreKeysColumn = value & MORE_KEYS_COLUMN_MASK;
}
if ((value = KeySpecParser.getIntValue(moreKeys, MORE_KEYS_FIXED_COLUMN_ORDER, -1)) > 0) {
moreKeysColumn = MORE_KEYS_FLAGS_FIXED_COLUMN_ORDER | (value & MORE_KEYS_COLUMN_MASK);
}
if (KeySpecParser.getBooleanValue(moreKeys, MORE_KEYS_HAS_LABELS)) {
moreKeysColumn |= MORE_KEYS_FLAGS_HAS_LABELS;
}
if (KeySpecParser.getBooleanValue(moreKeys, MORE_KEYS_NEEDS_DIVIDERS)) {
moreKeysColumn |= MORE_KEYS_FLAGS_NEEDS_DIVIDERS;
}
if (KeySpecParser.getBooleanValue(moreKeys, MORE_KEYS_EMBEDDED_MORE_KEY)) {
moreKeysColumn |= MORE_KEYS_FLAGS_EMBEDDED_MORE_KEY;
}
mMoreKeysColumnAndFlags = moreKeysColumn;
final String[] additionalMoreKeys;
if ((mLabelFlags & LABEL_FLAGS_DISABLE_ADDITIONAL_MORE_KEYS) != 0) {
additionalMoreKeys = null;
} else {
additionalMoreKeys = style.getStringArray(keyAttr,
R.styleable.Keyboard_Key_additionalMoreKeys);
}
moreKeys = KeySpecParser.insertAdditionalMoreKeys(moreKeys, additionalMoreKeys);
if (moreKeys != null) {
actionFlags |= ACTION_FLAGS_ENABLE_LONG_PRESS;
mMoreKeys = new MoreKeySpec[moreKeys.length];
for (int i = 0; i < moreKeys.length; i++) {
mMoreKeys[i] = new MoreKeySpec(
moreKeys[i], needsToUpperCase, locale, params.mCodesSet);
}
} else {
mMoreKeys = null;
}
mActionFlags = actionFlags;
if ((mLabelFlags & LABEL_FLAGS_FROM_CUSTOM_ACTION_LABEL) != 0) {
mLabel = params.mId.mCustomActionLabel;
} else {
mLabel = KeySpecParser.toUpperCaseOfStringForLocale(style.getString(keyAttr,
R.styleable.Keyboard_Key_keyLabel), needsToUpperCase, locale);
}
if ((mLabelFlags & LABEL_FLAGS_DISABLE_HINT_LABEL) != 0) {
mHintLabel = null;
} else {
mHintLabel = KeySpecParser.toUpperCaseOfStringForLocale(style.getString(keyAttr,
R.styleable.Keyboard_Key_keyHintLabel), needsToUpperCase, locale);
}
String outputText = KeySpecParser.toUpperCaseOfStringForLocale(style.getString(keyAttr,
R.styleable.Keyboard_Key_keyOutputText), needsToUpperCase, locale);
final int code = KeySpecParser.parseCode(style.getString(keyAttr,
R.styleable.Keyboard_Key_code), params.mCodesSet, CODE_UNSPECIFIED);
// Choose the first letter of the label as primary code if not specified.
if (code == CODE_UNSPECIFIED && TextUtils.isEmpty(outputText)
&& !TextUtils.isEmpty(mLabel)) {
if (StringUtils.codePointCount(mLabel) == 1) {
// Use the first letter of the hint label if shiftedLetterActivated flag is
// specified.
if (hasShiftedLetterHint() && isShiftedLetterActivated()
&& !TextUtils.isEmpty(mHintLabel)) {
mCode = mHintLabel.codePointAt(0);
} else {
mCode = mLabel.codePointAt(0);
}
} else {
// In some locale and case, the character might be represented by multiple code
// points, such as upper case Eszett of German alphabet.
outputText = mLabel;
mCode = CODE_OUTPUT_TEXT;
}
} else if (code == CODE_UNSPECIFIED && outputText != null) {
if (StringUtils.codePointCount(outputText) == 1) {
mCode = outputText.codePointAt(0);
outputText = null;
} else {
mCode = CODE_OUTPUT_TEXT;
}
} else {
mCode = KeySpecParser.toUpperCaseOfCodeForLocale(code, needsToUpperCase, locale);
}
mOutputText = outputText;
mAltCode = KeySpecParser.toUpperCaseOfCodeForLocale(
KeySpecParser.parseCode(style.getString(keyAttr,
R.styleable.Keyboard_Key_altCode), params.mCodesSet, CODE_UNSPECIFIED),
needsToUpperCase, locale);
mHashCode = computeHashCode(this);
keyAttr.recycle();
if (hasShiftedLetterHint() && TextUtils.isEmpty(mHintLabel)) {
Log.w(TAG, "hasShiftedLetterHint specified without keyHintLabel: " + this);
}
}
| public Key(Resources res, Keyboard.Params params, Keyboard.Builder.Row row,
XmlPullParser parser) throws XmlPullParserException {
final float horizontalGap = isSpacer() ? 0 : params.mHorizontalGap;
final int keyHeight = row.mRowHeight;
mVerticalGap = params.mVerticalGap;
mHeight = keyHeight - mVerticalGap;
final TypedArray keyAttr = res.obtainAttributes(Xml.asAttributeSet(parser),
R.styleable.Keyboard_Key);
final KeyStyle style = params.mKeyStyles.getKeyStyle(keyAttr, parser);
final float keyXPos = row.getKeyX(keyAttr);
final float keyWidth = row.getKeyWidth(keyAttr, keyXPos);
final int keyYPos = row.getKeyY();
// Horizontal gap is divided equally to both sides of the key.
mX = Math.round(keyXPos + horizontalGap / 2);
mY = keyYPos;
mWidth = Math.round(keyWidth - horizontalGap);
mHorizontalGap = Math.round(horizontalGap);
mHitBox.set(Math.round(keyXPos), keyYPos, Math.round(keyXPos + keyWidth) + 1,
keyYPos + keyHeight);
// Update row to have current x coordinate.
row.setXPos(keyXPos + keyWidth);
mBackgroundType = style.getInt(keyAttr,
R.styleable.Keyboard_Key_backgroundType, BACKGROUND_TYPE_NORMAL);
mVisualInsetsLeft = Math.round(Keyboard.Builder.getDimensionOrFraction(keyAttr,
R.styleable.Keyboard_Key_visualInsetsLeft, params.mBaseWidth, 0));
mVisualInsetsRight = Math.round(Keyboard.Builder.getDimensionOrFraction(keyAttr,
R.styleable.Keyboard_Key_visualInsetsRight, params.mBaseWidth, 0));
mIconId = KeySpecParser.getIconId(style.getString(keyAttr,
R.styleable.Keyboard_Key_keyIcon));
mDisabledIconId = KeySpecParser.getIconId(style.getString(keyAttr,
R.styleable.Keyboard_Key_keyIconDisabled));
mPreviewIconId = KeySpecParser.getIconId(style.getString(keyAttr,
R.styleable.Keyboard_Key_keyIconPreview));
mLabelFlags = style.getFlag(keyAttr, R.styleable.Keyboard_Key_keyLabelFlags)
| row.getDefaultKeyLabelFlags();
final boolean needsToUpperCase = needsToUpperCase(mLabelFlags, params.mId.mElementId);
final Locale locale = params.mId.mLocale;
int actionFlags = style.getFlag(keyAttr, R.styleable.Keyboard_Key_keyActionFlags);
String[] moreKeys = style.getStringArray(keyAttr, R.styleable.Keyboard_Key_moreKeys);
int moreKeysColumn = style.getInt(keyAttr,
R.styleable.Keyboard_Key_maxMoreKeysColumn, params.mMaxMoreKeysKeyboardColumn);
int value;
if ((value = KeySpecParser.getIntValue(moreKeys, MORE_KEYS_AUTO_COLUMN_ORDER, -1)) > 0) {
moreKeysColumn = value & MORE_KEYS_COLUMN_MASK;
}
if ((value = KeySpecParser.getIntValue(moreKeys, MORE_KEYS_FIXED_COLUMN_ORDER, -1)) > 0) {
moreKeysColumn = MORE_KEYS_FLAGS_FIXED_COLUMN_ORDER | (value & MORE_KEYS_COLUMN_MASK);
}
if (KeySpecParser.getBooleanValue(moreKeys, MORE_KEYS_HAS_LABELS)) {
moreKeysColumn |= MORE_KEYS_FLAGS_HAS_LABELS;
}
if (KeySpecParser.getBooleanValue(moreKeys, MORE_KEYS_NEEDS_DIVIDERS)) {
moreKeysColumn |= MORE_KEYS_FLAGS_NEEDS_DIVIDERS;
}
if (KeySpecParser.getBooleanValue(moreKeys, MORE_KEYS_EMBEDDED_MORE_KEY)) {
moreKeysColumn |= MORE_KEYS_FLAGS_EMBEDDED_MORE_KEY;
}
mMoreKeysColumnAndFlags = moreKeysColumn;
final String[] additionalMoreKeys;
if ((mLabelFlags & LABEL_FLAGS_DISABLE_ADDITIONAL_MORE_KEYS) != 0) {
additionalMoreKeys = null;
} else {
additionalMoreKeys = style.getStringArray(keyAttr,
R.styleable.Keyboard_Key_additionalMoreKeys);
}
moreKeys = KeySpecParser.insertAdditionalMoreKeys(moreKeys, additionalMoreKeys);
if (moreKeys != null) {
actionFlags |= ACTION_FLAGS_ENABLE_LONG_PRESS;
mMoreKeys = new MoreKeySpec[moreKeys.length];
for (int i = 0; i < moreKeys.length; i++) {
mMoreKeys[i] = new MoreKeySpec(
moreKeys[i], needsToUpperCase, locale, params.mCodesSet);
}
} else {
mMoreKeys = null;
}
mActionFlags = actionFlags;
if ((mLabelFlags & LABEL_FLAGS_FROM_CUSTOM_ACTION_LABEL) != 0) {
mLabel = params.mId.mCustomActionLabel;
} else {
mLabel = KeySpecParser.toUpperCaseOfStringForLocale(style.getString(keyAttr,
R.styleable.Keyboard_Key_keyLabel), needsToUpperCase, locale);
}
if ((mLabelFlags & LABEL_FLAGS_DISABLE_HINT_LABEL) != 0) {
mHintLabel = null;
} else {
mHintLabel = KeySpecParser.toUpperCaseOfStringForLocale(style.getString(keyAttr,
R.styleable.Keyboard_Key_keyHintLabel), needsToUpperCase, locale);
}
String outputText = KeySpecParser.toUpperCaseOfStringForLocale(style.getString(keyAttr,
R.styleable.Keyboard_Key_keyOutputText), needsToUpperCase, locale);
final int code = KeySpecParser.parseCode(style.getString(keyAttr,
R.styleable.Keyboard_Key_code), params.mCodesSet, CODE_UNSPECIFIED);
// Choose the first letter of the label as primary code if not specified.
if (code == CODE_UNSPECIFIED && TextUtils.isEmpty(outputText)
&& !TextUtils.isEmpty(mLabel)) {
if (StringUtils.codePointCount(mLabel) == 1) {
// Use the first letter of the hint label if shiftedLetterActivated flag is
// specified.
if (hasShiftedLetterHint() && isShiftedLetterActivated()
&& !TextUtils.isEmpty(mHintLabel)) {
mCode = mHintLabel.codePointAt(0);
} else {
mCode = mLabel.codePointAt(0);
}
} else {
// In some locale and case, the character might be represented by multiple code
// points, such as upper case Eszett of German alphabet.
outputText = mLabel;
mCode = CODE_OUTPUT_TEXT;
}
} else if (code == CODE_UNSPECIFIED && outputText != null) {
if (StringUtils.codePointCount(outputText) == 1) {
mCode = outputText.codePointAt(0);
outputText = null;
} else {
mCode = CODE_OUTPUT_TEXT;
}
} else {
mCode = KeySpecParser.toUpperCaseOfCodeForLocale(code, needsToUpperCase, locale);
}
mOutputText = outputText;
mAltCode = KeySpecParser.toUpperCaseOfCodeForLocale(
KeySpecParser.parseCode(style.getString(keyAttr,
R.styleable.Keyboard_Key_altCode), params.mCodesSet, CODE_UNSPECIFIED),
needsToUpperCase, locale);
mHashCode = computeHashCode(this);
keyAttr.recycle();
if (hasShiftedLetterHint() && TextUtils.isEmpty(mHintLabel)) {
Log.w(TAG, "hasShiftedLetterHint specified without keyHintLabel: " + this);
}
}
|
diff --git a/postprocessing/demo/src/com/bitfire/postprocessing/demo/PostProcessingDemo.java b/postprocessing/demo/src/com/bitfire/postprocessing/demo/PostProcessingDemo.java
index 65b2d57..3472036 100644
--- a/postprocessing/demo/src/com/bitfire/postprocessing/demo/PostProcessingDemo.java
+++ b/postprocessing/demo/src/com/bitfire/postprocessing/demo/PostProcessingDemo.java
@@ -1,268 +1,268 @@
/*******************************************************************************
* Copyright 2012 bmanuel
*
* 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.bitfire.postprocessing.demo;
import java.awt.DisplayMode;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import org.lwjgl.opengl.Display;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.InputMultiplexer;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.MathUtils;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.utils.TimeUtils;
import com.bitfire.utils.ShaderLoader;
public class PostProcessingDemo implements ApplicationListener, InputProcessor {
private static final boolean UsePanelAnimator = true;
private static final boolean UseRightScreen = true;
SpriteBatch batch;
Sprite badlogic;
OrthographicCamera camera;
float angle;
float width, height, halfWidth, halfHeight;
long startMs;
Vector2 circleOffset = new Vector2();
PostProcessing post;
InputMultiplexer plex;
UI ui;
public static void main( String[] argv ) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.title = "libgdx's post-processing demo";
config.width = 1280;
config.height = 720;
config.samples = 0;
config.depth = 0;
config.vSyncEnabled = true;
// Note: this is usually set to false, but i'm noticing a 3fps improvement over
// a cpuSync=false setting. Also, in case of grabbing the window via ffmpeg/qx11grab
// to make a video, artifacts may appear at the top such as flashing white bars: if
// this is the case, using cpuSync=true may solve this.
//
// ffmpeg -xerror -loglevel info -f x11grab -framerate 25 -video_size 1280x720 -i :0.0+2240,200 -dcodec copy -vcodec
// libx264 -preset ultrafast -y /tmp/out.mkv
- config.useCPUSynch = true;
+ config.useCPUSynch = false;
config.useGL20 = true;
config.fullscreen = false;
new LwjglApplication( new PostProcessingDemo(), config );
if( UseRightScreen ) {
// move the window to the right screen
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice primary = env.getDefaultScreenDevice();
GraphicsDevice[] devices = env.getScreenDevices();
GraphicsDevice target = null;
// search for the first target screen
for( int i = 0; i < devices.length; i++ ) {
boolean isPrimary = (primary == devices[i]);
if( !isPrimary ) {
target = devices[i];
break;
}
}
if( target != null ) {
DisplayMode pmode = primary.getDisplayMode();
DisplayMode tmode = target.getDisplayMode();
Display.setLocation( pmode.getWidth() + (tmode.getWidth() - config.width) / 2,
(tmode.getHeight() - config.height) / 2 );
}
}
}
@Override
public void create() {
ShaderLoader.BasePath = "../shaders/";
plex = new InputMultiplexer();
plex.addProcessor( this );
Gdx.input.setInputProcessor( plex );
post = new PostProcessing();
createScene();
ui = new UI( plex, post, UsePanelAnimator );
}
private void createScene() {
width = Gdx.graphics.getWidth();
height = Gdx.graphics.getHeight();
halfWidth = width / 2;
halfHeight = height / 2;
camera = new OrthographicCamera( width, height );
camera.setToOrtho( true );
batch = new SpriteBatch();
batch.setProjectionMatrix( camera.projection );
batch.setTransformMatrix( camera.view );
badlogic = ResourceFactory.newSprite( "badlogic.jpg" );
angle = 0;
startMs = TimeUtils.millis();
}
@Override
public void dispose() {
ResourceFactory.dispose();
post.dispose();
}
@Override
public void render() {
update();
draw();
}
private void update() {
float delta = Gdx.graphics.getDeltaTime();
float angleSpeed = 50;
float angleAmplitude = 50;
float elapsedSecs = (float)(TimeUtils.millis() - startMs) / 1000;
// circling offset
circleOffset.x = halfWidth + (angleAmplitude * 8) * MathUtils.sin( angle * MathUtils.degreesToRadians );
circleOffset.y = halfHeight + (angleAmplitude * 4.5f) * MathUtils.cos( angle * MathUtils.degreesToRadians );
// angle
angle += angleSpeed * delta;
if( angle > 360 ) {
angle -= 360;
}
// UI
ui.update( Gdx.graphics.getDeltaTime() );
// post-processing
post.update( elapsedSecs );
}
private void draw() {
boolean willPostProcess = post.isReady();
boolean backgroundFirst = (willPostProcess && !ui.backgroundAffected && ui.drawBackground)
|| (!willPostProcess && ui.drawBackground);
post.blending = backgroundFirst && willPostProcess;
if( backgroundFirst || !willPostProcess ) {
Gdx.gl20.glClearColor( 0, 0, 0, 1 );
Gdx.gl20.glClear( GL20.GL_COLOR_BUFFER_BIT );
if( backgroundFirst ) {
batch.begin();
ui.background.draw( batch );
batch.end();
}
}
post.begin();
batch.begin();
{
if( ui.drawBackground && ui.backgroundAffected ) {
ui.background.draw( batch );
}
if( ui.drawSprite ) {
badlogic.setPosition( circleOffset.x - badlogic.getWidth() / 2, circleOffset.y - badlogic.getHeight() / 2 );
badlogic.draw( batch );
}
}
batch.end();
post.end();
ui.draw();
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void resize( int width, int height ) {
}
@Override
public boolean keyDown( int keycode ) {
return false;
}
@Override
public boolean keyUp( int keycode ) {
// check for quitting in keyUp, avoid multiple re-entrant keydown events
if( keycode == Keys.Q || keycode == Keys.ESCAPE ) {
Gdx.app.exit();
}
return false;
}
@Override
public boolean keyTyped( char character ) {
return false;
}
@Override
public boolean touchDown( int x, int y, int pointer, int button ) {
return false;
}
@Override
public boolean touchUp( int x, int y, int pointer, int button ) {
return false;
}
@Override
public boolean touchDragged( int x, int y, int pointer ) {
return false;
}
@Override
public boolean mouseMoved( int x, int y ) {
if( post.zoomer.isEnabled() ) {
post.zoomer.setOrigin( x, y );
}
ui.mouseMoved( x, y );
return false;
}
@Override
public boolean scrolled( int amount ) {
post.zoomAmount += amount * -1;
post.zoomAmount = MathUtils.clamp( post.zoomAmount, 0, 15 );
return false;
}
}
| true | true | public static void main( String[] argv ) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.title = "libgdx's post-processing demo";
config.width = 1280;
config.height = 720;
config.samples = 0;
config.depth = 0;
config.vSyncEnabled = true;
// Note: this is usually set to false, but i'm noticing a 3fps improvement over
// a cpuSync=false setting. Also, in case of grabbing the window via ffmpeg/qx11grab
// to make a video, artifacts may appear at the top such as flashing white bars: if
// this is the case, using cpuSync=true may solve this.
//
// ffmpeg -xerror -loglevel info -f x11grab -framerate 25 -video_size 1280x720 -i :0.0+2240,200 -dcodec copy -vcodec
// libx264 -preset ultrafast -y /tmp/out.mkv
config.useCPUSynch = true;
config.useGL20 = true;
config.fullscreen = false;
new LwjglApplication( new PostProcessingDemo(), config );
if( UseRightScreen ) {
// move the window to the right screen
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice primary = env.getDefaultScreenDevice();
GraphicsDevice[] devices = env.getScreenDevices();
GraphicsDevice target = null;
// search for the first target screen
for( int i = 0; i < devices.length; i++ ) {
boolean isPrimary = (primary == devices[i]);
if( !isPrimary ) {
target = devices[i];
break;
}
}
if( target != null ) {
DisplayMode pmode = primary.getDisplayMode();
DisplayMode tmode = target.getDisplayMode();
Display.setLocation( pmode.getWidth() + (tmode.getWidth() - config.width) / 2,
(tmode.getHeight() - config.height) / 2 );
}
}
}
| public static void main( String[] argv ) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.title = "libgdx's post-processing demo";
config.width = 1280;
config.height = 720;
config.samples = 0;
config.depth = 0;
config.vSyncEnabled = true;
// Note: this is usually set to false, but i'm noticing a 3fps improvement over
// a cpuSync=false setting. Also, in case of grabbing the window via ffmpeg/qx11grab
// to make a video, artifacts may appear at the top such as flashing white bars: if
// this is the case, using cpuSync=true may solve this.
//
// ffmpeg -xerror -loglevel info -f x11grab -framerate 25 -video_size 1280x720 -i :0.0+2240,200 -dcodec copy -vcodec
// libx264 -preset ultrafast -y /tmp/out.mkv
config.useCPUSynch = false;
config.useGL20 = true;
config.fullscreen = false;
new LwjglApplication( new PostProcessingDemo(), config );
if( UseRightScreen ) {
// move the window to the right screen
GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice primary = env.getDefaultScreenDevice();
GraphicsDevice[] devices = env.getScreenDevices();
GraphicsDevice target = null;
// search for the first target screen
for( int i = 0; i < devices.length; i++ ) {
boolean isPrimary = (primary == devices[i]);
if( !isPrimary ) {
target = devices[i];
break;
}
}
if( target != null ) {
DisplayMode pmode = primary.getDisplayMode();
DisplayMode tmode = target.getDisplayMode();
Display.setLocation( pmode.getWidth() + (tmode.getWidth() - config.width) / 2,
(tmode.getHeight() - config.height) / 2 );
}
}
}
|
diff --git a/src/cytoscape/actions/ImportNodeAttributesAction.java b/src/cytoscape/actions/ImportNodeAttributesAction.java
index 53cf41a10..d8386d4ac 100644
--- a/src/cytoscape/actions/ImportNodeAttributesAction.java
+++ b/src/cytoscape/actions/ImportNodeAttributesAction.java
@@ -1,201 +1,191 @@
/*
File: ImportNodeAttributesAction.java
Copyright (c) 2006, The Cytoscape Consortium (www.cytoscape.org)
The Cytoscape Consortium is:
- Institute for Systems Biology
- University of California San Diego
- Memorial Sloan-Kettering Cancer Center
- Institut Pasteur
- Agilent Technologies
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
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. The software and
documentation provided hereunder is on an "as is" basis, and the
Institute for Systems Biology and the Whitehead Institute
have no obligations to provide maintenance, support,
updates, enhancements or modifications. In no event shall the
Institute for Systems Biology and the Whitehead Institute
be liable to any party for direct, indirect, special,
incidental or consequential damages, including lost profits, arising
out of the use of this software and its documentation, even if the
Institute for Systems Biology and the Whitehead Institute
have been advised of the possibility of such damage. 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.
*/
// $Revision$
// $Date$
// $Author$
package cytoscape.actions;
import cytoscape.Cytoscape;
import cytoscape.CytoscapeInit;
import cytoscape.data.servers.BioDataServer;
import cytoscape.task.Task;
import cytoscape.task.TaskMonitor;
import cytoscape.task.util.TaskManager;
import cytoscape.task.ui.JTaskConfig;
import cytoscape.util.CyFileFilter;
import cytoscape.util.CytoscapeAction;
import cytoscape.util.FileUtil;
import java.awt.event.ActionEvent;
import java.io.File;
/*
* Added by T. Ideker April 16, 2003
* to allow loading of node / edge attributes from the GUI
*/
public class ImportNodeAttributesAction extends CytoscapeAction {
/**
* Constructor.
*/
public ImportNodeAttributesAction() {
super("Node Attributes...");
setPreferredMenu("File.Import");
}
/**
* User Initiated Request.
*
* @param e Action Event.
*/
public void actionPerformed(ActionEvent e) {
// Use a Default CyFileFilter: enables user to select any file type.
CyFileFilter nf = new CyFileFilter();
// get the file name
File[] files = FileUtil.getFiles("Import Node Attributes",
FileUtil.LOAD, new CyFileFilter[]{nf});
if (files != null) {
// Create Load Attributes Task
ImportAttributesTask task =
new ImportAttributesTask (files, ImportAttributesTask.NODE_ATTRIBUTES);
// Configure JTask Dialog Pop-Up Box
JTaskConfig jTaskConfig = new JTaskConfig();
jTaskConfig.setOwner(Cytoscape.getDesktop());
jTaskConfig.displayCloseButton(true);
jTaskConfig.displayStatus(true);
jTaskConfig.setAutoDispose(false);
// Execute Task in New Thread; pop open JTask Dialog Box.
TaskManager.executeTask(task, jTaskConfig);
}
}
}
/**
* Task to Load New Node/Edge Attributes Data.
*/
class ImportAttributesTask implements Task {
private TaskMonitor taskMonitor;
private File[] files;
private int type;
static final int NODE_ATTRIBUTES = 0;
static final int EDGE_ATTRIBUTES = 1;
/**
* Constructor.
* @param file File Object.
* @param type NODE_ATTRIBUTES or EDGE_ATTRIBUTES
*/
ImportAttributesTask (File[] files, int type) {
this.files = files;
this.type = type;
}
/**
* Executes Task.
*/
public void run() {
try {
taskMonitor.setPercentCompleted(-1);
taskMonitor.setStatus("Reading in Attributes");
- // Get Defaults.
- BioDataServer bioDataServer = Cytoscape.getBioDataServer();
- String speciesName = CytoscapeInit.getProperties().getProperty("defaultSpeciesName");
- boolean canonicalize = CytoscapeInit.getProperties().getProperty("canonicalizeNames").equals("true");
// Read in Data
// track progress. CyAttributes has separation between
// reading attributes and storing them
// so we need to find a different way of monitoring this task:
// attributes.setTaskMonitor(taskMonitor);
for (int i=0; i<files.length; ++i) {
taskMonitor.setPercentCompleted(100*i/files.length);
if ( type == NODE_ATTRIBUTES )
Cytoscape.loadAttributes( new String[] { files[i].getAbsolutePath() },
- new String[] {},
- canonicalize,
- bioDataServer,
- speciesName );
+ new String[] {});
else if ( type == EDGE_ATTRIBUTES )
Cytoscape.loadAttributes( new String[] {},
- new String[] { files[i].getAbsolutePath() },
- canonicalize,
- bioDataServer,
- speciesName );
+ new String[] { files[i].getAbsolutePath() });
else
throw new Exception("Unknown attribute type: " + Integer.toString(type) );
}
// Inform others via property change event.
taskMonitor.setPercentCompleted(100);
Cytoscape.firePropertyChange(Cytoscape.ATTRIBUTES_CHANGED, null, null );
taskMonitor.setStatus("Done");
} catch (Exception e) {
taskMonitor.setException(e, e.getMessage());
}
}
/**
* Halts the Task: Not Currently Implemented.
*/
public void halt() {
// Task can not currently be halted.
}
/**
* Sets the Task Monitor Object.
* @param taskMonitor
* @throws IllegalThreadStateException
*/
public void setTaskMonitor(TaskMonitor taskMonitor)
throws IllegalThreadStateException {
this.taskMonitor = taskMonitor;
}
/**
* Gets the Task Title.
*
* @return Task Title.
*/
public String getTitle() {
if (type == NODE_ATTRIBUTES) {
return new String ("Loading Node Attributes");
} else {
return new String ("Loading Edge Attributes");
}
}
}
| false | true | public void run() {
try {
taskMonitor.setPercentCompleted(-1);
taskMonitor.setStatus("Reading in Attributes");
// Get Defaults.
BioDataServer bioDataServer = Cytoscape.getBioDataServer();
String speciesName = CytoscapeInit.getProperties().getProperty("defaultSpeciesName");
boolean canonicalize = CytoscapeInit.getProperties().getProperty("canonicalizeNames").equals("true");
// Read in Data
// track progress. CyAttributes has separation between
// reading attributes and storing them
// so we need to find a different way of monitoring this task:
// attributes.setTaskMonitor(taskMonitor);
for (int i=0; i<files.length; ++i) {
taskMonitor.setPercentCompleted(100*i/files.length);
if ( type == NODE_ATTRIBUTES )
Cytoscape.loadAttributes( new String[] { files[i].getAbsolutePath() },
new String[] {},
canonicalize,
bioDataServer,
speciesName );
else if ( type == EDGE_ATTRIBUTES )
Cytoscape.loadAttributes( new String[] {},
new String[] { files[i].getAbsolutePath() },
canonicalize,
bioDataServer,
speciesName );
else
throw new Exception("Unknown attribute type: " + Integer.toString(type) );
}
// Inform others via property change event.
taskMonitor.setPercentCompleted(100);
Cytoscape.firePropertyChange(Cytoscape.ATTRIBUTES_CHANGED, null, null );
taskMonitor.setStatus("Done");
} catch (Exception e) {
taskMonitor.setException(e, e.getMessage());
}
}
| public void run() {
try {
taskMonitor.setPercentCompleted(-1);
taskMonitor.setStatus("Reading in Attributes");
// Read in Data
// track progress. CyAttributes has separation between
// reading attributes and storing them
// so we need to find a different way of monitoring this task:
// attributes.setTaskMonitor(taskMonitor);
for (int i=0; i<files.length; ++i) {
taskMonitor.setPercentCompleted(100*i/files.length);
if ( type == NODE_ATTRIBUTES )
Cytoscape.loadAttributes( new String[] { files[i].getAbsolutePath() },
new String[] {});
else if ( type == EDGE_ATTRIBUTES )
Cytoscape.loadAttributes( new String[] {},
new String[] { files[i].getAbsolutePath() });
else
throw new Exception("Unknown attribute type: " + Integer.toString(type) );
}
// Inform others via property change event.
taskMonitor.setPercentCompleted(100);
Cytoscape.firePropertyChange(Cytoscape.ATTRIBUTES_CHANGED, null, null );
taskMonitor.setStatus("Done");
} catch (Exception e) {
taskMonitor.setException(e, e.getMessage());
}
}
|
diff --git a/src/java/nl/b3p/viewer/stripes/ComponentActionBean.java b/src/java/nl/b3p/viewer/stripes/ComponentActionBean.java
index 0ddabb3cf..a2bc8bef9 100644
--- a/src/java/nl/b3p/viewer/stripes/ComponentActionBean.java
+++ b/src/java/nl/b3p/viewer/stripes/ComponentActionBean.java
@@ -1,267 +1,269 @@
/*
* Copyright (C) 2012 B3Partners B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.b3p.viewer.stripes;
import com.google.javascript.jscomp.Compiler;
import com.google.javascript.jscomp.CompilationLevel;
import com.google.javascript.jscomp.CompilerOptions;
import com.google.javascript.jscomp.JSSourceFile;
import java.util.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.http.HttpServletResponse;
import net.sourceforge.stripes.action.*;
import net.sourceforge.stripes.controller.LifecycleStage;
import net.sourceforge.stripes.validation.*;
import nl.b3p.viewer.components.ViewerComponent;
import nl.b3p.viewer.config.app.Application;
import nl.b3p.viewer.config.app.ConfiguredComponent;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* @author Matthijs Laan
*/
@UrlBinding("/app/component/{className}/{$event}/{file}")
@StrictBinding
public class ComponentActionBean implements ActionBean {
private static final Log log = LogFactory.getLog(ComponentActionBean.class);
@Validate
private String app;
@Validate
private String version;
@Validate
private String className;
@Validate
private String file;
@Validate
private boolean minified;
private Application application;
private ViewerComponent component;
private ActionBeanContext context;
private static final Map<String,Object[]> minifiedSourceCache = new HashMap<String,Object[]>();
//<editor-fold defaultstate="collapsed" desc="getters and setters">
public void setContext(ActionBeanContext abc) {
this.context = abc;
}
public ActionBeanContext getContext() {
return context;
}
public String getApp() {
return app;
}
public void setApp(String app) {
this.app = app;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public String getFile() {
return file;
}
public void setFile(String file) {
this.file = file;
}
public boolean isMinified() {
return minified;
}
public void setMinified(boolean minified) {
this.minified = minified;
}
//</editor-fold>
@Before(stages=LifecycleStage.EventHandling)
public void load() {
application = ApplicationActionBean.findApplication(app, version);
if(application != null && className != null) {
for(ConfiguredComponent cc: application.getComponents()) {
if(cc.getClassName().equals(className)) {
// TODO: check readers, return SC_FORBIDDEN if not authorized
component = cc.getViewerComponent();
break;
}
}
}
}
@DefaultHandler
public Resolution source() throws IOException {
File[] files = null;
if(component == null) {
// All source files for all components for this application
// Sort list for consistency (error line numbers, cache, etc.)
List<ConfiguredComponent> comps = new ArrayList<ConfiguredComponent>(application.getComponents());
Collections.sort(comps);
Set<String> classNamesDone = new HashSet<String>();
List<File> fileList = new ArrayList<File>();
for(ConfiguredComponent cc: comps) {
if(!classNamesDone.contains(cc.getClassName())) {
classNamesDone.add(cc.getClassName());
// TODO: check readers, skip if not authorized
- fileList.addAll(Arrays.asList(cc.getViewerComponent().getSources()));
+ if(cc.getViewerComponent() != null && cc.getViewerComponent().getSources() != null) {
+ fileList.addAll(Arrays.asList(cc.getViewerComponent().getSources()));
+ }
}
}
files = fileList.toArray(new File[] {});
} else {
// Source files specific to a component
if(file != null) {
// Search for the specified file in the component sources
for(File f: component.getSources()) {
if(f.getName().equals(file)) {
files = new File[] {f};
break;
}
}
if(files == null) {
return new ErrorResolution(HttpServletResponse.SC_NOT_FOUND, file);
}
} else {
// No specific sourcefile requested, return all sourcefiles
// concatenated
files = component.getSources();
}
}
long lastModified = -1;
for(File f: files) {
lastModified = Math.max(lastModified, f.lastModified());
}
if(lastModified != -1) {
long ifModifiedSince = context.getRequest().getDateHeader("If-Modified-Since");
if(ifModifiedSince != -1) {
if(ifModifiedSince >= lastModified) {
return new ErrorResolution(HttpServletResponse.SC_NOT_MODIFIED);
}
}
}
final File[] theFiles = files;
StreamingResolution res = new StreamingResolution("application/javascript") {
@Override
public void stream(HttpServletResponse response) throws Exception {
OutputStream out = response.getOutputStream();
for(File f: theFiles) {
if(theFiles.length != 1) {
out.write(("\n\n// Source file: " + f.getName() + "\n\n").getBytes("UTF-8"));
}
if(isMinified()) {
String minified = getMinifiedSource(f);
if(minified != null) {
out.write(minified.getBytes("UTF-8"));
} else {
IOUtils.copy(new FileInputStream(f), out);
}
} else {
IOUtils.copy(new FileInputStream(f), out);
}
}
}
};
if(lastModified != -1) {
res.setLastModified(lastModified);
}
return res;
}
public Resolution resource() throws IOException {
// TODO conditional HTTP request
// TODO send a resource from the subdirectory "resources" from the components.json dir for the component
getContext().getResponse().sendError(404);
return null;
}
private static synchronized String getMinifiedSource(File f) throws IOException {
String key = f.getCanonicalPath();
Object[] cache = minifiedSourceCache.get(key);
if(cache != null) {
// check last modified time
Long lastModified = (Long)cache[0];
if(!lastModified.equals(f.lastModified())) {
minifiedSourceCache.remove(key);
cache = null;
}
}
if(cache != null) {
return (String)cache[1];
}
String minified = null;
try {
Compiler compiler = new Compiler();
CompilerOptions options = new CompilerOptions();
CompilationLevel.SIMPLE_OPTIMIZATIONS.setOptionsForCompilationLevel(options);
options.setOutputCharset("UTF-8");
compiler.compile(JSSourceFile.fromCode("dummy.js",""), JSSourceFile.fromFile(f), options);
minified = compiler.toSource();
} catch(Exception e) {
log.warn(String.format("Error minifying file \"%s\" using closure compiler, sending original source\n", f.getCanonicalPath()), e);
}
Object[] entry = new Object[] { f.lastModified(), minified};
minifiedSourceCache.put(key, entry);
return minified;
}
}
| true | true | public Resolution source() throws IOException {
File[] files = null;
if(component == null) {
// All source files for all components for this application
// Sort list for consistency (error line numbers, cache, etc.)
List<ConfiguredComponent> comps = new ArrayList<ConfiguredComponent>(application.getComponents());
Collections.sort(comps);
Set<String> classNamesDone = new HashSet<String>();
List<File> fileList = new ArrayList<File>();
for(ConfiguredComponent cc: comps) {
if(!classNamesDone.contains(cc.getClassName())) {
classNamesDone.add(cc.getClassName());
// TODO: check readers, skip if not authorized
fileList.addAll(Arrays.asList(cc.getViewerComponent().getSources()));
}
}
files = fileList.toArray(new File[] {});
} else {
// Source files specific to a component
if(file != null) {
// Search for the specified file in the component sources
for(File f: component.getSources()) {
if(f.getName().equals(file)) {
files = new File[] {f};
break;
}
}
if(files == null) {
return new ErrorResolution(HttpServletResponse.SC_NOT_FOUND, file);
}
} else {
// No specific sourcefile requested, return all sourcefiles
// concatenated
files = component.getSources();
}
}
long lastModified = -1;
for(File f: files) {
lastModified = Math.max(lastModified, f.lastModified());
}
if(lastModified != -1) {
long ifModifiedSince = context.getRequest().getDateHeader("If-Modified-Since");
if(ifModifiedSince != -1) {
if(ifModifiedSince >= lastModified) {
return new ErrorResolution(HttpServletResponse.SC_NOT_MODIFIED);
}
}
}
final File[] theFiles = files;
StreamingResolution res = new StreamingResolution("application/javascript") {
@Override
public void stream(HttpServletResponse response) throws Exception {
OutputStream out = response.getOutputStream();
for(File f: theFiles) {
if(theFiles.length != 1) {
out.write(("\n\n// Source file: " + f.getName() + "\n\n").getBytes("UTF-8"));
}
if(isMinified()) {
String minified = getMinifiedSource(f);
if(minified != null) {
out.write(minified.getBytes("UTF-8"));
} else {
IOUtils.copy(new FileInputStream(f), out);
}
} else {
IOUtils.copy(new FileInputStream(f), out);
}
}
}
};
if(lastModified != -1) {
res.setLastModified(lastModified);
}
return res;
}
| public Resolution source() throws IOException {
File[] files = null;
if(component == null) {
// All source files for all components for this application
// Sort list for consistency (error line numbers, cache, etc.)
List<ConfiguredComponent> comps = new ArrayList<ConfiguredComponent>(application.getComponents());
Collections.sort(comps);
Set<String> classNamesDone = new HashSet<String>();
List<File> fileList = new ArrayList<File>();
for(ConfiguredComponent cc: comps) {
if(!classNamesDone.contains(cc.getClassName())) {
classNamesDone.add(cc.getClassName());
// TODO: check readers, skip if not authorized
if(cc.getViewerComponent() != null && cc.getViewerComponent().getSources() != null) {
fileList.addAll(Arrays.asList(cc.getViewerComponent().getSources()));
}
}
}
files = fileList.toArray(new File[] {});
} else {
// Source files specific to a component
if(file != null) {
// Search for the specified file in the component sources
for(File f: component.getSources()) {
if(f.getName().equals(file)) {
files = new File[] {f};
break;
}
}
if(files == null) {
return new ErrorResolution(HttpServletResponse.SC_NOT_FOUND, file);
}
} else {
// No specific sourcefile requested, return all sourcefiles
// concatenated
files = component.getSources();
}
}
long lastModified = -1;
for(File f: files) {
lastModified = Math.max(lastModified, f.lastModified());
}
if(lastModified != -1) {
long ifModifiedSince = context.getRequest().getDateHeader("If-Modified-Since");
if(ifModifiedSince != -1) {
if(ifModifiedSince >= lastModified) {
return new ErrorResolution(HttpServletResponse.SC_NOT_MODIFIED);
}
}
}
final File[] theFiles = files;
StreamingResolution res = new StreamingResolution("application/javascript") {
@Override
public void stream(HttpServletResponse response) throws Exception {
OutputStream out = response.getOutputStream();
for(File f: theFiles) {
if(theFiles.length != 1) {
out.write(("\n\n// Source file: " + f.getName() + "\n\n").getBytes("UTF-8"));
}
if(isMinified()) {
String minified = getMinifiedSource(f);
if(minified != null) {
out.write(minified.getBytes("UTF-8"));
} else {
IOUtils.copy(new FileInputStream(f), out);
}
} else {
IOUtils.copy(new FileInputStream(f), out);
}
}
}
};
if(lastModified != -1) {
res.setLastModified(lastModified);
}
return res;
}
|
diff --git a/geopaparazzi.app/src/eu/hydrologis/geopaparazzi/maps/overlays/MapsOverlay.java b/geopaparazzi.app/src/eu/hydrologis/geopaparazzi/maps/overlays/MapsOverlay.java
index 0df14afd..9122eaa5 100644
--- a/geopaparazzi.app/src/eu/hydrologis/geopaparazzi/maps/overlays/MapsOverlay.java
+++ b/geopaparazzi.app/src/eu/hydrologis/geopaparazzi/maps/overlays/MapsOverlay.java
@@ -1,244 +1,244 @@
/*
* Geopaparazzi - Digital field mapping on Android based devices
* Copyright (C) 2010 HydroloGIS (www.hydrologis.com)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.hydrologis.geopaparazzi.maps.overlays;
import static eu.hydrologis.geopaparazzi.util.Constants.E6;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import org.osmdroid.ResourceProxy;
import org.osmdroid.util.BoundingBoxE6;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.MapView.Projection;
import org.osmdroid.views.overlay.Overlay;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.graphics.Rect;
import android.preference.PreferenceManager;
import android.view.MotionEvent;
import eu.hydrologis.geopaparazzi.R;
import eu.hydrologis.geopaparazzi.database.DaoMaps;
import eu.hydrologis.geopaparazzi.maps.DataManager;
import eu.hydrologis.geopaparazzi.maps.MapItem;
import eu.hydrologis.geopaparazzi.util.ApplicationManager;
import eu.hydrologis.geopaparazzi.util.Constants;
import eu.hydrologis.geopaparazzi.util.PointsContainer;
import eu.hydrologis.geopaparazzi.util.debug.Logger;
/**
* Overlay to show imported maps.
*
* @author Andrea Antonello (www.hydrologis.com)
*/
public class MapsOverlay extends Overlay {
private Paint gpxPaint = new Paint();
private Context context;
private int decimationFactor;
final private Rect screenRect = new Rect();
private boolean touchDragging = false;
private boolean doDraw = true;
private boolean gpsUpdate = false;
private int zoomLevel1;
private int zoomLevel2;
private int zoomLevelLabelLength1;
private int zoomLevelLabelLength2;
private Paint gpxTextPaint;
public MapsOverlay( final Context ctx, final ResourceProxy pResourceProxy ) {
super(pResourceProxy);
this.context = ctx;
ApplicationManager applicationManager = ApplicationManager.getInstance(context);
decimationFactor = applicationManager.getDecimationFactor();
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
zoomLevel1 = Integer.parseInt(preferences.getString(Constants.PREFS_KEY_ZOOM1, "14"));
zoomLevel2 = Integer.parseInt(preferences.getString(Constants.PREFS_KEY_ZOOM2, "16"));
zoomLevelLabelLength1 = Integer.parseInt(preferences.getString(Constants.PREFS_KEY_ZOOM1_LABELLENGTH, "4"));
zoomLevelLabelLength2 = Integer.parseInt(preferences.getString(Constants.PREFS_KEY_ZOOM2_LABELLENGTH, "-1"));
float textSizeMedium = ctx.getResources().getDimension(R.dimen.text_normal);
gpxPaint = new Paint();
gpxTextPaint = new Paint();
gpxTextPaint.setAntiAlias(true);
gpxTextPaint.setTextSize(textSizeMedium);
}
public void setDoDraw( boolean doDraw ) {
this.doDraw = doDraw;
Logger.d(this, "Will draw: " + doDraw);
}
public void setGpsUpdate( boolean gpsUpdate ) {
this.gpsUpdate = gpsUpdate;
}
private HashMap<MapItem, PointsContainer> pointsContainerMap = new HashMap<MapItem, PointsContainer>();
protected void draw( final Canvas canvas, final MapView mapsView, final boolean shadow ) {
if (touchDragging || shadow || !doDraw || mapsView.isAnimating() || !DataManager.getInstance().areLogsVisible())
return;
BoundingBoxE6 boundingBox = mapsView.getBoundingBox();
float y0 = boundingBox.getLatNorthE6() / E6;
float y1 = boundingBox.getLatSouthE6() / E6;
float x0 = boundingBox.getLonWestE6() / E6;
float x1 = boundingBox.getLonEastE6() / E6;
Projection pj = mapsView.getProjection();
int screenWidth = canvas.getWidth();
int screenHeight = canvas.getHeight();
screenRect.contains(0, 0, screenWidth, screenHeight);
mapsView.getScreenRect(screenRect);
int zoomLevel = mapsView.getZoomLevel();
try {
List<MapItem> mapsMap = DaoMaps.getMaps(context);
if (!gpsUpdate) {
pointsContainerMap.clear();
for( MapItem mapItem : mapsMap ) {
if (!mapItem.isVisible()) {
continue;
}
PointsContainer coordsContainer = DaoMaps.getCoordinatesInWorldBoundsForMapIdDecimated2(context,
mapItem.getId(), y0, y1, x0, x1, pj, decimationFactor);
if (coordsContainer == null) {
continue;
}
pointsContainerMap.put(mapItem, coordsContainer);
}
}
Set<Entry<MapItem, PointsContainer>> entrySet = pointsContainerMap.entrySet();
for( Entry<MapItem, PointsContainer> entry : entrySet ) {
MapItem mapItem = entry.getKey();
PointsContainer coordsContainer = entry.getValue();
if (mapItem.getType() == Constants.MAP_TYPE_LINE) {
gpxPaint.setAntiAlias(true);
gpxPaint.setColor(Color.parseColor(mapItem.getColor()));
gpxPaint.setStrokeWidth(mapItem.getWidth());
gpxPaint.setStyle(Paint.Style.STROKE);
gpxPaint.setStrokeJoin(Paint.Join.ROUND);
gpxPaint.setStrokeCap(Paint.Cap.ROUND);
Path path = new Path();
float prevScreenX = Float.POSITIVE_INFINITY;
float prevScreenY = Float.POSITIVE_INFINITY;
float[] latArray = coordsContainer.getLatArray();
float[] lonArray = coordsContainer.getLonArray();
final Point p = new Point();
for( int i = 0; i < coordsContainer.getIndex(); i++ ) {
pj.toMapPixels(new GeoPoint(latArray[i], lonArray[i]), p);
float screenX = p.x;
float screenY = p.y;
// Logger.d(LOGTAG, screenX + "/" + screenY);
if (i == 0) {
path.moveTo(screenX, screenY);
} else {
if (prevScreenX == screenX && prevScreenY == screenY) {
continue;
}
path.lineTo(screenX, screenY);
prevScreenX = screenX;
prevScreenY = screenY;
}
}
canvas.drawPath(path, gpxPaint);
} else if (mapItem.getType() == Constants.MAP_TYPE_POINT) {
gpxPaint.setAntiAlias(true);
gpxPaint.setColor(Color.parseColor(mapItem.getColor()));
gpxPaint.setStrokeWidth(mapItem.getWidth());
gpxPaint.setStyle(Paint.Style.FILL);
float[] latArray = coordsContainer.getLatArray();
float[] lonArray = coordsContainer.getLonArray();
String[] namesArray = coordsContainer.getNamesArray();
// boolean hasNames = namesArray.length == latArray.length;
final Point p = new Point();
for( int i = 0; i < coordsContainer.getIndex(); i++ ) {
pj.toMapPixels(new GeoPoint(latArray[i], lonArray[i]), p);
float screenX = p.x;
float screenY = p.y;
canvas.drawPoint(screenX, screenY, gpxPaint);
- drawLabel(canvas, namesArray[i], lonArray[i], latArray[i], gpxTextPaint, zoomLevel);
+ drawLabel(canvas, namesArray[i], screenX, screenY, gpxTextPaint, zoomLevel);
}
}
}
} catch (IOException e) {
Logger.e(this, e.getLocalizedMessage(), e);
e.printStackTrace();
}
}
private void drawLabel( Canvas canvas, String label, float positionX, float positionY, Paint paint, int zoom ) {
if (label == null || label.length() == 0) {
return;
}
if (zoom >= zoomLevel1) {
if (zoom < zoomLevel2) {
if (zoomLevelLabelLength1 != -1 && label.length() > zoomLevelLabelLength1) {
label = label.substring(0, zoomLevelLabelLength1);
}
} else {
if (zoomLevelLabelLength2 != -1 && label.length() > zoomLevelLabelLength2) {
label = label.substring(0, zoomLevelLabelLength2);
}
}
canvas.drawText(label, positionX, positionY, paint);
// Logger.d(this, "WRITING: " + label);
}
}
@Override
public boolean onTouchEvent( MotionEvent event, MapView mapView ) {
int action = event.getAction();
switch( action ) {
case MotionEvent.ACTION_MOVE:
touchDragging = true;
break;
case MotionEvent.ACTION_UP:
touchDragging = false;
mapView.invalidate();
break;
}
return super.onTouchEvent(event, mapView);
}
}
| true | true | protected void draw( final Canvas canvas, final MapView mapsView, final boolean shadow ) {
if (touchDragging || shadow || !doDraw || mapsView.isAnimating() || !DataManager.getInstance().areLogsVisible())
return;
BoundingBoxE6 boundingBox = mapsView.getBoundingBox();
float y0 = boundingBox.getLatNorthE6() / E6;
float y1 = boundingBox.getLatSouthE6() / E6;
float x0 = boundingBox.getLonWestE6() / E6;
float x1 = boundingBox.getLonEastE6() / E6;
Projection pj = mapsView.getProjection();
int screenWidth = canvas.getWidth();
int screenHeight = canvas.getHeight();
screenRect.contains(0, 0, screenWidth, screenHeight);
mapsView.getScreenRect(screenRect);
int zoomLevel = mapsView.getZoomLevel();
try {
List<MapItem> mapsMap = DaoMaps.getMaps(context);
if (!gpsUpdate) {
pointsContainerMap.clear();
for( MapItem mapItem : mapsMap ) {
if (!mapItem.isVisible()) {
continue;
}
PointsContainer coordsContainer = DaoMaps.getCoordinatesInWorldBoundsForMapIdDecimated2(context,
mapItem.getId(), y0, y1, x0, x1, pj, decimationFactor);
if (coordsContainer == null) {
continue;
}
pointsContainerMap.put(mapItem, coordsContainer);
}
}
Set<Entry<MapItem, PointsContainer>> entrySet = pointsContainerMap.entrySet();
for( Entry<MapItem, PointsContainer> entry : entrySet ) {
MapItem mapItem = entry.getKey();
PointsContainer coordsContainer = entry.getValue();
if (mapItem.getType() == Constants.MAP_TYPE_LINE) {
gpxPaint.setAntiAlias(true);
gpxPaint.setColor(Color.parseColor(mapItem.getColor()));
gpxPaint.setStrokeWidth(mapItem.getWidth());
gpxPaint.setStyle(Paint.Style.STROKE);
gpxPaint.setStrokeJoin(Paint.Join.ROUND);
gpxPaint.setStrokeCap(Paint.Cap.ROUND);
Path path = new Path();
float prevScreenX = Float.POSITIVE_INFINITY;
float prevScreenY = Float.POSITIVE_INFINITY;
float[] latArray = coordsContainer.getLatArray();
float[] lonArray = coordsContainer.getLonArray();
final Point p = new Point();
for( int i = 0; i < coordsContainer.getIndex(); i++ ) {
pj.toMapPixels(new GeoPoint(latArray[i], lonArray[i]), p);
float screenX = p.x;
float screenY = p.y;
// Logger.d(LOGTAG, screenX + "/" + screenY);
if (i == 0) {
path.moveTo(screenX, screenY);
} else {
if (prevScreenX == screenX && prevScreenY == screenY) {
continue;
}
path.lineTo(screenX, screenY);
prevScreenX = screenX;
prevScreenY = screenY;
}
}
canvas.drawPath(path, gpxPaint);
} else if (mapItem.getType() == Constants.MAP_TYPE_POINT) {
gpxPaint.setAntiAlias(true);
gpxPaint.setColor(Color.parseColor(mapItem.getColor()));
gpxPaint.setStrokeWidth(mapItem.getWidth());
gpxPaint.setStyle(Paint.Style.FILL);
float[] latArray = coordsContainer.getLatArray();
float[] lonArray = coordsContainer.getLonArray();
String[] namesArray = coordsContainer.getNamesArray();
// boolean hasNames = namesArray.length == latArray.length;
final Point p = new Point();
for( int i = 0; i < coordsContainer.getIndex(); i++ ) {
pj.toMapPixels(new GeoPoint(latArray[i], lonArray[i]), p);
float screenX = p.x;
float screenY = p.y;
canvas.drawPoint(screenX, screenY, gpxPaint);
drawLabel(canvas, namesArray[i], lonArray[i], latArray[i], gpxTextPaint, zoomLevel);
}
}
}
} catch (IOException e) {
Logger.e(this, e.getLocalizedMessage(), e);
e.printStackTrace();
}
}
| protected void draw( final Canvas canvas, final MapView mapsView, final boolean shadow ) {
if (touchDragging || shadow || !doDraw || mapsView.isAnimating() || !DataManager.getInstance().areLogsVisible())
return;
BoundingBoxE6 boundingBox = mapsView.getBoundingBox();
float y0 = boundingBox.getLatNorthE6() / E6;
float y1 = boundingBox.getLatSouthE6() / E6;
float x0 = boundingBox.getLonWestE6() / E6;
float x1 = boundingBox.getLonEastE6() / E6;
Projection pj = mapsView.getProjection();
int screenWidth = canvas.getWidth();
int screenHeight = canvas.getHeight();
screenRect.contains(0, 0, screenWidth, screenHeight);
mapsView.getScreenRect(screenRect);
int zoomLevel = mapsView.getZoomLevel();
try {
List<MapItem> mapsMap = DaoMaps.getMaps(context);
if (!gpsUpdate) {
pointsContainerMap.clear();
for( MapItem mapItem : mapsMap ) {
if (!mapItem.isVisible()) {
continue;
}
PointsContainer coordsContainer = DaoMaps.getCoordinatesInWorldBoundsForMapIdDecimated2(context,
mapItem.getId(), y0, y1, x0, x1, pj, decimationFactor);
if (coordsContainer == null) {
continue;
}
pointsContainerMap.put(mapItem, coordsContainer);
}
}
Set<Entry<MapItem, PointsContainer>> entrySet = pointsContainerMap.entrySet();
for( Entry<MapItem, PointsContainer> entry : entrySet ) {
MapItem mapItem = entry.getKey();
PointsContainer coordsContainer = entry.getValue();
if (mapItem.getType() == Constants.MAP_TYPE_LINE) {
gpxPaint.setAntiAlias(true);
gpxPaint.setColor(Color.parseColor(mapItem.getColor()));
gpxPaint.setStrokeWidth(mapItem.getWidth());
gpxPaint.setStyle(Paint.Style.STROKE);
gpxPaint.setStrokeJoin(Paint.Join.ROUND);
gpxPaint.setStrokeCap(Paint.Cap.ROUND);
Path path = new Path();
float prevScreenX = Float.POSITIVE_INFINITY;
float prevScreenY = Float.POSITIVE_INFINITY;
float[] latArray = coordsContainer.getLatArray();
float[] lonArray = coordsContainer.getLonArray();
final Point p = new Point();
for( int i = 0; i < coordsContainer.getIndex(); i++ ) {
pj.toMapPixels(new GeoPoint(latArray[i], lonArray[i]), p);
float screenX = p.x;
float screenY = p.y;
// Logger.d(LOGTAG, screenX + "/" + screenY);
if (i == 0) {
path.moveTo(screenX, screenY);
} else {
if (prevScreenX == screenX && prevScreenY == screenY) {
continue;
}
path.lineTo(screenX, screenY);
prevScreenX = screenX;
prevScreenY = screenY;
}
}
canvas.drawPath(path, gpxPaint);
} else if (mapItem.getType() == Constants.MAP_TYPE_POINT) {
gpxPaint.setAntiAlias(true);
gpxPaint.setColor(Color.parseColor(mapItem.getColor()));
gpxPaint.setStrokeWidth(mapItem.getWidth());
gpxPaint.setStyle(Paint.Style.FILL);
float[] latArray = coordsContainer.getLatArray();
float[] lonArray = coordsContainer.getLonArray();
String[] namesArray = coordsContainer.getNamesArray();
// boolean hasNames = namesArray.length == latArray.length;
final Point p = new Point();
for( int i = 0; i < coordsContainer.getIndex(); i++ ) {
pj.toMapPixels(new GeoPoint(latArray[i], lonArray[i]), p);
float screenX = p.x;
float screenY = p.y;
canvas.drawPoint(screenX, screenY, gpxPaint);
drawLabel(canvas, namesArray[i], screenX, screenY, gpxTextPaint, zoomLevel);
}
}
}
} catch (IOException e) {
Logger.e(this, e.getLocalizedMessage(), e);
e.printStackTrace();
}
}
|
diff --git a/EDUkid/src/bu/edu/cs673/edukid/settings/useraccount/UserAccountView.java b/EDUkid/src/bu/edu/cs673/edukid/settings/useraccount/UserAccountView.java
index 1f61f63..00259b5 100644
--- a/EDUkid/src/bu/edu/cs673/edukid/settings/useraccount/UserAccountView.java
+++ b/EDUkid/src/bu/edu/cs673/edukid/settings/useraccount/UserAccountView.java
@@ -1,194 +1,197 @@
package bu.edu.cs673.edukid.settings.useraccount;
import java.io.IOException;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import android.media.*;
import bu.edu.cs673.edukid.R;
import bu.edu.cs673.edukid.db.Database;
import bu.edu.cs673.edukid.db.ImageUtils;
import bu.edu.cs673.edukid.db.model.UserAccount;
/**
* The view which contains the user account information. The user account can be
* seen and edited here.
*
* @author Peter Trevino
*
* @see UserAccount
*
*/
public class UserAccountView extends Activity implements OnClickListener {
private static final int TAKE_PICTURE = 1888;
private boolean mStartRecording = true;
private static final long DATABASE_ERROR = -1;
private String userName;
private ImageView userImage;
private ImageView micImage;
private Database database = Database.getInstance(this);
public MediaRecorder recorder = new MediaRecorder();
private String mFileName = "";
/**
* {@inheritDoc}
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_account);
userImage = (ImageView) findViewById(R.id.createUserImage);
micImage = (ImageView) findViewById(R.id.accountCreationRecorderButton);
// Populate user account info from database (if any)
List<UserAccount> userAccounts = database.getUserAccounts();
if (userAccounts.size() == 1) {
UserAccount userAccount = userAccounts.get(0);
// Set user name
EditText userNameTextField = ((EditText) findViewById(R.id.createEditChildName));
userNameTextField.setText(userAccount.getUserName());
// Set user image
userImage.setImageDrawable(ImageUtils
.byteArrayToDrawable(userAccount.getUserImage()));
+ userImage.setMaxHeight(400);
+ userImage.setMaxWidth(400);
+ userImage.setAdjustViewBounds(false);
}
// Add listeners
Button createSaveButton = (Button) findViewById(R.id.createSaveButton);
createSaveButton.setOnClickListener(this);
ImageButton createUploadPhotoButton = (ImageButton) findViewById(R.id.createUploadPhotoButton);
createUploadPhotoButton.setOnClickListener(this);
micImage.setOnClickListener(this);
}
/**
* {@inheritDoc}
*/
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.createSaveButton:
saveUserAccount();
break;
case R.id.createUploadPhotoButton:
// TODO: we should have other options other than the camera like
// picking from the camera roll
startCamera();
break;
case R.id.accountCreationRecorderButton:
// TODO:have state of button switch between start and stop recording
onRecord(mStartRecording);
mStartRecording = !mStartRecording;
break;
}
}
/**
* {@inheritDoc}
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK) {
Bitmap photo = (Bitmap) data.getExtras().get("data");
if (photo != null) {
userImage.setImageBitmap(photo);
}
}
}
/**
* Saves the user account in the database.
*/
private void saveUserAccount() {
userName = ((EditText) findViewById(R.id.createEditChildName))
.getText().toString();
List<UserAccount> userAccounts = database.getUserAccounts();
long result = DATABASE_ERROR;
if (userAccounts.size() == 0) {
// TODO: Peter: replace "" with real user sound.
result = database.addUserAccount(userName, "",
userImage.getDrawable());
} else if (userAccounts.size() == 1) {
UserAccount userAccount = userAccounts.get(0);
userAccount.setUserName(userName);
userAccount.setUserImage(ImageUtils.drawableToByteArray(userImage
.getDrawable()));
result = database.editUserAccount(userAccount);
} else {
// TODO: implement more than 1 user. Should not get here now.
}
if (result != DATABASE_ERROR) {
Toast.makeText(this, "User account saved successfully!",
Toast.LENGTH_LONG).show();
} else {
// TODO: inform user of error
}
}
/**
* Starts the front facing camera to take a picture.
*/
private void startCamera() {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, TAKE_PICTURE);
}
public void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void startRecording() {
micImage.setBackgroundResource(R.drawable.abacus);
recorder = new MediaRecorder();
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/audiorecordtest.3gp";
recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
recorder.setOutputFile(mFileName);
try {
recorder.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
recorder.start();
}
private void stopRecording() {
micImage.setBackgroundResource(R.drawable.mikebutton);
recorder.stop();
recorder.release();
recorder = null;
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_account);
userImage = (ImageView) findViewById(R.id.createUserImage);
micImage = (ImageView) findViewById(R.id.accountCreationRecorderButton);
// Populate user account info from database (if any)
List<UserAccount> userAccounts = database.getUserAccounts();
if (userAccounts.size() == 1) {
UserAccount userAccount = userAccounts.get(0);
// Set user name
EditText userNameTextField = ((EditText) findViewById(R.id.createEditChildName));
userNameTextField.setText(userAccount.getUserName());
// Set user image
userImage.setImageDrawable(ImageUtils
.byteArrayToDrawable(userAccount.getUserImage()));
}
// Add listeners
Button createSaveButton = (Button) findViewById(R.id.createSaveButton);
createSaveButton.setOnClickListener(this);
ImageButton createUploadPhotoButton = (ImageButton) findViewById(R.id.createUploadPhotoButton);
createUploadPhotoButton.setOnClickListener(this);
micImage.setOnClickListener(this);
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_account);
userImage = (ImageView) findViewById(R.id.createUserImage);
micImage = (ImageView) findViewById(R.id.accountCreationRecorderButton);
// Populate user account info from database (if any)
List<UserAccount> userAccounts = database.getUserAccounts();
if (userAccounts.size() == 1) {
UserAccount userAccount = userAccounts.get(0);
// Set user name
EditText userNameTextField = ((EditText) findViewById(R.id.createEditChildName));
userNameTextField.setText(userAccount.getUserName());
// Set user image
userImage.setImageDrawable(ImageUtils
.byteArrayToDrawable(userAccount.getUserImage()));
userImage.setMaxHeight(400);
userImage.setMaxWidth(400);
userImage.setAdjustViewBounds(false);
}
// Add listeners
Button createSaveButton = (Button) findViewById(R.id.createSaveButton);
createSaveButton.setOnClickListener(this);
ImageButton createUploadPhotoButton = (ImageButton) findViewById(R.id.createUploadPhotoButton);
createUploadPhotoButton.setOnClickListener(this);
micImage.setOnClickListener(this);
}
|
diff --git a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/io/dav/http/HTTPConnection.java b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/io/dav/http/HTTPConnection.java
index 192dec69c..345f023ef 100644
--- a/svnkit/src/main/java/org/tmatesoft/svn/core/internal/io/dav/http/HTTPConnection.java
+++ b/svnkit/src/main/java/org/tmatesoft/svn/core/internal/io/dav/http/HTTPConnection.java
@@ -1,1146 +1,1148 @@
/*
* ====================================================================
* Copyright (c) 2004-2012 TMate Software Ltd. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://svnkit.com/license.html
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
* ====================================================================
*/
package org.tmatesoft.svn.core.internal.io.dav.http;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import javax.net.ssl.KeyManager;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;
import javax.net.ssl.TrustManager;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.tmatesoft.svn.core.SVNCancelException;
import org.tmatesoft.svn.core.SVNErrorCode;
import org.tmatesoft.svn.core.SVNErrorMessage;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.auth.BasicAuthenticationManager;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManager;
import org.tmatesoft.svn.core.auth.ISVNAuthenticationManagerExt;
import org.tmatesoft.svn.core.auth.ISVNProxyManager;
import org.tmatesoft.svn.core.auth.SVNAuthentication;
import org.tmatesoft.svn.core.auth.SVNPasswordAuthentication;
import org.tmatesoft.svn.core.internal.io.dav.handlers.DAVErrorHandler;
import org.tmatesoft.svn.core.internal.util.ChunkedInputStream;
import org.tmatesoft.svn.core.internal.util.FixedSizeInputStream;
import org.tmatesoft.svn.core.internal.util.SVNSSLUtil;
import org.tmatesoft.svn.core.internal.util.SVNSocketFactory;
import org.tmatesoft.svn.core.internal.wc.DefaultSVNAuthenticationManager;
import org.tmatesoft.svn.core.internal.wc.IOExceptionWrapper;
import org.tmatesoft.svn.core.internal.wc.SVNCancellableOutputStream;
import org.tmatesoft.svn.core.internal.wc.SVNErrorManager;
import org.tmatesoft.svn.core.internal.wc.SVNFileUtil;
import org.tmatesoft.svn.core.io.SVNRepository;
import org.tmatesoft.svn.util.ISVNDebugLog;
import org.tmatesoft.svn.util.SVNDebugLog;
import org.tmatesoft.svn.util.SVNLogType;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;
/**
* @version 1.3
* @author TMate Software Ltd.
*/
public class HTTPConnection implements IHTTPConnection {
private static final DefaultHandler DEFAULT_SAX_HANDLER = new DefaultHandler();
private static EntityResolver NO_ENTITY_RESOLVER = new EntityResolver() {
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
return new InputSource(new ByteArrayInputStream(new byte[0]));
}
};
private static final int requestAttempts;
private static final int DEFAULT_HTTP_TIMEOUT = 3600*1000;
static {
String attemptsString = System.getProperty("svnkit.http.requestAttempts", "1" );
int attempts = 1;
try {
attempts = Integer.parseInt(attemptsString);
} catch (NumberFormatException nfe) {
attempts = 1;
}
if (attempts <= 0) {
attempts = 1;
}
requestAttempts = attempts;
}
private static SAXParserFactory ourSAXParserFactory;
private byte[] myBuffer;
private SAXParser mySAXParser;
private SVNURL myHost;
private OutputStream myOutputStream;
private InputStream myInputStream;
private Socket mySocket;
private SVNRepository myRepository;
private boolean myIsSecured;
private boolean myIsProxied;
private SVNAuthentication myLastValidAuth;
private HTTPAuthentication myChallengeCredentials;
private HTTPAuthentication myProxyAuthentication;
private boolean myIsSpoolResponse;
private TrustManager myTrustManager;
private HTTPSSLKeyManager myKeyManager;
private String myCharset;
private boolean myIsSpoolAll;
private File mySpoolDirectory;
private long myNextRequestTimeout;
private Collection<String> myCookies;
private int myRequestCount;
private HTTPStatus myLastStatus;
public HTTPConnection(SVNRepository repository, String charset, File spoolDirectory, boolean spoolAll) throws SVNException {
myRepository = repository;
myCharset = charset;
myHost = repository.getLocation().setPath("", false);
myIsSecured = "https".equalsIgnoreCase(myHost.getProtocol());
myIsSpoolAll = spoolAll;
mySpoolDirectory = spoolDirectory;
myNextRequestTimeout = Long.MAX_VALUE;
}
public HTTPStatus getLastStatus() {
return myLastStatus;
}
public SVNURL getHost() {
return myHost;
}
private void connect(HTTPSSLKeyManager keyManager, TrustManager trustManager, ISVNProxyManager proxyManager) throws IOException, SVNException {
SVNURL location = myRepository.getLocation();
if (mySocket == null || SVNSocketFactory.isSocketStale(mySocket)) {
close();
String host = location.getHost();
int port = location.getPort();
ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager();
int connectTimeout = authManager != null ? authManager.getConnectTimeout(myRepository) : 0;
int readTimeout = authManager != null ? authManager.getReadTimeout(myRepository) : DEFAULT_HTTP_TIMEOUT;
if (readTimeout < 0) {
readTimeout = DEFAULT_HTTP_TIMEOUT;
}
if (proxyManager != null && proxyManager.getProxyHost() != null) {
final ISVNDebugLog debugLog = myRepository.getDebugLog();
debugLog.logFine(SVNLogType.NETWORK, "Using proxy " + proxyManager.getProxyHost() + " (secured=" + myIsSecured + ")");
mySocket = SVNSocketFactory.createPlainSocket(proxyManager.getProxyHost(), proxyManager.getProxyPort(), connectTimeout, readTimeout, myRepository.getCanceller());
myIsProxied = true;
if (myIsSecured) {
int authAttempts = 0;
boolean credentialsUsed = false;
while(true) {
if (mySocket == null) {
mySocket = SVNSocketFactory.createPlainSocket(proxyManager.getProxyHost(), proxyManager.getProxyPort(), connectTimeout, readTimeout, myRepository.getCanceller());
debugLog.logFine(SVNLogType.NETWORK, "proxy connection reopened");
}
HTTPRequest connectRequest = new HTTPRequest(myCharset);
connectRequest.setConnection(this);
if (myProxyAuthentication != null) {
final String authToken = myProxyAuthentication.authenticate();
connectRequest.setProxyAuthentication(authToken);
debugLog.logFine(SVNLogType.NETWORK, "auth token set: " + authToken);
}
connectRequest.setForceProxyAuth(true);
connectRequest.dispatch("CONNECT", host + ":" + port, null, 0, 0, null);
HTTPStatus status = connectRequest.getStatus();
if (status.getCode() == HttpURLConnection.HTTP_OK) {
myInputStream = null;
myOutputStream = null;
myProxyAuthentication = null;
mySocket = SVNSocketFactory.createSSLSocket(keyManager != null ? new KeyManager[] { keyManager } : new KeyManager[0], trustManager, host, port, mySocket, readTimeout);
proxyManager.acknowledgeProxyContext(true, null);
return;
} else if (status.getCode() == HttpURLConnection.HTTP_PROXY_AUTH) {
if (hasToCloseConnection(connectRequest.getResponseHeader())) {
close();
debugLog.logFine(SVNLogType.NETWORK, "Connection closed as requested by the response header");
}
authAttempts++;
debugLog.logFine(SVNLogType.NETWORK, "authentication attempt #" + authAttempts);
Collection<String> proxyAuthHeaders = connectRequest.getResponseHeader().getHeaderValues(HTTPHeader.PROXY_AUTHENTICATE_HEADER);
Collection<String> authTypes = Arrays.asList("Basic", "Digest", "Negotiate", "NTLM");
debugLog.logFine(SVNLogType.NETWORK, "authentication methods supported: " + authTypes);
try {
myProxyAuthentication = HTTPAuthentication.parseAuthParameters(proxyAuthHeaders, myProxyAuthentication, myCharset, authTypes, null, myRequestCount);
} catch (SVNException svne) {
myRepository.getDebugLog().logFine(SVNLogType.NETWORK, svne);
close();
throw svne;
}
debugLog.logFine(SVNLogType.NETWORK, "authentication type chosen: " + myProxyAuthentication.getClass().getSimpleName());
connectRequest.initCredentials(myProxyAuthentication, "CONNECT", host + ":" + port);
HTTPNTLMAuthentication ntlmProxyAuth = null;
HTTPNegotiateAuthentication negotiateProxyAuth = null;
if (myProxyAuthentication instanceof HTTPNTLMAuthentication) {
ntlmProxyAuth = (HTTPNTLMAuthentication) myProxyAuthentication;
if (ntlmProxyAuth.isInType3State()) {
debugLog.logFine(SVNLogType.NETWORK, "continuation of NTLM authentication");
continue;
}
} else if (myProxyAuthentication instanceof HTTPNegotiateAuthentication) {
negotiateProxyAuth = (HTTPNegotiateAuthentication) myProxyAuthentication;
if (negotiateProxyAuth.isStarted()) {
debugLog.logFine(SVNLogType.NETWORK, "continuation of Negotiate authentication");
continue;
}
}
if (ntlmProxyAuth != null && authAttempts == 1) {
if (!ntlmProxyAuth.allowPropmtForCredentials()) {
continue;
}
}
if (negotiateProxyAuth != null && !negotiateProxyAuth.needsLogin()) {
debugLog.logFine(SVNLogType.NETWORK, "Negotiate will use existing credentials");
continue;
}
if (!credentialsUsed) {
myProxyAuthentication.setCredentials(new SVNPasswordAuthentication(proxyManager.getProxyUserName(),
proxyManager.getProxyPassword(), false, myRepository.getLocation(), false));
debugLog.logFine(SVNLogType.NETWORK, "explicit credentials set");
credentialsUsed = true;
} else {
debugLog.logFine(SVNLogType.NETWORK, "no more credentials to try");
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "HTTP proxy authorization failed");
if (proxyManager != null) {
proxyManager.acknowledgeProxyContext(false, err);
}
SVNErrorManager.error(err, SVNLogType.NETWORK);
}
} else {
SVNURL proxyURL = SVNURL.parseURIEncoded("http://" + proxyManager.getProxyHost() + ":" + proxyManager.getProxyPort());
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "{0} request failed on ''{1}''", new Object[] {"CONNECT", proxyURL});
proxyManager.acknowledgeProxyContext(false, err);
SVNErrorManager.error(err, connectRequest.getErrorMessage(), SVNLogType.NETWORK);
}
}
} else if (proxyManager.getProxyUserName() != null && proxyManager.getProxyPassword() != null ){
myProxyAuthentication = new HTTPBasicAuthentication("UTF-8");
myProxyAuthentication.setCredentials(new SVNPasswordAuthentication(proxyManager.getProxyUserName(),
proxyManager.getProxyPassword(), false, myRepository.getLocation(), false));
debugLog.logFine(SVNLogType.NETWORK, "explicit credentials set");
}
} else {
myIsProxied = false;
myProxyAuthentication = null;
mySocket = myIsSecured ?
SVNSocketFactory.createSSLSocket(keyManager != null ? new KeyManager[] { keyManager } : new KeyManager[0], trustManager, host, port, connectTimeout, readTimeout, myRepository.getCanceller()) :
SVNSocketFactory.createPlainSocket(host, port, connectTimeout, readTimeout, myRepository.getCanceller());
}
}
}
public void readHeader(HTTPRequest request) throws IOException {
InputStream is = myRepository.getDebugLog().createLogStream(SVNLogType.NETWORK, getInputStream());
try {
// may throw EOF exception.
HTTPStatus status = HTTPParser.parseStatus(is, myCharset);
HTTPHeader header = HTTPHeader.parseHeader(is, myCharset);
request.setStatus(status);
request.setResponseHeader(header);
} catch (ParseException e) {
// in case of parse exception:
// try to read remaining and log it.
String line = HTTPParser.readLine(is, myCharset);
while(line != null && line.length() > 0) {
line = HTTPParser.readLine(is, myCharset);
}
throw new IOException(e.getMessage());
} finally {
myRepository.getDebugLog().flushStream(is);
}
}
public SVNErrorMessage readError(HTTPRequest request, String method, String path) {
DAVErrorHandler errorHandler = new DAVErrorHandler();
try {
readData(request, method, path, errorHandler);
} catch (IOException e) {
return null;
}
return errorHandler.getErrorMessage();
}
public void sendData(byte[] body) throws IOException {
try {
getOutputStream().write(body, 0, body.length);
getOutputStream().flush();
} finally {
myRepository.getDebugLog().flushStream(getOutputStream());
}
}
public void sendData(InputStream source, long length) throws IOException {
try {
byte[] buffer = getBuffer();
while(length > 0) {
int read = source.read(buffer, 0, (int) Math.min(buffer.length, length));
if (read > 0) {
length -= read;
getOutputStream().write(buffer, 0, read);
} else if (read < 0) {
break;
}
}
getOutputStream().flush();
} finally {
myRepository.getDebugLog().flushStream(getOutputStream());
}
}
public SVNAuthentication getLastValidCredentials() {
return myLastValidAuth;
}
public void clearAuthenticationCache() {
myCookies = null;
myLastValidAuth = null;
myTrustManager = null;
myKeyManager = null;
myChallengeCredentials = null;
myProxyAuthentication = null;
myRequestCount = 0;
}
public HTTPStatus request(String method, String path, HTTPHeader header, StringBuffer body, int ok1, int ok2, OutputStream dst, DefaultHandler handler) throws SVNException {
return request(method, path, header, body, ok1, ok2, dst, handler, null);
}
public HTTPStatus request(String method, String path, HTTPHeader header, StringBuffer body, int ok1, int ok2, OutputStream dst, DefaultHandler handler, SVNErrorMessage context) throws SVNException {
byte[] buffer = null;
if (body != null) {
try {
buffer = body.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
buffer = body.toString().getBytes();
}
}
return request(method, path, header, buffer != null ? new ByteArrayInputStream(buffer) : null, ok1, ok2, dst, handler, context);
}
public HTTPStatus request(String method, String path, HTTPHeader header, InputStream body, int ok1, int ok2, OutputStream dst, DefaultHandler handler) throws SVNException {
return request(method, path, header, body, ok1, ok2, dst, handler, null);
}
public HTTPStatus request(String method, String path, HTTPHeader header, InputStream body, int ok1, int ok2, OutputStream dst, DefaultHandler handler, SVNErrorMessage context) throws SVNException {
myLastStatus = null;
myRequestCount++;
if ("".equals(path) || path == null) {
path = "/";
}
ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager();
// 1. prompt for ssl client cert if needed, if cancelled - throw cancellation exception.
HTTPSSLKeyManager keyManager = myKeyManager == null && authManager != null ? createKeyManager() : myKeyManager;
TrustManager trustManager = myTrustManager == null && authManager != null ? authManager.getTrustManager(myRepository.getLocation()) : myTrustManager;
ISVNProxyManager proxyManager = authManager != null ? authManager.getProxyManager(myRepository.getLocation()) : null;
String sslRealm = composeRealm("");
SVNAuthentication httpAuth = myLastValidAuth;
boolean isAuthForced = authManager != null ? authManager.isAuthenticationForced() : false;
if (httpAuth == null && isAuthForced) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.WC, "SVNPasswordAuthentication requested.");
httpAuth = authManager.getFirstAuthentication(ISVNAuthenticationManager.PASSWORD, sslRealm, null);
logAuthFetched(httpAuth);
myChallengeCredentials = new HTTPBasicAuthentication((SVNPasswordAuthentication)httpAuth, myCharset);
}
String realm = null;
// 2. create request instance.
HTTPRequest request = new HTTPRequest(myCharset);
request.setConnection(this);
request.setKeepAlive(true);
request.setRequestBody(body);
request.setResponseHandler(handler);
request.setResponseStream(dst);
SVNErrorMessage err = null;
boolean ntlmAuthIsRequired = false;
boolean ntlmProxyAuthIsRequired = false;
boolean negoAuthIsRequired = false;
int authAttempts = 0;
while (true) {
if (myNextRequestTimeout < 0 || System.currentTimeMillis() >= myNextRequestTimeout) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, "Keep-Alive timeout detected");
close();
if (isClearCredentialsOnClose(myChallengeCredentials)) {
httpAuth = null;
}
}
int retryCount = 1;
try {
err = null;
String httpAuthResponse = null;
String proxyAuthResponse = null;
while(retryCount >= 0) {
connect(keyManager, trustManager, proxyManager);
request.reset();
request.setProxied(myIsProxied);
request.setSecured(myIsSecured);
if (myProxyAuthentication != null && (ntlmProxyAuthIsRequired || !"NTLM".equals(myProxyAuthentication.getAuthenticationScheme()))) {
if (proxyAuthResponse == null) {
request.initCredentials(myProxyAuthentication, method, path);
proxyAuthResponse = myProxyAuthentication.authenticate();
}
request.setProxyAuthentication(proxyAuthResponse);
}
if (myChallengeCredentials != null && (ntlmAuthIsRequired || negoAuthIsRequired || ((!"NTLM".equals(myChallengeCredentials.getAuthenticationScheme())) && !"Negotiate".equals(myChallengeCredentials.getAuthenticationScheme())) &&
httpAuth != null)) {
if (httpAuthResponse == null) {
request.initCredentials(myChallengeCredentials, method, path);
httpAuthResponse = myChallengeCredentials.authenticate();
}
request.setAuthentication(httpAuthResponse);
}
if (myCookies != null && !myCookies.isEmpty()) {
request.setCookies(myCookies);
}
try {
request.dispatch(method, path, header, ok1, ok2, context);
break;
} catch (EOFException pe) {
// retry, EOF always means closed connection.
if (retryCount > 0) {
close();
continue;
}
throw (IOException) new IOException(pe.getMessage()).initCause(pe);
} finally {
retryCount--;
}
}
if (request.getResponseHeader().hasHeader(HTTPHeader.SET_COOKIE)) {
myCookies = request.getResponseHeader().getHeaderValues(HTTPHeader.COOKIE);
}
myNextRequestTimeout = request.getNextRequestTimeout();
myLastStatus = request.getStatus();
} catch (SSLHandshakeException ssl) {
myRepository.getDebugLog().logFine(SVNLogType.NETWORK, ssl);
close();
if (ssl.getCause() instanceof SVNSSLUtil.CertificateNotTrustedException) {
SVNErrorManager.cancel(ssl.getCause().getMessage(), SVNLogType.NETWORK);
}
SVNErrorMessage sslErr = SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "SSL handshake failed: ''{0}''", new Object[] { ssl.getMessage() }, SVNErrorMessage.TYPE_ERROR, ssl);
if (keyManager != null) {
keyManager.acknowledgeAndClearAuthentication(sslErr);
}
err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, ssl);
continue;
} catch (IOException e) {
myRepository.getDebugLog().logFine(SVNLogType.NETWORK, e);
if (e instanceof SocketTimeoutException) {
err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED,
"timed out waiting for server", null, SVNErrorMessage.TYPE_ERROR, e);
} else if (e instanceof UnknownHostException) {
err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED,
"unknown host", null, SVNErrorMessage.TYPE_ERROR, e);
} else if (e instanceof ConnectException) {
err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED,
"connection refused by the server", null,
SVNErrorMessage.TYPE_ERROR, e);
} else if (e instanceof SVNCancellableOutputStream.IOCancelException) {
SVNErrorManager.cancel(e.getMessage(), SVNLogType.NETWORK);
} else if (e instanceof SSLException) {
err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e);
} else {
err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e);
}
} catch (SVNException e) {
myRepository.getDebugLog().logFine(SVNLogType.NETWORK, e);
// force connection close on SVNException
// (could be thrown by user's auth manager methods).
close();
throw e;
} finally {
finishResponse(request);
}
if (err != null) {
if (proxyManager != null) {
proxyManager.acknowledgeProxyContext(false, err);
}
close();
break;
}
if (proxyManager != null) {
proxyManager.acknowledgeProxyContext(true, err);
}
if (keyManager != null) {
myKeyManager = keyManager;
myTrustManager = trustManager;
keyManager.acknowledgeAndClearAuthentication(null);
}
if (myLastStatus.getCode() == HttpURLConnection.HTTP_FORBIDDEN) {
if (httpAuth != null && authManager != null) {
BasicAuthenticationManager.acknowledgeAuthentication(false, ISVNAuthenticationManager.PASSWORD, realm, request.getErrorMessage(), httpAuth, myRepository.getLocation(), authManager);
}
myLastValidAuth = null;
close();
err = request.getErrorMessage();
} else if (myIsProxied && myLastStatus.getCode() == HttpURLConnection.HTTP_PROXY_AUTH) {
Collection<String> proxyAuthHeaders = request.getResponseHeader().getHeaderValues(HTTPHeader.PROXY_AUTHENTICATE_HEADER);
Collection<String> authTypes = null;
if (authManager != null && authManager instanceof DefaultSVNAuthenticationManager) {
DefaultSVNAuthenticationManager defaultAuthManager = (DefaultSVNAuthenticationManager) authManager;
authTypes = defaultAuthManager.getAuthTypes(myRepository.getLocation());
}
try {
myProxyAuthentication = HTTPAuthentication.parseAuthParameters(proxyAuthHeaders, myProxyAuthentication, myCharset, authTypes, null, myRequestCount);
} catch (SVNException svne) {
myRepository.getDebugLog().logFine(SVNLogType.NETWORK, svne);
err = svne.getErrorMessage();
break;
}
if (myProxyAuthentication instanceof HTTPNTLMAuthentication) {
ntlmProxyAuthIsRequired = true;
HTTPNTLMAuthentication ntlmProxyAuth = (HTTPNTLMAuthentication) myProxyAuthentication;
if (ntlmProxyAuth.isInType3State()) {
continue;
}
}
err = SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "HTTP proxy authorization failed");
if (proxyManager != null) {
proxyManager.acknowledgeProxyContext(false, err);
}
close();
break;
} else if (myLastStatus.getCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
authAttempts++;//how many times did we try?
Collection<String> authHeaderValues = request.getResponseHeader().getHeaderValues(HTTPHeader.AUTHENTICATE_HEADER);
if (authHeaderValues == null || authHeaderValues.size() == 0) {
err = request.getErrorMessage();
myLastStatus.setError(SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, err.getMessageTemplate(), err.getRelatedObjects()));
if ("LOCK".equalsIgnoreCase(method)) {
myLastStatus.getError().setChildErrorMessage(SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE,
"Probably you are trying to lock file in repository that only allows anonymous access"));
}
SVNErrorManager.error(myLastStatus.getError(), SVNLogType.NETWORK);
return myLastStatus;
}
//we should work around a situation when a server
//does not support Basic authentication while we're
//forcing it, credentials should not be immediately
//thrown away
boolean skip = false;
isAuthForced = authManager != null ? authManager.isAuthenticationForced() : false;
if (isAuthForced) {
if (httpAuth != null && myChallengeCredentials != null && !HTTPAuthentication.isSchemeSupportedByServer(myChallengeCredentials.getAuthenticationScheme(), authHeaderValues)) {
skip = true;
}
}
Collection<String> authTypes = null;
if (authManager != null && authManager instanceof DefaultSVNAuthenticationManager) {
DefaultSVNAuthenticationManager defaultAuthManager = (DefaultSVNAuthenticationManager) authManager;
authTypes = defaultAuthManager.getAuthTypes(myRepository.getLocation());
}
try {
myChallengeCredentials = HTTPAuthentication.parseAuthParameters(authHeaderValues, myChallengeCredentials, myCharset, authTypes, authManager, myRequestCount);
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, "server auth method is " + myChallengeCredentials);
} catch (SVNException svne) {
err = svne.getErrorMessage();
break;
}
myChallengeCredentials.setChallengeParameter("method", method);
myChallengeCredentials.setChallengeParameter("uri", HTTPParser.getCanonicalPath(path, null).toString());
if (skip) {
close();
continue;
}
HTTPNTLMAuthentication ntlmAuth = null;
HTTPNegotiateAuthentication negoAuth = null;
if (myChallengeCredentials instanceof HTTPNTLMAuthentication) {
ntlmAuthIsRequired = true;
ntlmAuth = (HTTPNTLMAuthentication)myChallengeCredentials;
if (ntlmAuth.isInType3State()) {
continue;
}
} else if (myChallengeCredentials instanceof HTTPDigestAuthentication) {
// continue (retry once) if previous request was acceppted?
if (myLastValidAuth != null) {
myLastValidAuth = null;
continue;
}
} else if (myChallengeCredentials instanceof HTTPNegotiateAuthentication) {
negoAuthIsRequired = true;
negoAuth = (HTTPNegotiateAuthentication)myChallengeCredentials;
if (negoAuth.isStarted()) {
continue;
}
}
myLastValidAuth = null;
- if (ntlmAuth != null && ntlmAuth.isNative() && authAttempts == 1) {
+ if (ntlmAuth != null && authAttempts == 1) {
/*
* if this is the first time we get HTTP_UNAUTHORIZED, NTLM is the target auth scheme
* and JNA is available, we should try a native auth mechanism first without calling
* auth providers.
- */
- continue;
- }
+ */
+ if (!ntlmAuth.allowPropmtForCredentials()) {
+ continue;
+ }
+ }
if (negoAuth != null && !negoAuth.needsLogin()) {
continue;
}
if (authManager == null) {
err = request.getErrorMessage();
break;
}
realm = myChallengeCredentials.getChallengeParameter("realm");
realm = realm == null ? "" : " " + realm;
realm = composeRealm(realm);
if (httpAuth == null) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.WC, "SVNPasswordAuthentication requested (first).");
httpAuth = authManager.getFirstAuthentication(ISVNAuthenticationManager.PASSWORD, realm, myRepository.getLocation());
logAuthFetched(httpAuth);
} else if (authAttempts >= requestAttempts) {
BasicAuthenticationManager.acknowledgeAuthentication(false, ISVNAuthenticationManager.PASSWORD, realm, request.getErrorMessage(), httpAuth, myRepository.getLocation(), authManager);
SVNDebugLog.getDefaultLog().logFine(SVNLogType.WC, "SVNPasswordAuthentication requested (second).");
httpAuth = authManager.getNextAuthentication(ISVNAuthenticationManager.PASSWORD, realm, myRepository.getLocation());
logAuthFetched(httpAuth);
}
if (httpAuth == null) {
err = SVNErrorMessage.create(SVNErrorCode.CANCELLED, new SVNCancelException(SVNErrorMessage.create(SVNErrorCode.CANCELLED, "ISVNAuthentication provider did not provide credentials; HTTP authorization cancelled.")));
break;
}
if (httpAuth != null) {
myChallengeCredentials.setCredentials((SVNPasswordAuthentication) httpAuth);
}
continue;
} else if (myLastStatus.getCode() == HttpURLConnection.HTTP_MOVED_PERM || myLastStatus.getCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
String newLocation = request.getResponseHeader().getFirstHeaderValue(HTTPHeader.LOCATION_HEADER);
if (newLocation == null) {
err = request.getErrorMessage();
break;
}
int hostIndex = newLocation.indexOf("://");
if (hostIndex > 0) {
hostIndex += 3;
hostIndex = newLocation.indexOf("/", hostIndex);
}
if (hostIndex > 0 && hostIndex < newLocation.length()) {
String newPath = newLocation.substring(hostIndex);
if (newPath.endsWith("/") &&
!newPath.endsWith("//") && !path.endsWith("/") &&
newPath.substring(0, newPath.length() - 1).equals(path)) {
path += "//";
continue;
}
}
err = request.getErrorMessage();
close();
} else if (request.getErrorMessage() != null) {
err = request.getErrorMessage();
} else {
ntlmProxyAuthIsRequired = false;
ntlmAuthIsRequired = false;
negoAuthIsRequired = false;
}
if (err != null) {
break;
}
if (myIsProxied) {
if (proxyManager != null) {
proxyManager.acknowledgeProxyContext(true, null);
}
}
if (httpAuth != null && realm != null && authManager != null) {
BasicAuthenticationManager.acknowledgeAuthentication(true, ISVNAuthenticationManager.PASSWORD, realm, null, httpAuth, myRepository.getLocation(), authManager);
}
if (trustManager != null && authManager != null) {
authManager.acknowledgeTrustManager(trustManager);
}
if (httpAuth != null) {
myLastValidAuth = httpAuth;
}
if (authManager instanceof ISVNAuthenticationManagerExt) {
((ISVNAuthenticationManagerExt)authManager).acknowledgeConnectionSuccessful(myRepository.getLocation());
}
myLastStatus.setHeader(request.getResponseHeader());
return myLastStatus;
}
// force close on error that was not processed before.
// these are errors that has no relation to http status (processing error or cancellation).
close();
if (err != null && err.getErrorCode().getCategory() != SVNErrorCode.RA_DAV_CATEGORY &&
err.getErrorCode() != SVNErrorCode.UNSUPPORTED_FEATURE) {
SVNErrorManager.error(err, SVNLogType.NETWORK);
}
// err2 is another default context...
myRepository.getDebugLog().logFine(SVNLogType.NETWORK, new Exception(err.getMessage()));
SVNErrorMessage err2 = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "{0} request failed on ''{1}''", new Object[] {method, path}, err.getType(), err.getCause());
SVNErrorManager.error(err, err2, SVNLogType.NETWORK);
return null;
}
private void logAuthFetched(SVNAuthentication httpAuth) {
if (httpAuth != null) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.WC, "SVNPasswordAuthentication fetched.");
SVNDebugLog.getDefaultLog().logFine(SVNLogType.WC, "user name: " + httpAuth.getUserName());
SVNDebugLog.getDefaultLog().logFine(SVNLogType.WC, "password: " + ((SVNPasswordAuthentication) httpAuth).getPassword());
SVNDebugLog.getDefaultLog().logFine(SVNLogType.WC, new Exception());
} else {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.WC, "SVNPasswordAuthentication is not available.");
}
}
private String composeRealm(String realm) {
final StringBuffer buffer = new StringBuffer();
buffer.append("<");
buffer.append(myHost.getProtocol());
buffer.append("://");
if (myHost.getUserInfo() != null && !"".equals(myHost.getUserInfo().trim())) {
buffer.append(myHost.getUserInfo());
buffer.append("@");
}
buffer.append(myHost.getHost());
buffer.append(":");
buffer.append(myHost.getPort());
buffer.append(">");
if (realm != null) {
buffer.append(realm);
}
return buffer.toString();
}
private boolean isClearCredentialsOnClose(HTTPAuthentication auth) {
return !(auth instanceof HTTPBasicAuthentication || auth instanceof HTTPDigestAuthentication
|| auth instanceof HTTPNegotiateAuthentication);
}
private HTTPSSLKeyManager createKeyManager() {
if (!myIsSecured) {
return null;
}
SVNURL location = myRepository.getLocation();
ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager();
String sslRealm = "<" + location.getProtocol() + "://" + location.getHost() + ":" + location.getPort() + ">";
return new HTTPSSLKeyManager(authManager, sslRealm, location);
}
public SVNErrorMessage readData(HTTPRequest request, OutputStream dst) throws IOException {
InputStream stream = createInputStream(request.getResponseHeader(), getInputStream());
byte[] buffer = getBuffer();
boolean willCloseConnection = false;
try {
while (true) {
int count = stream.read(buffer);
if (count < 0) {
break;
}
if (dst != null) {
dst.write(buffer, 0, count);
}
}
} catch (IOException e) {
willCloseConnection = true;
if (e instanceof IOExceptionWrapper) {
IOExceptionWrapper wrappedException = (IOExceptionWrapper) e;
return wrappedException.getOriginalException().getErrorMessage();
}
if (e.getCause() instanceof SVNException) {
return ((SVNException) e.getCause()).getErrorMessage();
}
throw e;
} finally {
if (!willCloseConnection) {
SVNFileUtil.closeFile(stream);
}
myRepository.getDebugLog().flushStream(stream);
}
return null;
}
public SVNErrorMessage readData(HTTPRequest request, String method, String path, DefaultHandler handler) throws IOException {
InputStream is = null;
SpoolFile tmpFile = null;
SVNErrorMessage err = null;
try {
if (myIsSpoolResponse || myIsSpoolAll) {
OutputStream dst = null;
try {
tmpFile = new SpoolFile(mySpoolDirectory);
dst = tmpFile.openForWriting();
dst = new SVNCancellableOutputStream(dst, myRepository.getCanceller());
// this will exhaust http stream anyway.
err = readData(request, dst);
SVNFileUtil.closeFile(dst);
dst = null;
if (err != null) {
return err;
}
// this stream always have to be closed.
is = tmpFile.openForReading();
} finally {
SVNFileUtil.closeFile(dst);
}
} else {
is = createInputStream(request.getResponseHeader(), getInputStream());
}
// this will not close is stream.
err = readData(is, method, path, handler);
} catch (IOException e) {
throw e;
} finally {
if (myIsSpoolResponse || myIsSpoolAll) {
// always close spooled stream.
SVNFileUtil.closeFile(is);
} else if (err == null && !hasToCloseConnection(request.getResponseHeader())) {
// exhaust stream if connection is not about to be closed.
SVNFileUtil.closeFile(is);
}
if (tmpFile != null) {
try {
tmpFile.delete();
} catch (SVNException e) {
throw new IOException(e.getMessage());
}
}
myIsSpoolResponse = false;
}
return err;
}
private SVNErrorMessage readData(InputStream is, String method, String path, DefaultHandler handler) throws FactoryConfigurationError, UnsupportedEncodingException, IOException {
try {
if (mySAXParser == null) {
mySAXParser = getSAXParserFactory().newSAXParser();
}
XMLReader reader = new XMLReader(is);
while (!reader.isClosed()) {
org.xml.sax.XMLReader xmlReader = mySAXParser.getXMLReader();
xmlReader.setContentHandler(handler);
xmlReader.setDTDHandler(handler);
xmlReader.setErrorHandler(handler);
xmlReader.setEntityResolver(NO_ENTITY_RESOLVER);
xmlReader.parse(new InputSource(reader));
}
} catch (SAXException e) {
mySAXParser = null;
if (e instanceof SAXParseException) {
if (handler instanceof DAVErrorHandler) {
// failed to read svn-specific error, return null.
return null;
}
} else if (e.getException() instanceof SVNException) {
return ((SVNException) e.getException()).getErrorMessage();
} else if (e.getCause() instanceof SVNException) {
return ((SVNException) e.getCause()).getErrorMessage();
}
return SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "Processing {0} request response failed: {1} ({2}) ", new Object[] {method, e.getMessage(), path});
} catch (ParserConfigurationException e) {
mySAXParser = null;
return SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "XML parser configuration error while processing {0} request response: {1} ({2}) ", new Object[] {method, e.getMessage(), path});
} catch (EOFException e) {
// skip it.
} finally {
if (mySAXParser != null) {
// to avoid memory leaks when connection is cached.
org.xml.sax.XMLReader xmlReader = null;
try {
xmlReader = mySAXParser.getXMLReader();
} catch (SAXException e) {
}
if (xmlReader != null) {
xmlReader.setContentHandler(DEFAULT_SAX_HANDLER);
xmlReader.setDTDHandler(DEFAULT_SAX_HANDLER);
xmlReader.setErrorHandler(DEFAULT_SAX_HANDLER);
xmlReader.setEntityResolver(NO_ENTITY_RESOLVER);
}
}
myRepository.getDebugLog().flushStream(is);
}
return null;
}
public void skipData(HTTPRequest request) throws IOException {
if (hasToCloseConnection(request.getResponseHeader())) {
return;
}
InputStream is = createInputStream(request.getResponseHeader(), getInputStream());
while(is.skip(2048) > 0);
}
public void close() {
if (isClearCredentialsOnClose(myChallengeCredentials)) {
clearAuthenticationCache();
}
if (mySocket != null) {
if (myInputStream != null) {
try {
myInputStream.close();
} catch (IOException e) {}
}
if (myOutputStream != null) {
try {
myOutputStream.flush();
} catch (IOException e) {}
}
if (myOutputStream != null) {
try {
myOutputStream.close();
} catch (IOException e) {}
}
try {
mySocket.close();
} catch (IOException e) {}
mySocket = null;
myOutputStream = null;
myInputStream = null;
}
}
private byte[] getBuffer() {
if (myBuffer == null) {
myBuffer = new byte[32*1024];
}
return myBuffer;
}
private InputStream getInputStream() throws IOException {
if (myInputStream == null) {
if (mySocket == null) {
return null;
}
// myInputStream = new CancellableSocketInputStream(new BufferedInputStream(mySocket.getInputStream(), 2048), myRepository.getCanceller());
myInputStream = new BufferedInputStream(mySocket.getInputStream(), 2048);
}
return myInputStream;
}
private OutputStream getOutputStream() throws IOException {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.DEFAULT, "socket output stream requested...");
if (myOutputStream == null) {
if (mySocket == null) {
return null;
}
myOutputStream = new BufferedOutputStream(mySocket.getOutputStream(), 2048);
myOutputStream = myRepository.getDebugLog().createLogStream(SVNLogType.NETWORK, myOutputStream);
}
return myOutputStream;
}
private void finishResponse(HTTPRequest request) {
if (myOutputStream != null) {
try {
myOutputStream.flush();
} catch (IOException ex) {
}
}
HTTPHeader header = request != null ? request.getResponseHeader() : null;
if (hasToCloseConnection(header)) {
close();
}
}
private static boolean hasToCloseConnection(HTTPHeader header) {
if (header == null) {
return true;
}
String connectionHeader = header.getFirstHeaderValue(HTTPHeader.CONNECTION_HEADER);
String proxyHeader = header.getFirstHeaderValue(HTTPHeader.PROXY_CONNECTION_HEADER);
if (connectionHeader != null && connectionHeader.toLowerCase().indexOf("close") >= 0) {
return true;
} else if (proxyHeader != null && proxyHeader.toLowerCase().indexOf("close") >= 0) {
return true;
}
return false;
}
private InputStream createInputStream(HTTPHeader readHeader, InputStream is) throws IOException {
if ("chunked".equalsIgnoreCase(readHeader.getFirstHeaderValue(HTTPHeader.TRANSFER_ENCODING_HEADER))) {
is = new ChunkedInputStream(is, myCharset);
} else if (readHeader.getFirstHeaderValue(HTTPHeader.CONTENT_LENGTH_HEADER) != null) {
String lengthStr = readHeader.getFirstHeaderValue(HTTPHeader.CONTENT_LENGTH_HEADER);
long length = 0;
try {
length = Long.parseLong(lengthStr);
} catch (NumberFormatException nfe) {
length = 0;
}
is = new FixedSizeInputStream(is, length);
} else if (!hasToCloseConnection(readHeader)) {
// no content length and no valid transfer-encoding!
// consider as empty response.
// but only when there is no "Connection: close" or "Proxy-Connection: close" header,
// in that case just return "is".
// skipData will not read that as it should also analyze "close" instruction.
// return empty stream.
// and force connection close? (not to read garbage on the next request).
is = new FixedSizeInputStream(is, 0);
// this will force connection to close.
readHeader.setHeaderValue(HTTPHeader.CONNECTION_HEADER, "close");
}
if ("gzip".equals(readHeader.getFirstHeaderValue(HTTPHeader.CONTENT_ENCODING_HEADER))) {
is = new GZIPInputStream(is);
}
return myRepository.getDebugLog().createLogStream(SVNLogType.NETWORK, is);
}
private static synchronized SAXParserFactory getSAXParserFactory() throws FactoryConfigurationError {
if (ourSAXParserFactory == null) {
ourSAXParserFactory = createSAXParserFactory();
Map<String, Object> supportedFeatures = new HashMap<String, Object>();
try {
ourSAXParserFactory.setFeature("http://xml.org/sax/features/namespaces", true);
supportedFeatures.put("http://xml.org/sax/features/namespaces", Boolean.TRUE);
} catch (SAXNotRecognizedException e) {
} catch (SAXNotSupportedException e) {
} catch (ParserConfigurationException e) {
}
try {
ourSAXParserFactory.setFeature("http://xml.org/sax/features/validation", false);
supportedFeatures.put("http://xml.org/sax/features/validation", Boolean.FALSE);
} catch (SAXNotRecognizedException e) {
} catch (SAXNotSupportedException e) {
} catch (ParserConfigurationException e) {
}
try {
ourSAXParserFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
supportedFeatures.put("http://apache.org/xml/features/nonvalidating/load-external-dtd", Boolean.FALSE);
} catch (SAXNotRecognizedException e) {
} catch (SAXNotSupportedException e) {
} catch (ParserConfigurationException e) {
}
if (supportedFeatures.size() < 3) {
ourSAXParserFactory = createSAXParserFactory();
for (Iterator<String> names = supportedFeatures.keySet().iterator(); names.hasNext();) {
String name = names.next();
try {
ourSAXParserFactory.setFeature(name, supportedFeatures.get(name) == Boolean.TRUE);
} catch (SAXNotRecognizedException e) {
} catch (SAXNotSupportedException e) {
} catch (ParserConfigurationException e) {
}
}
}
ourSAXParserFactory.setNamespaceAware(true);
ourSAXParserFactory.setValidating(false);
}
return ourSAXParserFactory;
}
public static SAXParserFactory createSAXParserFactory() {
String legacy = System.getProperty("svnkit.sax.useDefault");
if (legacy == null || !Boolean.valueOf(legacy).booleanValue()) {
return SAXParserFactory.newInstance();
}
// instantiate JVM parser.
String[] parsers = {"com.sun.org.apache.xerces.internal.jaxp.SAXParserFactoryImpl", // 1.5, 1.6
"org.apache.crimson.jaxp.SAXParserFactoryImpl", // 1.4
};
for (int i = 0; i < parsers.length; i++) {
String className = parsers[i];
ClassLoader loader = HTTPConnection.class.getClassLoader();
try {
Class<?> clazz = null;
if (loader != null) {
clazz = loader.loadClass(className);
} else {
clazz = Class.forName(className);
}
if (clazz != null) {
Object factory = clazz.newInstance();
if (factory instanceof SAXParserFactory) {
return (SAXParserFactory) factory;
}
}
} catch (ClassNotFoundException e) {
} catch (InstantiationException e) {
} catch (IllegalAccessException e) {
}
}
return SAXParserFactory.newInstance();
}
public void setSpoolResponse(boolean spoolResponse) {
myIsSpoolResponse = spoolResponse;
}
}
| false | true | public HTTPStatus request(String method, String path, HTTPHeader header, InputStream body, int ok1, int ok2, OutputStream dst, DefaultHandler handler, SVNErrorMessage context) throws SVNException {
myLastStatus = null;
myRequestCount++;
if ("".equals(path) || path == null) {
path = "/";
}
ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager();
// 1. prompt for ssl client cert if needed, if cancelled - throw cancellation exception.
HTTPSSLKeyManager keyManager = myKeyManager == null && authManager != null ? createKeyManager() : myKeyManager;
TrustManager trustManager = myTrustManager == null && authManager != null ? authManager.getTrustManager(myRepository.getLocation()) : myTrustManager;
ISVNProxyManager proxyManager = authManager != null ? authManager.getProxyManager(myRepository.getLocation()) : null;
String sslRealm = composeRealm("");
SVNAuthentication httpAuth = myLastValidAuth;
boolean isAuthForced = authManager != null ? authManager.isAuthenticationForced() : false;
if (httpAuth == null && isAuthForced) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.WC, "SVNPasswordAuthentication requested.");
httpAuth = authManager.getFirstAuthentication(ISVNAuthenticationManager.PASSWORD, sslRealm, null);
logAuthFetched(httpAuth);
myChallengeCredentials = new HTTPBasicAuthentication((SVNPasswordAuthentication)httpAuth, myCharset);
}
String realm = null;
// 2. create request instance.
HTTPRequest request = new HTTPRequest(myCharset);
request.setConnection(this);
request.setKeepAlive(true);
request.setRequestBody(body);
request.setResponseHandler(handler);
request.setResponseStream(dst);
SVNErrorMessage err = null;
boolean ntlmAuthIsRequired = false;
boolean ntlmProxyAuthIsRequired = false;
boolean negoAuthIsRequired = false;
int authAttempts = 0;
while (true) {
if (myNextRequestTimeout < 0 || System.currentTimeMillis() >= myNextRequestTimeout) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, "Keep-Alive timeout detected");
close();
if (isClearCredentialsOnClose(myChallengeCredentials)) {
httpAuth = null;
}
}
int retryCount = 1;
try {
err = null;
String httpAuthResponse = null;
String proxyAuthResponse = null;
while(retryCount >= 0) {
connect(keyManager, trustManager, proxyManager);
request.reset();
request.setProxied(myIsProxied);
request.setSecured(myIsSecured);
if (myProxyAuthentication != null && (ntlmProxyAuthIsRequired || !"NTLM".equals(myProxyAuthentication.getAuthenticationScheme()))) {
if (proxyAuthResponse == null) {
request.initCredentials(myProxyAuthentication, method, path);
proxyAuthResponse = myProxyAuthentication.authenticate();
}
request.setProxyAuthentication(proxyAuthResponse);
}
if (myChallengeCredentials != null && (ntlmAuthIsRequired || negoAuthIsRequired || ((!"NTLM".equals(myChallengeCredentials.getAuthenticationScheme())) && !"Negotiate".equals(myChallengeCredentials.getAuthenticationScheme())) &&
httpAuth != null)) {
if (httpAuthResponse == null) {
request.initCredentials(myChallengeCredentials, method, path);
httpAuthResponse = myChallengeCredentials.authenticate();
}
request.setAuthentication(httpAuthResponse);
}
if (myCookies != null && !myCookies.isEmpty()) {
request.setCookies(myCookies);
}
try {
request.dispatch(method, path, header, ok1, ok2, context);
break;
} catch (EOFException pe) {
// retry, EOF always means closed connection.
if (retryCount > 0) {
close();
continue;
}
throw (IOException) new IOException(pe.getMessage()).initCause(pe);
} finally {
retryCount--;
}
}
if (request.getResponseHeader().hasHeader(HTTPHeader.SET_COOKIE)) {
myCookies = request.getResponseHeader().getHeaderValues(HTTPHeader.COOKIE);
}
myNextRequestTimeout = request.getNextRequestTimeout();
myLastStatus = request.getStatus();
} catch (SSLHandshakeException ssl) {
myRepository.getDebugLog().logFine(SVNLogType.NETWORK, ssl);
close();
if (ssl.getCause() instanceof SVNSSLUtil.CertificateNotTrustedException) {
SVNErrorManager.cancel(ssl.getCause().getMessage(), SVNLogType.NETWORK);
}
SVNErrorMessage sslErr = SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "SSL handshake failed: ''{0}''", new Object[] { ssl.getMessage() }, SVNErrorMessage.TYPE_ERROR, ssl);
if (keyManager != null) {
keyManager.acknowledgeAndClearAuthentication(sslErr);
}
err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, ssl);
continue;
} catch (IOException e) {
myRepository.getDebugLog().logFine(SVNLogType.NETWORK, e);
if (e instanceof SocketTimeoutException) {
err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED,
"timed out waiting for server", null, SVNErrorMessage.TYPE_ERROR, e);
} else if (e instanceof UnknownHostException) {
err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED,
"unknown host", null, SVNErrorMessage.TYPE_ERROR, e);
} else if (e instanceof ConnectException) {
err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED,
"connection refused by the server", null,
SVNErrorMessage.TYPE_ERROR, e);
} else if (e instanceof SVNCancellableOutputStream.IOCancelException) {
SVNErrorManager.cancel(e.getMessage(), SVNLogType.NETWORK);
} else if (e instanceof SSLException) {
err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e);
} else {
err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e);
}
} catch (SVNException e) {
myRepository.getDebugLog().logFine(SVNLogType.NETWORK, e);
// force connection close on SVNException
// (could be thrown by user's auth manager methods).
close();
throw e;
} finally {
finishResponse(request);
}
if (err != null) {
if (proxyManager != null) {
proxyManager.acknowledgeProxyContext(false, err);
}
close();
break;
}
if (proxyManager != null) {
proxyManager.acknowledgeProxyContext(true, err);
}
if (keyManager != null) {
myKeyManager = keyManager;
myTrustManager = trustManager;
keyManager.acknowledgeAndClearAuthentication(null);
}
if (myLastStatus.getCode() == HttpURLConnection.HTTP_FORBIDDEN) {
if (httpAuth != null && authManager != null) {
BasicAuthenticationManager.acknowledgeAuthentication(false, ISVNAuthenticationManager.PASSWORD, realm, request.getErrorMessage(), httpAuth, myRepository.getLocation(), authManager);
}
myLastValidAuth = null;
close();
err = request.getErrorMessage();
} else if (myIsProxied && myLastStatus.getCode() == HttpURLConnection.HTTP_PROXY_AUTH) {
Collection<String> proxyAuthHeaders = request.getResponseHeader().getHeaderValues(HTTPHeader.PROXY_AUTHENTICATE_HEADER);
Collection<String> authTypes = null;
if (authManager != null && authManager instanceof DefaultSVNAuthenticationManager) {
DefaultSVNAuthenticationManager defaultAuthManager = (DefaultSVNAuthenticationManager) authManager;
authTypes = defaultAuthManager.getAuthTypes(myRepository.getLocation());
}
try {
myProxyAuthentication = HTTPAuthentication.parseAuthParameters(proxyAuthHeaders, myProxyAuthentication, myCharset, authTypes, null, myRequestCount);
} catch (SVNException svne) {
myRepository.getDebugLog().logFine(SVNLogType.NETWORK, svne);
err = svne.getErrorMessage();
break;
}
if (myProxyAuthentication instanceof HTTPNTLMAuthentication) {
ntlmProxyAuthIsRequired = true;
HTTPNTLMAuthentication ntlmProxyAuth = (HTTPNTLMAuthentication) myProxyAuthentication;
if (ntlmProxyAuth.isInType3State()) {
continue;
}
}
err = SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "HTTP proxy authorization failed");
if (proxyManager != null) {
proxyManager.acknowledgeProxyContext(false, err);
}
close();
break;
} else if (myLastStatus.getCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
authAttempts++;//how many times did we try?
Collection<String> authHeaderValues = request.getResponseHeader().getHeaderValues(HTTPHeader.AUTHENTICATE_HEADER);
if (authHeaderValues == null || authHeaderValues.size() == 0) {
err = request.getErrorMessage();
myLastStatus.setError(SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, err.getMessageTemplate(), err.getRelatedObjects()));
if ("LOCK".equalsIgnoreCase(method)) {
myLastStatus.getError().setChildErrorMessage(SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE,
"Probably you are trying to lock file in repository that only allows anonymous access"));
}
SVNErrorManager.error(myLastStatus.getError(), SVNLogType.NETWORK);
return myLastStatus;
}
//we should work around a situation when a server
//does not support Basic authentication while we're
//forcing it, credentials should not be immediately
//thrown away
boolean skip = false;
isAuthForced = authManager != null ? authManager.isAuthenticationForced() : false;
if (isAuthForced) {
if (httpAuth != null && myChallengeCredentials != null && !HTTPAuthentication.isSchemeSupportedByServer(myChallengeCredentials.getAuthenticationScheme(), authHeaderValues)) {
skip = true;
}
}
Collection<String> authTypes = null;
if (authManager != null && authManager instanceof DefaultSVNAuthenticationManager) {
DefaultSVNAuthenticationManager defaultAuthManager = (DefaultSVNAuthenticationManager) authManager;
authTypes = defaultAuthManager.getAuthTypes(myRepository.getLocation());
}
try {
myChallengeCredentials = HTTPAuthentication.parseAuthParameters(authHeaderValues, myChallengeCredentials, myCharset, authTypes, authManager, myRequestCount);
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, "server auth method is " + myChallengeCredentials);
} catch (SVNException svne) {
err = svne.getErrorMessage();
break;
}
myChallengeCredentials.setChallengeParameter("method", method);
myChallengeCredentials.setChallengeParameter("uri", HTTPParser.getCanonicalPath(path, null).toString());
if (skip) {
close();
continue;
}
HTTPNTLMAuthentication ntlmAuth = null;
HTTPNegotiateAuthentication negoAuth = null;
if (myChallengeCredentials instanceof HTTPNTLMAuthentication) {
ntlmAuthIsRequired = true;
ntlmAuth = (HTTPNTLMAuthentication)myChallengeCredentials;
if (ntlmAuth.isInType3State()) {
continue;
}
} else if (myChallengeCredentials instanceof HTTPDigestAuthentication) {
// continue (retry once) if previous request was acceppted?
if (myLastValidAuth != null) {
myLastValidAuth = null;
continue;
}
} else if (myChallengeCredentials instanceof HTTPNegotiateAuthentication) {
negoAuthIsRequired = true;
negoAuth = (HTTPNegotiateAuthentication)myChallengeCredentials;
if (negoAuth.isStarted()) {
continue;
}
}
myLastValidAuth = null;
if (ntlmAuth != null && ntlmAuth.isNative() && authAttempts == 1) {
/*
* if this is the first time we get HTTP_UNAUTHORIZED, NTLM is the target auth scheme
* and JNA is available, we should try a native auth mechanism first without calling
* auth providers.
*/
continue;
}
if (negoAuth != null && !negoAuth.needsLogin()) {
continue;
}
if (authManager == null) {
err = request.getErrorMessage();
break;
}
realm = myChallengeCredentials.getChallengeParameter("realm");
realm = realm == null ? "" : " " + realm;
realm = composeRealm(realm);
if (httpAuth == null) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.WC, "SVNPasswordAuthentication requested (first).");
httpAuth = authManager.getFirstAuthentication(ISVNAuthenticationManager.PASSWORD, realm, myRepository.getLocation());
logAuthFetched(httpAuth);
} else if (authAttempts >= requestAttempts) {
BasicAuthenticationManager.acknowledgeAuthentication(false, ISVNAuthenticationManager.PASSWORD, realm, request.getErrorMessage(), httpAuth, myRepository.getLocation(), authManager);
SVNDebugLog.getDefaultLog().logFine(SVNLogType.WC, "SVNPasswordAuthentication requested (second).");
httpAuth = authManager.getNextAuthentication(ISVNAuthenticationManager.PASSWORD, realm, myRepository.getLocation());
logAuthFetched(httpAuth);
}
if (httpAuth == null) {
err = SVNErrorMessage.create(SVNErrorCode.CANCELLED, new SVNCancelException(SVNErrorMessage.create(SVNErrorCode.CANCELLED, "ISVNAuthentication provider did not provide credentials; HTTP authorization cancelled.")));
break;
}
if (httpAuth != null) {
myChallengeCredentials.setCredentials((SVNPasswordAuthentication) httpAuth);
}
continue;
} else if (myLastStatus.getCode() == HttpURLConnection.HTTP_MOVED_PERM || myLastStatus.getCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
String newLocation = request.getResponseHeader().getFirstHeaderValue(HTTPHeader.LOCATION_HEADER);
if (newLocation == null) {
err = request.getErrorMessage();
break;
}
int hostIndex = newLocation.indexOf("://");
if (hostIndex > 0) {
hostIndex += 3;
hostIndex = newLocation.indexOf("/", hostIndex);
}
if (hostIndex > 0 && hostIndex < newLocation.length()) {
String newPath = newLocation.substring(hostIndex);
if (newPath.endsWith("/") &&
!newPath.endsWith("//") && !path.endsWith("/") &&
newPath.substring(0, newPath.length() - 1).equals(path)) {
path += "//";
continue;
}
}
err = request.getErrorMessage();
close();
} else if (request.getErrorMessage() != null) {
err = request.getErrorMessage();
} else {
ntlmProxyAuthIsRequired = false;
ntlmAuthIsRequired = false;
negoAuthIsRequired = false;
}
if (err != null) {
break;
}
if (myIsProxied) {
if (proxyManager != null) {
proxyManager.acknowledgeProxyContext(true, null);
}
}
if (httpAuth != null && realm != null && authManager != null) {
BasicAuthenticationManager.acknowledgeAuthentication(true, ISVNAuthenticationManager.PASSWORD, realm, null, httpAuth, myRepository.getLocation(), authManager);
}
if (trustManager != null && authManager != null) {
authManager.acknowledgeTrustManager(trustManager);
}
if (httpAuth != null) {
myLastValidAuth = httpAuth;
}
if (authManager instanceof ISVNAuthenticationManagerExt) {
((ISVNAuthenticationManagerExt)authManager).acknowledgeConnectionSuccessful(myRepository.getLocation());
}
myLastStatus.setHeader(request.getResponseHeader());
return myLastStatus;
}
// force close on error that was not processed before.
// these are errors that has no relation to http status (processing error or cancellation).
close();
if (err != null && err.getErrorCode().getCategory() != SVNErrorCode.RA_DAV_CATEGORY &&
err.getErrorCode() != SVNErrorCode.UNSUPPORTED_FEATURE) {
SVNErrorManager.error(err, SVNLogType.NETWORK);
}
// err2 is another default context...
myRepository.getDebugLog().logFine(SVNLogType.NETWORK, new Exception(err.getMessage()));
SVNErrorMessage err2 = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "{0} request failed on ''{1}''", new Object[] {method, path}, err.getType(), err.getCause());
SVNErrorManager.error(err, err2, SVNLogType.NETWORK);
return null;
}
| public HTTPStatus request(String method, String path, HTTPHeader header, InputStream body, int ok1, int ok2, OutputStream dst, DefaultHandler handler, SVNErrorMessage context) throws SVNException {
myLastStatus = null;
myRequestCount++;
if ("".equals(path) || path == null) {
path = "/";
}
ISVNAuthenticationManager authManager = myRepository.getAuthenticationManager();
// 1. prompt for ssl client cert if needed, if cancelled - throw cancellation exception.
HTTPSSLKeyManager keyManager = myKeyManager == null && authManager != null ? createKeyManager() : myKeyManager;
TrustManager trustManager = myTrustManager == null && authManager != null ? authManager.getTrustManager(myRepository.getLocation()) : myTrustManager;
ISVNProxyManager proxyManager = authManager != null ? authManager.getProxyManager(myRepository.getLocation()) : null;
String sslRealm = composeRealm("");
SVNAuthentication httpAuth = myLastValidAuth;
boolean isAuthForced = authManager != null ? authManager.isAuthenticationForced() : false;
if (httpAuth == null && isAuthForced) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.WC, "SVNPasswordAuthentication requested.");
httpAuth = authManager.getFirstAuthentication(ISVNAuthenticationManager.PASSWORD, sslRealm, null);
logAuthFetched(httpAuth);
myChallengeCredentials = new HTTPBasicAuthentication((SVNPasswordAuthentication)httpAuth, myCharset);
}
String realm = null;
// 2. create request instance.
HTTPRequest request = new HTTPRequest(myCharset);
request.setConnection(this);
request.setKeepAlive(true);
request.setRequestBody(body);
request.setResponseHandler(handler);
request.setResponseStream(dst);
SVNErrorMessage err = null;
boolean ntlmAuthIsRequired = false;
boolean ntlmProxyAuthIsRequired = false;
boolean negoAuthIsRequired = false;
int authAttempts = 0;
while (true) {
if (myNextRequestTimeout < 0 || System.currentTimeMillis() >= myNextRequestTimeout) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, "Keep-Alive timeout detected");
close();
if (isClearCredentialsOnClose(myChallengeCredentials)) {
httpAuth = null;
}
}
int retryCount = 1;
try {
err = null;
String httpAuthResponse = null;
String proxyAuthResponse = null;
while(retryCount >= 0) {
connect(keyManager, trustManager, proxyManager);
request.reset();
request.setProxied(myIsProxied);
request.setSecured(myIsSecured);
if (myProxyAuthentication != null && (ntlmProxyAuthIsRequired || !"NTLM".equals(myProxyAuthentication.getAuthenticationScheme()))) {
if (proxyAuthResponse == null) {
request.initCredentials(myProxyAuthentication, method, path);
proxyAuthResponse = myProxyAuthentication.authenticate();
}
request.setProxyAuthentication(proxyAuthResponse);
}
if (myChallengeCredentials != null && (ntlmAuthIsRequired || negoAuthIsRequired || ((!"NTLM".equals(myChallengeCredentials.getAuthenticationScheme())) && !"Negotiate".equals(myChallengeCredentials.getAuthenticationScheme())) &&
httpAuth != null)) {
if (httpAuthResponse == null) {
request.initCredentials(myChallengeCredentials, method, path);
httpAuthResponse = myChallengeCredentials.authenticate();
}
request.setAuthentication(httpAuthResponse);
}
if (myCookies != null && !myCookies.isEmpty()) {
request.setCookies(myCookies);
}
try {
request.dispatch(method, path, header, ok1, ok2, context);
break;
} catch (EOFException pe) {
// retry, EOF always means closed connection.
if (retryCount > 0) {
close();
continue;
}
throw (IOException) new IOException(pe.getMessage()).initCause(pe);
} finally {
retryCount--;
}
}
if (request.getResponseHeader().hasHeader(HTTPHeader.SET_COOKIE)) {
myCookies = request.getResponseHeader().getHeaderValues(HTTPHeader.COOKIE);
}
myNextRequestTimeout = request.getNextRequestTimeout();
myLastStatus = request.getStatus();
} catch (SSLHandshakeException ssl) {
myRepository.getDebugLog().logFine(SVNLogType.NETWORK, ssl);
close();
if (ssl.getCause() instanceof SVNSSLUtil.CertificateNotTrustedException) {
SVNErrorManager.cancel(ssl.getCause().getMessage(), SVNLogType.NETWORK);
}
SVNErrorMessage sslErr = SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "SSL handshake failed: ''{0}''", new Object[] { ssl.getMessage() }, SVNErrorMessage.TYPE_ERROR, ssl);
if (keyManager != null) {
keyManager.acknowledgeAndClearAuthentication(sslErr);
}
err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, ssl);
continue;
} catch (IOException e) {
myRepository.getDebugLog().logFine(SVNLogType.NETWORK, e);
if (e instanceof SocketTimeoutException) {
err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED,
"timed out waiting for server", null, SVNErrorMessage.TYPE_ERROR, e);
} else if (e instanceof UnknownHostException) {
err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED,
"unknown host", null, SVNErrorMessage.TYPE_ERROR, e);
} else if (e instanceof ConnectException) {
err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED,
"connection refused by the server", null,
SVNErrorMessage.TYPE_ERROR, e);
} else if (e instanceof SVNCancellableOutputStream.IOCancelException) {
SVNErrorManager.cancel(e.getMessage(), SVNLogType.NETWORK);
} else if (e instanceof SSLException) {
err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e);
} else {
err = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, e);
}
} catch (SVNException e) {
myRepository.getDebugLog().logFine(SVNLogType.NETWORK, e);
// force connection close on SVNException
// (could be thrown by user's auth manager methods).
close();
throw e;
} finally {
finishResponse(request);
}
if (err != null) {
if (proxyManager != null) {
proxyManager.acknowledgeProxyContext(false, err);
}
close();
break;
}
if (proxyManager != null) {
proxyManager.acknowledgeProxyContext(true, err);
}
if (keyManager != null) {
myKeyManager = keyManager;
myTrustManager = trustManager;
keyManager.acknowledgeAndClearAuthentication(null);
}
if (myLastStatus.getCode() == HttpURLConnection.HTTP_FORBIDDEN) {
if (httpAuth != null && authManager != null) {
BasicAuthenticationManager.acknowledgeAuthentication(false, ISVNAuthenticationManager.PASSWORD, realm, request.getErrorMessage(), httpAuth, myRepository.getLocation(), authManager);
}
myLastValidAuth = null;
close();
err = request.getErrorMessage();
} else if (myIsProxied && myLastStatus.getCode() == HttpURLConnection.HTTP_PROXY_AUTH) {
Collection<String> proxyAuthHeaders = request.getResponseHeader().getHeaderValues(HTTPHeader.PROXY_AUTHENTICATE_HEADER);
Collection<String> authTypes = null;
if (authManager != null && authManager instanceof DefaultSVNAuthenticationManager) {
DefaultSVNAuthenticationManager defaultAuthManager = (DefaultSVNAuthenticationManager) authManager;
authTypes = defaultAuthManager.getAuthTypes(myRepository.getLocation());
}
try {
myProxyAuthentication = HTTPAuthentication.parseAuthParameters(proxyAuthHeaders, myProxyAuthentication, myCharset, authTypes, null, myRequestCount);
} catch (SVNException svne) {
myRepository.getDebugLog().logFine(SVNLogType.NETWORK, svne);
err = svne.getErrorMessage();
break;
}
if (myProxyAuthentication instanceof HTTPNTLMAuthentication) {
ntlmProxyAuthIsRequired = true;
HTTPNTLMAuthentication ntlmProxyAuth = (HTTPNTLMAuthentication) myProxyAuthentication;
if (ntlmProxyAuth.isInType3State()) {
continue;
}
}
err = SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, "HTTP proxy authorization failed");
if (proxyManager != null) {
proxyManager.acknowledgeProxyContext(false, err);
}
close();
break;
} else if (myLastStatus.getCode() == HttpURLConnection.HTTP_UNAUTHORIZED) {
authAttempts++;//how many times did we try?
Collection<String> authHeaderValues = request.getResponseHeader().getHeaderValues(HTTPHeader.AUTHENTICATE_HEADER);
if (authHeaderValues == null || authHeaderValues.size() == 0) {
err = request.getErrorMessage();
myLastStatus.setError(SVNErrorMessage.create(SVNErrorCode.RA_NOT_AUTHORIZED, err.getMessageTemplate(), err.getRelatedObjects()));
if ("LOCK".equalsIgnoreCase(method)) {
myLastStatus.getError().setChildErrorMessage(SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE,
"Probably you are trying to lock file in repository that only allows anonymous access"));
}
SVNErrorManager.error(myLastStatus.getError(), SVNLogType.NETWORK);
return myLastStatus;
}
//we should work around a situation when a server
//does not support Basic authentication while we're
//forcing it, credentials should not be immediately
//thrown away
boolean skip = false;
isAuthForced = authManager != null ? authManager.isAuthenticationForced() : false;
if (isAuthForced) {
if (httpAuth != null && myChallengeCredentials != null && !HTTPAuthentication.isSchemeSupportedByServer(myChallengeCredentials.getAuthenticationScheme(), authHeaderValues)) {
skip = true;
}
}
Collection<String> authTypes = null;
if (authManager != null && authManager instanceof DefaultSVNAuthenticationManager) {
DefaultSVNAuthenticationManager defaultAuthManager = (DefaultSVNAuthenticationManager) authManager;
authTypes = defaultAuthManager.getAuthTypes(myRepository.getLocation());
}
try {
myChallengeCredentials = HTTPAuthentication.parseAuthParameters(authHeaderValues, myChallengeCredentials, myCharset, authTypes, authManager, myRequestCount);
SVNDebugLog.getDefaultLog().logFine(SVNLogType.NETWORK, "server auth method is " + myChallengeCredentials);
} catch (SVNException svne) {
err = svne.getErrorMessage();
break;
}
myChallengeCredentials.setChallengeParameter("method", method);
myChallengeCredentials.setChallengeParameter("uri", HTTPParser.getCanonicalPath(path, null).toString());
if (skip) {
close();
continue;
}
HTTPNTLMAuthentication ntlmAuth = null;
HTTPNegotiateAuthentication negoAuth = null;
if (myChallengeCredentials instanceof HTTPNTLMAuthentication) {
ntlmAuthIsRequired = true;
ntlmAuth = (HTTPNTLMAuthentication)myChallengeCredentials;
if (ntlmAuth.isInType3State()) {
continue;
}
} else if (myChallengeCredentials instanceof HTTPDigestAuthentication) {
// continue (retry once) if previous request was acceppted?
if (myLastValidAuth != null) {
myLastValidAuth = null;
continue;
}
} else if (myChallengeCredentials instanceof HTTPNegotiateAuthentication) {
negoAuthIsRequired = true;
negoAuth = (HTTPNegotiateAuthentication)myChallengeCredentials;
if (negoAuth.isStarted()) {
continue;
}
}
myLastValidAuth = null;
if (ntlmAuth != null && authAttempts == 1) {
/*
* if this is the first time we get HTTP_UNAUTHORIZED, NTLM is the target auth scheme
* and JNA is available, we should try a native auth mechanism first without calling
* auth providers.
*/
if (!ntlmAuth.allowPropmtForCredentials()) {
continue;
}
}
if (negoAuth != null && !negoAuth.needsLogin()) {
continue;
}
if (authManager == null) {
err = request.getErrorMessage();
break;
}
realm = myChallengeCredentials.getChallengeParameter("realm");
realm = realm == null ? "" : " " + realm;
realm = composeRealm(realm);
if (httpAuth == null) {
SVNDebugLog.getDefaultLog().logFine(SVNLogType.WC, "SVNPasswordAuthentication requested (first).");
httpAuth = authManager.getFirstAuthentication(ISVNAuthenticationManager.PASSWORD, realm, myRepository.getLocation());
logAuthFetched(httpAuth);
} else if (authAttempts >= requestAttempts) {
BasicAuthenticationManager.acknowledgeAuthentication(false, ISVNAuthenticationManager.PASSWORD, realm, request.getErrorMessage(), httpAuth, myRepository.getLocation(), authManager);
SVNDebugLog.getDefaultLog().logFine(SVNLogType.WC, "SVNPasswordAuthentication requested (second).");
httpAuth = authManager.getNextAuthentication(ISVNAuthenticationManager.PASSWORD, realm, myRepository.getLocation());
logAuthFetched(httpAuth);
}
if (httpAuth == null) {
err = SVNErrorMessage.create(SVNErrorCode.CANCELLED, new SVNCancelException(SVNErrorMessage.create(SVNErrorCode.CANCELLED, "ISVNAuthentication provider did not provide credentials; HTTP authorization cancelled.")));
break;
}
if (httpAuth != null) {
myChallengeCredentials.setCredentials((SVNPasswordAuthentication) httpAuth);
}
continue;
} else if (myLastStatus.getCode() == HttpURLConnection.HTTP_MOVED_PERM || myLastStatus.getCode() == HttpURLConnection.HTTP_MOVED_TEMP) {
String newLocation = request.getResponseHeader().getFirstHeaderValue(HTTPHeader.LOCATION_HEADER);
if (newLocation == null) {
err = request.getErrorMessage();
break;
}
int hostIndex = newLocation.indexOf("://");
if (hostIndex > 0) {
hostIndex += 3;
hostIndex = newLocation.indexOf("/", hostIndex);
}
if (hostIndex > 0 && hostIndex < newLocation.length()) {
String newPath = newLocation.substring(hostIndex);
if (newPath.endsWith("/") &&
!newPath.endsWith("//") && !path.endsWith("/") &&
newPath.substring(0, newPath.length() - 1).equals(path)) {
path += "//";
continue;
}
}
err = request.getErrorMessage();
close();
} else if (request.getErrorMessage() != null) {
err = request.getErrorMessage();
} else {
ntlmProxyAuthIsRequired = false;
ntlmAuthIsRequired = false;
negoAuthIsRequired = false;
}
if (err != null) {
break;
}
if (myIsProxied) {
if (proxyManager != null) {
proxyManager.acknowledgeProxyContext(true, null);
}
}
if (httpAuth != null && realm != null && authManager != null) {
BasicAuthenticationManager.acknowledgeAuthentication(true, ISVNAuthenticationManager.PASSWORD, realm, null, httpAuth, myRepository.getLocation(), authManager);
}
if (trustManager != null && authManager != null) {
authManager.acknowledgeTrustManager(trustManager);
}
if (httpAuth != null) {
myLastValidAuth = httpAuth;
}
if (authManager instanceof ISVNAuthenticationManagerExt) {
((ISVNAuthenticationManagerExt)authManager).acknowledgeConnectionSuccessful(myRepository.getLocation());
}
myLastStatus.setHeader(request.getResponseHeader());
return myLastStatus;
}
// force close on error that was not processed before.
// these are errors that has no relation to http status (processing error or cancellation).
close();
if (err != null && err.getErrorCode().getCategory() != SVNErrorCode.RA_DAV_CATEGORY &&
err.getErrorCode() != SVNErrorCode.UNSUPPORTED_FEATURE) {
SVNErrorManager.error(err, SVNLogType.NETWORK);
}
// err2 is another default context...
myRepository.getDebugLog().logFine(SVNLogType.NETWORK, new Exception(err.getMessage()));
SVNErrorMessage err2 = SVNErrorMessage.create(SVNErrorCode.RA_DAV_REQUEST_FAILED, "{0} request failed on ''{1}''", new Object[] {method, path}, err.getType(), err.getCause());
SVNErrorManager.error(err, err2, SVNLogType.NETWORK);
return null;
}
|
diff --git a/atlas-web/src/main/java/uk/ac/ebi/gxa/requesthandlers/query/ExperimentsPopupRequestHandler.java b/atlas-web/src/main/java/uk/ac/ebi/gxa/requesthandlers/query/ExperimentsPopupRequestHandler.java
index 0283ccbed..b81d22374 100644
--- a/atlas-web/src/main/java/uk/ac/ebi/gxa/requesthandlers/query/ExperimentsPopupRequestHandler.java
+++ b/atlas-web/src/main/java/uk/ac/ebi/gxa/requesthandlers/query/ExperimentsPopupRequestHandler.java
@@ -1,248 +1,248 @@
/*
* Copyright 2008-2010 Microarray Informatics Team, EMBL-European Bioinformatics Institute
*
* 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 further details of the Gene Expression Atlas project, including source code,
* downloads and documentation, please see:
*
* http://gxa.github.com/gxa
*/
package uk.ac.ebi.gxa.requesthandlers.query;
import ae3.dao.AtlasSolrDAO;
import ae3.model.AtlasExperiment;
import ae3.model.AtlasGene;
import ae3.service.AtlasStatisticsQueryService;
import ae3.service.structuredquery.Constants;
import uk.ac.ebi.gxa.efo.Efo;
import uk.ac.ebi.gxa.efo.EfoTerm;
import uk.ac.ebi.gxa.properties.AtlasProperties;
import uk.ac.ebi.gxa.requesthandlers.base.AbstractRestRequestHandler;
import uk.ac.ebi.gxa.statistics.Attribute;
import uk.ac.ebi.gxa.statistics.Experiment;
import uk.ac.ebi.gxa.statistics.StatisticsQueryUtils;
import uk.ac.ebi.gxa.statistics.StatisticsType;
import uk.ac.ebi.gxa.utils.EscapeUtil;
import uk.ac.ebi.microarray.atlas.model.ExpressionAnalysis;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
/**
* @author pashky
*/
public class ExperimentsPopupRequestHandler extends AbstractRestRequestHandler {
private AtlasSolrDAO atlasSolrDAO;
private Efo efo;
private AtlasProperties atlasProperties;
private AtlasStatisticsQueryService atlasStatisticsQueryService;
public void setDao(AtlasSolrDAO atlasSolrDAO) {
this.atlasSolrDAO = atlasSolrDAO;
}
public void setEfo(Efo efo) {
this.efo = efo;
}
public void setAtlasProperties(AtlasProperties atlasProperties) {
this.atlasProperties = atlasProperties;
}
public void setAtlasStatisticsQueryService(AtlasStatisticsQueryService atlasStatisticsQueryService) {
this.atlasStatisticsQueryService = atlasStatisticsQueryService;
}
public Object process(HttpServletRequest request) {
Map<String, Object> jsResult = new HashMap<String, Object>();
String geneIdKey = request.getParameter("gene");
String factor = request.getParameter("ef");
String factorValue = request.getParameter("efv");
if (geneIdKey != null && factor != null && factorValue != null) {
boolean isEfo = Constants.EFO_FACTOR_NAME.equals(factor);
jsResult.put("ef", factor);
jsResult.put("eftext", atlasProperties.getCuratedEf(factor));
jsResult.put("efv", factorValue);
if (isEfo) {
EfoTerm term = efo.getTermById(factorValue);
if (term != null) {
jsResult.put("efv", term.getTerm());
}
}
AtlasSolrDAO.AtlasGeneResult result = atlasSolrDAO.getGeneById(geneIdKey);
if (!result.isFound()) {
throw new IllegalArgumentException("Atlas gene " + geneIdKey + " not found");
}
AtlasGene gene = result.getGene();
Map<String, Object> jsGene = new HashMap<String, Object>();
jsGene.put("id", geneIdKey);
jsGene.put("identifier", gene.getGeneIdentifier());
jsGene.put("name", gene.getGeneName());
jsResult.put("gene", jsGene);
Long geneId = Long.parseLong(gene.getGeneId());
- List<Experiment> sortedExperiments = new ArrayList<Experiment>();
+ List<Experiment> experiments = new ArrayList<Experiment>();
if (isEfo) {
- sortedExperiments.addAll(atlasStatisticsQueryService.getExperimentsSortedByPvalueTRank(
- Long.parseLong(gene.getGeneId()), StatisticsType.UP_DOWN, factor, factorValue, isEfo, -1, -1));
+ experiments.addAll(atlasStatisticsQueryService.getExperimentsSortedByPvalueTRank(
+ Long.parseLong(gene.getGeneId()), StatisticsType.UP_DOWN, factor, factorValue, StatisticsQueryUtils.EFO, -1, -1));
} else {
List<Attribute> scoringEfvsForGene = atlasStatisticsQueryService.getScoringEfvsForGene(geneId, StatisticsType.UP_DOWN);
for (Attribute attr : scoringEfvsForGene) {
if (!factor.equals(attr.getEf()))
continue;
- sortedExperiments.addAll(atlasStatisticsQueryService.getExperimentsSortedByPvalueTRank(
- Long.parseLong(gene.getGeneId()), StatisticsType.UP_DOWN, attr.getEf(), attr.getEfv(), isEfo, -1, -1));
+ experiments.addAll(atlasStatisticsQueryService.getExperimentsSortedByPvalueTRank(
+ Long.parseLong(gene.getGeneId()), StatisticsType.UP_DOWN, attr.getEf(), attr.getEfv(), !StatisticsQueryUtils.EFO, -1, -1));
}
}
Map<Long, Map<String, List<Experiment>>> exmap = new HashMap<Long, Map<String, List<Experiment>>>();
- for (Experiment experiment : sortedExperiments) {
+ for (Experiment experiment : experiments) {
Long expId = Long.parseLong(experiment.getExperimentId());
Map<String, List<Experiment>> efmap = exmap.get(expId);
if (efmap == null) {
exmap.put(expId, efmap = new HashMap<String, List<Experiment>>());
}
List<Experiment> list = efmap.get(experiment.getHighestRankAttribute().getEf());
if (list == null) {
efmap.put(experiment.getHighestRankAttribute().getEf(), list = new ArrayList<Experiment>());
}
list.add(experiment);
}
for (Map<String, List<Experiment>> ef : exmap.values()) {
for (List<Experiment> e : ef.values()) {
Collections.sort(e, new Comparator<Experiment>() {
public int compare(Experiment o1, Experiment o2) {
return o1.getpValTStatRank().compareTo(o2.getpValTStatRank());
}
});
}
}
@SuppressWarnings("unchecked")
List<Map.Entry<Long, Map<String, List<Experiment>>>> exps =
new ArrayList<Map.Entry<Long, Map<String, List<Experiment>>>>(exmap.entrySet());
Collections.sort(exps, new Comparator<Map.Entry<Long, Map<String, List<Experiment>>>>() {
public int compare(Map.Entry<Long, Map<String, List<Experiment>>> o1,
Map.Entry<Long, Map<String, List<Experiment>>> o2) {
double minp1 = 1;
for (Map.Entry<String, List<Experiment>> ef : o1.getValue().entrySet()) {
minp1 = Math.min(minp1, ef.getValue().get(0).getpValTStatRank().getPValue());
}
double minp2 = 1;
for (Map.Entry<String, List<Experiment>> ef : o2.getValue().entrySet()) {
minp2 = Math.min(minp2, ef.getValue().get(0).getpValTStatRank().getPValue());
}
return minp1 < minp2 ? -1 : 1;
}
});
int numUp = 0, numDn = 0, numNo = 0;
List<Map> jsExps = new ArrayList<Map>();
for (Map.Entry<Long, Map<String, List<Experiment>>> e : exps) {
AtlasExperiment aexp = atlasSolrDAO.getExperimentById(e.getKey());
if (aexp != null) {
Map<String, Object> jsExp = new HashMap<String, Object>();
jsExp.put("accession", aexp.getAccession());
jsExp.put("name", aexp.getDescription());
jsExp.put("id", e.getKey());
boolean wasup = false;
boolean wasdn = false;
boolean wasno = false;
List<Map> jsEfs = new ArrayList<Map>();
for (Map.Entry<String, List<Experiment>> ef : e.getValue().entrySet()) {
Map<String, Object> jsEf = new HashMap<String, Object>();
jsEf.put("ef", ef.getKey());
jsEf.put("eftext", atlasProperties.getCuratedEf(ef.getKey()));
List<Map> jsEfvs = new ArrayList<Map>();
for (Experiment exp : ef.getValue()) {
Map<String, Object> jsEfv = new HashMap<String, Object>();
boolean isNo = ExpressionAnalysis.isNo(exp.getpValTStatRank().getPValue(), exp.getpValTStatRank().getTStatRank());
boolean isUp = ExpressionAnalysis.isUp(exp.getpValTStatRank().getPValue(), exp.getpValTStatRank().getTStatRank());
jsEfv.put("efv", exp.getHighestRankAttribute().getEfv());
jsEfv.put("isexp", isNo ? "no" : (isUp ? "up" : "dn"));
jsEfv.put("pvalue", exp.getpValTStatRank().getPValue());
jsEfvs.add(jsEfv);
if(isNo)
wasno = true;
else {
if (isUp) {
wasup = true;
}
else {
wasdn = true;
}
}
}
jsEf.put("efvs", jsEfvs);
if(!jsEfvs.isEmpty())
jsEfs.add(jsEf);
}
jsExp.put("efs", jsEfs);
if (wasup) {
++numUp;
}
if (wasdn) {
++numDn;
}
if (wasno) {
++numNo;
}
jsExps.add(jsExp);
}
}
jsResult.put("experiments", jsExps);
String efv;
if (isEfo) {
efv = factorValue;
} else {
efv = EscapeUtil.encode(factor, factorValue);
}
long start = System.currentTimeMillis();
numNo = atlasStatisticsQueryService.getExperimentCountsForGene(efv, StatisticsType.NON_D_E, isEfo == StatisticsQueryUtils.EFO, Long.parseLong(geneIdKey));
log.debug("Obtained non-de counts for gene: " + geneIdKey + " and efv: " + efv + " in: " + (System.currentTimeMillis() - start) + " ms");
jsResult.put("numUp", numUp);
jsResult.put("numDn", numDn);
jsResult.put("numNo", numNo);
}
return jsResult;
}
}
| false | true | public Object process(HttpServletRequest request) {
Map<String, Object> jsResult = new HashMap<String, Object>();
String geneIdKey = request.getParameter("gene");
String factor = request.getParameter("ef");
String factorValue = request.getParameter("efv");
if (geneIdKey != null && factor != null && factorValue != null) {
boolean isEfo = Constants.EFO_FACTOR_NAME.equals(factor);
jsResult.put("ef", factor);
jsResult.put("eftext", atlasProperties.getCuratedEf(factor));
jsResult.put("efv", factorValue);
if (isEfo) {
EfoTerm term = efo.getTermById(factorValue);
if (term != null) {
jsResult.put("efv", term.getTerm());
}
}
AtlasSolrDAO.AtlasGeneResult result = atlasSolrDAO.getGeneById(geneIdKey);
if (!result.isFound()) {
throw new IllegalArgumentException("Atlas gene " + geneIdKey + " not found");
}
AtlasGene gene = result.getGene();
Map<String, Object> jsGene = new HashMap<String, Object>();
jsGene.put("id", geneIdKey);
jsGene.put("identifier", gene.getGeneIdentifier());
jsGene.put("name", gene.getGeneName());
jsResult.put("gene", jsGene);
Long geneId = Long.parseLong(gene.getGeneId());
List<Experiment> sortedExperiments = new ArrayList<Experiment>();
if (isEfo) {
sortedExperiments.addAll(atlasStatisticsQueryService.getExperimentsSortedByPvalueTRank(
Long.parseLong(gene.getGeneId()), StatisticsType.UP_DOWN, factor, factorValue, isEfo, -1, -1));
} else {
List<Attribute> scoringEfvsForGene = atlasStatisticsQueryService.getScoringEfvsForGene(geneId, StatisticsType.UP_DOWN);
for (Attribute attr : scoringEfvsForGene) {
if (!factor.equals(attr.getEf()))
continue;
sortedExperiments.addAll(atlasStatisticsQueryService.getExperimentsSortedByPvalueTRank(
Long.parseLong(gene.getGeneId()), StatisticsType.UP_DOWN, attr.getEf(), attr.getEfv(), isEfo, -1, -1));
}
}
Map<Long, Map<String, List<Experiment>>> exmap = new HashMap<Long, Map<String, List<Experiment>>>();
for (Experiment experiment : sortedExperiments) {
Long expId = Long.parseLong(experiment.getExperimentId());
Map<String, List<Experiment>> efmap = exmap.get(expId);
if (efmap == null) {
exmap.put(expId, efmap = new HashMap<String, List<Experiment>>());
}
List<Experiment> list = efmap.get(experiment.getHighestRankAttribute().getEf());
if (list == null) {
efmap.put(experiment.getHighestRankAttribute().getEf(), list = new ArrayList<Experiment>());
}
list.add(experiment);
}
for (Map<String, List<Experiment>> ef : exmap.values()) {
for (List<Experiment> e : ef.values()) {
Collections.sort(e, new Comparator<Experiment>() {
public int compare(Experiment o1, Experiment o2) {
return o1.getpValTStatRank().compareTo(o2.getpValTStatRank());
}
});
}
}
@SuppressWarnings("unchecked")
List<Map.Entry<Long, Map<String, List<Experiment>>>> exps =
new ArrayList<Map.Entry<Long, Map<String, List<Experiment>>>>(exmap.entrySet());
Collections.sort(exps, new Comparator<Map.Entry<Long, Map<String, List<Experiment>>>>() {
public int compare(Map.Entry<Long, Map<String, List<Experiment>>> o1,
Map.Entry<Long, Map<String, List<Experiment>>> o2) {
double minp1 = 1;
for (Map.Entry<String, List<Experiment>> ef : o1.getValue().entrySet()) {
minp1 = Math.min(minp1, ef.getValue().get(0).getpValTStatRank().getPValue());
}
double minp2 = 1;
for (Map.Entry<String, List<Experiment>> ef : o2.getValue().entrySet()) {
minp2 = Math.min(minp2, ef.getValue().get(0).getpValTStatRank().getPValue());
}
return minp1 < minp2 ? -1 : 1;
}
});
int numUp = 0, numDn = 0, numNo = 0;
List<Map> jsExps = new ArrayList<Map>();
for (Map.Entry<Long, Map<String, List<Experiment>>> e : exps) {
AtlasExperiment aexp = atlasSolrDAO.getExperimentById(e.getKey());
if (aexp != null) {
Map<String, Object> jsExp = new HashMap<String, Object>();
jsExp.put("accession", aexp.getAccession());
jsExp.put("name", aexp.getDescription());
jsExp.put("id", e.getKey());
boolean wasup = false;
boolean wasdn = false;
boolean wasno = false;
List<Map> jsEfs = new ArrayList<Map>();
for (Map.Entry<String, List<Experiment>> ef : e.getValue().entrySet()) {
Map<String, Object> jsEf = new HashMap<String, Object>();
jsEf.put("ef", ef.getKey());
jsEf.put("eftext", atlasProperties.getCuratedEf(ef.getKey()));
List<Map> jsEfvs = new ArrayList<Map>();
for (Experiment exp : ef.getValue()) {
Map<String, Object> jsEfv = new HashMap<String, Object>();
boolean isNo = ExpressionAnalysis.isNo(exp.getpValTStatRank().getPValue(), exp.getpValTStatRank().getTStatRank());
boolean isUp = ExpressionAnalysis.isUp(exp.getpValTStatRank().getPValue(), exp.getpValTStatRank().getTStatRank());
jsEfv.put("efv", exp.getHighestRankAttribute().getEfv());
jsEfv.put("isexp", isNo ? "no" : (isUp ? "up" : "dn"));
jsEfv.put("pvalue", exp.getpValTStatRank().getPValue());
jsEfvs.add(jsEfv);
if(isNo)
wasno = true;
else {
if (isUp) {
wasup = true;
}
else {
wasdn = true;
}
}
}
jsEf.put("efvs", jsEfvs);
if(!jsEfvs.isEmpty())
jsEfs.add(jsEf);
}
jsExp.put("efs", jsEfs);
if (wasup) {
++numUp;
}
if (wasdn) {
++numDn;
}
if (wasno) {
++numNo;
}
jsExps.add(jsExp);
}
}
jsResult.put("experiments", jsExps);
String efv;
if (isEfo) {
efv = factorValue;
} else {
efv = EscapeUtil.encode(factor, factorValue);
}
long start = System.currentTimeMillis();
numNo = atlasStatisticsQueryService.getExperimentCountsForGene(efv, StatisticsType.NON_D_E, isEfo == StatisticsQueryUtils.EFO, Long.parseLong(geneIdKey));
log.debug("Obtained non-de counts for gene: " + geneIdKey + " and efv: " + efv + " in: " + (System.currentTimeMillis() - start) + " ms");
jsResult.put("numUp", numUp);
jsResult.put("numDn", numDn);
jsResult.put("numNo", numNo);
}
return jsResult;
}
| public Object process(HttpServletRequest request) {
Map<String, Object> jsResult = new HashMap<String, Object>();
String geneIdKey = request.getParameter("gene");
String factor = request.getParameter("ef");
String factorValue = request.getParameter("efv");
if (geneIdKey != null && factor != null && factorValue != null) {
boolean isEfo = Constants.EFO_FACTOR_NAME.equals(factor);
jsResult.put("ef", factor);
jsResult.put("eftext", atlasProperties.getCuratedEf(factor));
jsResult.put("efv", factorValue);
if (isEfo) {
EfoTerm term = efo.getTermById(factorValue);
if (term != null) {
jsResult.put("efv", term.getTerm());
}
}
AtlasSolrDAO.AtlasGeneResult result = atlasSolrDAO.getGeneById(geneIdKey);
if (!result.isFound()) {
throw new IllegalArgumentException("Atlas gene " + geneIdKey + " not found");
}
AtlasGene gene = result.getGene();
Map<String, Object> jsGene = new HashMap<String, Object>();
jsGene.put("id", geneIdKey);
jsGene.put("identifier", gene.getGeneIdentifier());
jsGene.put("name", gene.getGeneName());
jsResult.put("gene", jsGene);
Long geneId = Long.parseLong(gene.getGeneId());
List<Experiment> experiments = new ArrayList<Experiment>();
if (isEfo) {
experiments.addAll(atlasStatisticsQueryService.getExperimentsSortedByPvalueTRank(
Long.parseLong(gene.getGeneId()), StatisticsType.UP_DOWN, factor, factorValue, StatisticsQueryUtils.EFO, -1, -1));
} else {
List<Attribute> scoringEfvsForGene = atlasStatisticsQueryService.getScoringEfvsForGene(geneId, StatisticsType.UP_DOWN);
for (Attribute attr : scoringEfvsForGene) {
if (!factor.equals(attr.getEf()))
continue;
experiments.addAll(atlasStatisticsQueryService.getExperimentsSortedByPvalueTRank(
Long.parseLong(gene.getGeneId()), StatisticsType.UP_DOWN, attr.getEf(), attr.getEfv(), !StatisticsQueryUtils.EFO, -1, -1));
}
}
Map<Long, Map<String, List<Experiment>>> exmap = new HashMap<Long, Map<String, List<Experiment>>>();
for (Experiment experiment : experiments) {
Long expId = Long.parseLong(experiment.getExperimentId());
Map<String, List<Experiment>> efmap = exmap.get(expId);
if (efmap == null) {
exmap.put(expId, efmap = new HashMap<String, List<Experiment>>());
}
List<Experiment> list = efmap.get(experiment.getHighestRankAttribute().getEf());
if (list == null) {
efmap.put(experiment.getHighestRankAttribute().getEf(), list = new ArrayList<Experiment>());
}
list.add(experiment);
}
for (Map<String, List<Experiment>> ef : exmap.values()) {
for (List<Experiment> e : ef.values()) {
Collections.sort(e, new Comparator<Experiment>() {
public int compare(Experiment o1, Experiment o2) {
return o1.getpValTStatRank().compareTo(o2.getpValTStatRank());
}
});
}
}
@SuppressWarnings("unchecked")
List<Map.Entry<Long, Map<String, List<Experiment>>>> exps =
new ArrayList<Map.Entry<Long, Map<String, List<Experiment>>>>(exmap.entrySet());
Collections.sort(exps, new Comparator<Map.Entry<Long, Map<String, List<Experiment>>>>() {
public int compare(Map.Entry<Long, Map<String, List<Experiment>>> o1,
Map.Entry<Long, Map<String, List<Experiment>>> o2) {
double minp1 = 1;
for (Map.Entry<String, List<Experiment>> ef : o1.getValue().entrySet()) {
minp1 = Math.min(minp1, ef.getValue().get(0).getpValTStatRank().getPValue());
}
double minp2 = 1;
for (Map.Entry<String, List<Experiment>> ef : o2.getValue().entrySet()) {
minp2 = Math.min(minp2, ef.getValue().get(0).getpValTStatRank().getPValue());
}
return minp1 < minp2 ? -1 : 1;
}
});
int numUp = 0, numDn = 0, numNo = 0;
List<Map> jsExps = new ArrayList<Map>();
for (Map.Entry<Long, Map<String, List<Experiment>>> e : exps) {
AtlasExperiment aexp = atlasSolrDAO.getExperimentById(e.getKey());
if (aexp != null) {
Map<String, Object> jsExp = new HashMap<String, Object>();
jsExp.put("accession", aexp.getAccession());
jsExp.put("name", aexp.getDescription());
jsExp.put("id", e.getKey());
boolean wasup = false;
boolean wasdn = false;
boolean wasno = false;
List<Map> jsEfs = new ArrayList<Map>();
for (Map.Entry<String, List<Experiment>> ef : e.getValue().entrySet()) {
Map<String, Object> jsEf = new HashMap<String, Object>();
jsEf.put("ef", ef.getKey());
jsEf.put("eftext", atlasProperties.getCuratedEf(ef.getKey()));
List<Map> jsEfvs = new ArrayList<Map>();
for (Experiment exp : ef.getValue()) {
Map<String, Object> jsEfv = new HashMap<String, Object>();
boolean isNo = ExpressionAnalysis.isNo(exp.getpValTStatRank().getPValue(), exp.getpValTStatRank().getTStatRank());
boolean isUp = ExpressionAnalysis.isUp(exp.getpValTStatRank().getPValue(), exp.getpValTStatRank().getTStatRank());
jsEfv.put("efv", exp.getHighestRankAttribute().getEfv());
jsEfv.put("isexp", isNo ? "no" : (isUp ? "up" : "dn"));
jsEfv.put("pvalue", exp.getpValTStatRank().getPValue());
jsEfvs.add(jsEfv);
if(isNo)
wasno = true;
else {
if (isUp) {
wasup = true;
}
else {
wasdn = true;
}
}
}
jsEf.put("efvs", jsEfvs);
if(!jsEfvs.isEmpty())
jsEfs.add(jsEf);
}
jsExp.put("efs", jsEfs);
if (wasup) {
++numUp;
}
if (wasdn) {
++numDn;
}
if (wasno) {
++numNo;
}
jsExps.add(jsExp);
}
}
jsResult.put("experiments", jsExps);
String efv;
if (isEfo) {
efv = factorValue;
} else {
efv = EscapeUtil.encode(factor, factorValue);
}
long start = System.currentTimeMillis();
numNo = atlasStatisticsQueryService.getExperimentCountsForGene(efv, StatisticsType.NON_D_E, isEfo == StatisticsQueryUtils.EFO, Long.parseLong(geneIdKey));
log.debug("Obtained non-de counts for gene: " + geneIdKey + " and efv: " + efv + " in: " + (System.currentTimeMillis() - start) + " ms");
jsResult.put("numUp", numUp);
jsResult.put("numDn", numDn);
jsResult.put("numNo", numNo);
}
return jsResult;
}
|
diff --git a/java-configuration-client/src/main/java/com/tjh/swivel/config/model/When.java b/java-configuration-client/src/main/java/com/tjh/swivel/config/model/When.java
index 1f496b2..a033a14 100644
--- a/java-configuration-client/src/main/java/com/tjh/swivel/config/model/When.java
+++ b/java-configuration-client/src/main/java/com/tjh/swivel/config/model/When.java
@@ -1,145 +1,142 @@
package com.tjh.swivel.config.model;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import vanderbilt.util.Maps;
import java.net.URI;
import java.util.Map;
import static vanderbilt.util.Validators.notNull;
public class When {
public static final String METHOD_KEY = "method";
public static final String SCRIPT_KEY = "script";
public static final String CONTENT_KEY = "content";
public static final String CONTENT_TYPE_KEY = "contentType";
public static final String REMOTE_ADDRESS_KEY = "remoteAddress";
private final HttpMethod method;
private String content;
private String contentType;
private String remoteAddress;
private String script;
private URI uri;
public When(HttpMethod method, URI uri) {
this.method = notNull("method", method);
this.uri = notNull("uri", uri);
}
public JSONObject toJSON() {
try {
JSONObject jsonObject = new JSONObject(Maps.asMap(METHOD_KEY, method.getMethodName()));
- if (script != null) {
- jsonObject.put(SCRIPT_KEY, script);
- } else {
- Map<String, Object> optionalValues = Maps.<String, Object>asMap(
- CONTENT_KEY, content,
- CONTENT_TYPE_KEY, contentType,
- REMOTE_ADDRESS_KEY, remoteAddress);
- for (Map.Entry<String, Object> entry : optionalValues.entrySet()) {
- jsonObject.putOpt(entry.getKey(), entry.getValue());
- }
+ Map<String, Object> optionalValues = Maps.<String, Object>asMap(
+ CONTENT_KEY, content,
+ SCRIPT_KEY, script,
+ CONTENT_TYPE_KEY, contentType,
+ REMOTE_ADDRESS_KEY, remoteAddress);
+ for (Map.Entry<String, Object> entry : optionalValues.entrySet()) {
+ jsonObject.putOpt(entry.getKey(), entry.getValue());
}
return jsonObject;
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
//<editor-fold desc="builder">
public When withContent(String content) {
setContent(content);
return this;
}
public When as(String contentType) {
setContentType(contentType);
return this;
}
public When from(String remoteAddress) {
setRemoteAddress(remoteAddress);
return this;
}
//YELLOWTAG:TJH - Contemplating either 'helpfully' replacing '\\' with '\\\\', or
//at least issuing a warning. Modifying data on a setter is full of problems,
//but so is the nasty double-interpreted strings that will be coming through here.
public When matches(String script) {
setScript(script);
return this;
}
//</editor-fold>
//<editor-fold desc="Object">
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof When)) return false;
When when = (When) o;
return method == when.method
&& uri.equals(when.uri)
&& !(content != null ? !content.equals(when.content) : when.content != null)
&& !(contentType != null ? !contentType.equals(when.contentType) : when.contentType != null)
&& !(remoteAddress != null ? !remoteAddress.equals(when.remoteAddress) : when.remoteAddress != null)
&& !(script != null ? !script.equals(when.script) : when.script != null);
}
@Override
public int hashCode() {
int result = method.hashCode();
result = 31 * result + uri.hashCode();
result = 31 * result + (content != null ? content.hashCode() : 0);
result = 31 * result + (contentType != null ? contentType.hashCode() : 0);
result = 31 * result + (remoteAddress != null ? remoteAddress.hashCode() : 0);
result = 31 * result + (script != null ? script.hashCode() : 0);
return result;
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("When{");
sb.append("method=").append(method);
sb.append(", content='").append(content).append('\'');
sb.append(", contentType='").append(contentType).append('\'');
sb.append(", remoteAddress='").append(remoteAddress).append('\'');
sb.append(", script='").append(script).append('\'');
sb.append(", uri=").append(uri);
sb.append('}');
return sb.toString();
}
//</editor-fold>
//<editor-fold desc="bean">
public void setContent(String content) {
if (!method.isAcceptsData()) {
throw new IllegalStateException("HTTP '" + method.getMethodName() + "' does not accept data");
}
this.content = content;
}
public String getContent() { return content; }
public HttpMethod getMethod() { return method; }
public String getContentType() { return contentType; }
public void setContentType(String contentType) { this.contentType = contentType; }
public String getRemoteAddress() { return remoteAddress; }
public void setRemoteAddress(String remoteAddress) { this.remoteAddress = remoteAddress; }
public String getScript() { return script; }
public void setScript(String script) { this.script = script; }
public URI getUri() { return uri; }
//</editor-fold>
}
| true | true | public JSONObject toJSON() {
try {
JSONObject jsonObject = new JSONObject(Maps.asMap(METHOD_KEY, method.getMethodName()));
if (script != null) {
jsonObject.put(SCRIPT_KEY, script);
} else {
Map<String, Object> optionalValues = Maps.<String, Object>asMap(
CONTENT_KEY, content,
CONTENT_TYPE_KEY, contentType,
REMOTE_ADDRESS_KEY, remoteAddress);
for (Map.Entry<String, Object> entry : optionalValues.entrySet()) {
jsonObject.putOpt(entry.getKey(), entry.getValue());
}
}
return jsonObject;
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
| public JSONObject toJSON() {
try {
JSONObject jsonObject = new JSONObject(Maps.asMap(METHOD_KEY, method.getMethodName()));
Map<String, Object> optionalValues = Maps.<String, Object>asMap(
CONTENT_KEY, content,
SCRIPT_KEY, script,
CONTENT_TYPE_KEY, contentType,
REMOTE_ADDRESS_KEY, remoteAddress);
for (Map.Entry<String, Object> entry : optionalValues.entrySet()) {
jsonObject.putOpt(entry.getKey(), entry.getValue());
}
return jsonObject;
} catch (JSONException e) {
throw new RuntimeException(e);
}
}
|
diff --git a/project-set/external/testing/test-support/src/main/java/com/rackspace/papi/mocks/MockServiceResource.java b/project-set/external/testing/test-support/src/main/java/com/rackspace/papi/mocks/MockServiceResource.java
index a01b5fee20..5e19baee84 100644
--- a/project-set/external/testing/test-support/src/main/java/com/rackspace/papi/mocks/MockServiceResource.java
+++ b/project-set/external/testing/test-support/src/main/java/com/rackspace/papi/mocks/MockServiceResource.java
@@ -1,82 +1,82 @@
package com.rackspace.papi.mocks;
import java.util.List;
import java.util.Set;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import com.rackspace.papi.components.limits.schema.*;
/**
*
* @author malconis
*/
@Path("/mockendservice/")
public class MockServiceResource {
protected ObjectFactory factory;
private String[] absNames = {"Admin", "Tech", "Demo"};
public MockServiceResource() {
factory = new ObjectFactory();
}
@GET
@Path("{id : .*}")
public Response getEndService(@Context HttpHeaders headers, @Context UriInfo uri) {
Set<String> headerPairs = headers.getRequestHeaders().keySet();
Set<String> queryParams = uri.getQueryParameters().keySet();
String resp = "<html>\n\t<head>\n\t\t<title>Servlet version</title>\n\t</head>\n\t<body>\n\t\t<h1>Servlet version at "
+ uri.getPath() + "</h1>";
List<String> header;
if (!headerPairs.isEmpty()) {
resp += "\n\t\t<h2>HEADERS</h2>";
for (String h : headerPairs) {
header = headers.getRequestHeader(h);
for (String hh : header) {
resp += "\n\t\t<h3> " + h + " : " + hh + "</h3>";
}
}
}
if (!queryParams.isEmpty()) {
resp += "\n\t\t<h2>Query Parameters</h2>";
for (String q : queryParams) {
- resp += "\n\t\t<h3> " + q + " : " + headers.getRequestHeader(q) + "</h3>";
+ resp += "\n\t\t<h3> " + q + " : " + uri.getQueryParameters().get(q) + "</h3>";
}
}
resp += "\n\t</body>\n</html>";
return Response.ok(resp).build();
}
@GET
@Path("/")
public Response getService(@Context HttpHeaders headers, @Context UriInfo uri) {
return this.getEndService(headers, uri);
}
@GET
@Path("/limits")
public Response getAbsoluteLimits() {
Limits limits = new Limits();
AbsoluteLimitList absList = buildAbsoluteLimits();
limits.setAbsolute(absList);
return Response.ok(factory.createLimits(limits)).build();
}
public AbsoluteLimitList buildAbsoluteLimits() {
AbsoluteLimitList limitList = new AbsoluteLimitList();
AbsoluteLimit abs;
int value = 20;
for (String name : absNames) {
abs = new AbsoluteLimit();
abs.setName(name);
abs.setValue(value -= 5);
limitList.getLimit().add(abs);
}
return limitList;
}
}
| true | true | public Response getEndService(@Context HttpHeaders headers, @Context UriInfo uri) {
Set<String> headerPairs = headers.getRequestHeaders().keySet();
Set<String> queryParams = uri.getQueryParameters().keySet();
String resp = "<html>\n\t<head>\n\t\t<title>Servlet version</title>\n\t</head>\n\t<body>\n\t\t<h1>Servlet version at "
+ uri.getPath() + "</h1>";
List<String> header;
if (!headerPairs.isEmpty()) {
resp += "\n\t\t<h2>HEADERS</h2>";
for (String h : headerPairs) {
header = headers.getRequestHeader(h);
for (String hh : header) {
resp += "\n\t\t<h3> " + h + " : " + hh + "</h3>";
}
}
}
if (!queryParams.isEmpty()) {
resp += "\n\t\t<h2>Query Parameters</h2>";
for (String q : queryParams) {
resp += "\n\t\t<h3> " + q + " : " + headers.getRequestHeader(q) + "</h3>";
}
}
resp += "\n\t</body>\n</html>";
return Response.ok(resp).build();
}
| public Response getEndService(@Context HttpHeaders headers, @Context UriInfo uri) {
Set<String> headerPairs = headers.getRequestHeaders().keySet();
Set<String> queryParams = uri.getQueryParameters().keySet();
String resp = "<html>\n\t<head>\n\t\t<title>Servlet version</title>\n\t</head>\n\t<body>\n\t\t<h1>Servlet version at "
+ uri.getPath() + "</h1>";
List<String> header;
if (!headerPairs.isEmpty()) {
resp += "\n\t\t<h2>HEADERS</h2>";
for (String h : headerPairs) {
header = headers.getRequestHeader(h);
for (String hh : header) {
resp += "\n\t\t<h3> " + h + " : " + hh + "</h3>";
}
}
}
if (!queryParams.isEmpty()) {
resp += "\n\t\t<h2>Query Parameters</h2>";
for (String q : queryParams) {
resp += "\n\t\t<h3> " + q + " : " + uri.getQueryParameters().get(q) + "</h3>";
}
}
resp += "\n\t</body>\n</html>";
return Response.ok(resp).build();
}
|
diff --git a/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/javascript/DebugFrameImpl.java b/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/javascript/DebugFrameImpl.java
index a36b8aad1..045d8c79b 100644
--- a/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/javascript/DebugFrameImpl.java
+++ b/htmlunit/src/main/java/com/gargoylesoftware/htmlunit/javascript/DebugFrameImpl.java
@@ -1,239 +1,239 @@
/*
* Copyright (c) 2002-2008 Gargoyle Software 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:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. 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.
* 3. The end-user documentation included with the redistribution, if any, must
* include the following acknowledgment:
*
* "This product includes software developed by Gargoyle Software Inc.
* (http://www.GargoyleSoftware.com/)."
*
* Alternately, this acknowledgment may appear in the software itself, if
* and wherever such third-party acknowledgments normally appear.
* 4. The name "Gargoyle Software" must not be used to endorse or promote
* products derived from this software without prior written permission.
* For written permission, please contact [email protected].
* 5. Products derived from this software may not be called "HtmlUnit", nor may
* "HtmlUnit" appear in their name, without prior written permission of
* Gargoyle Software Inc.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 GARGOYLE
* SOFTWARE INC. OR ITS 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.gargoylesoftware.htmlunit.javascript;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mozilla.javascript.Callable;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.NativeFunction;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.debug.DebugFrame;
import org.mozilla.javascript.debug.DebuggableScript;
/**
* <p>
* HtmlUnit's implementation of the {@link DebugFrame} interface, which logs stack entries as well
* as exceptions. All logging is done at the <tt>TRACE</tt> level. This class does a fairly good
* job of guessing names for anonymous functions when they are referenced by name from an existing
* object. See <a href="http://www.mozilla.org/rhino/rhino15R4-debugger.html">the Rhino
* documentation</a> or <a
* href="http://lxr.mozilla.org/mozilla/source/js/rhino/src/org/mozilla/javascript/debug/DebugFrame.java">the
* interface source code</a> for more information on the {@link DebugFrame} interface and its uses.
* </p>
*
* <p>
* Please note that this class is intended mainly to aid in the debugging and development of
* HtmlUnit itself, rather than the debugging and development of web applications.
* </p>
*
* @version $Revision$
* @author Daniel Gredler
* @see DebuggerImpl
*/
public class DebugFrameImpl implements DebugFrame {
private static final Log LOG = LogFactory.getLog(DebugFrameImpl.class);
private final DebuggableScript functionOrScript_;
/**
* Creates a new debug frame.
*
* @param functionOrScript the function or script to which this frame corresponds
*/
public DebugFrameImpl(final DebuggableScript functionOrScript) {
this.functionOrScript_ = functionOrScript;
}
/**
* {@inheritDoc}
*/
public void onEnter(final Context cx, final Scriptable activation, final Scriptable thisObj, final Object[] args) {
if (LOG.isTraceEnabled()) {
final StringBuilder sb = new StringBuilder();
Scriptable parent = activation.getParentScope();
while (parent != null) {
sb.append(" ");
parent = parent.getParentScope();
}
sb.append(this.getFunctionName(thisObj)).append("(");
for (int i = 0; i < args.length; i++) {
sb.append(this.getParamName(i)).append(" : ").append(args[i]);
if (i < args.length - 1) {
sb.append(", ");
}
}
sb.append(") @ line ").append(this.getFirstLine());
sb.append(" of ").append(this.getSourceName());
LOG.trace(sb);
}
}
/**
* {@inheritDoc}
*/
public void onExceptionThrown(final Context cx, final Throwable t) {
if (LOG.isTraceEnabled()) {
LOG.trace("Throwing exception: " + t.getMessage(), t);
}
}
/**
* {@inheritDoc}
*/
public void onExit(final Context cx, final boolean byThrow, final Object resultOrException) {
// Ignore.
}
/**
* {@inheritDoc}
*/
public void onLineChange(final Context cx, final int lineNumber) {
// Ignore.
}
/**
* Returns the name of the function corresponding to this frame, if it is a function and it has
* a name. If the function does not have a name, this method will try to return the name under
* which it was referenced. See <a
* href="http://www.digital-web.com/articles/scope_in_javascript/">this page</a> for a good
* explanation of how the <tt>thisObj</tt> plays into this guess.
*
* @param thisObj the object via which the function was referenced, used to try to guess a
* function name if the function is anonymous
* @return the name of the function corresponding to this frame
*/
private String getFunctionName(final Scriptable thisObj) {
if (this.functionOrScript_.isFunction()) {
final String name = this.functionOrScript_.getFunctionName();
if (name != null && name.length() > 0) {
// A named function -- we can just return the name.
return name;
}
else {
// An anonymous function -- try to figure out how it was referenced.
// For example, someone may have set foo.prototype.bar = function() { ... };
// And then called fooInstance.bar() -- in which case it's "named" bar.
final Object[] ids = thisObj.getIds();
for (int i = 0; i < ids.length; i++) {
final Object id = ids[i];
if (id instanceof String) {
final String s = (String) id;
if (thisObj instanceof ScriptableObject) {
Object o = ((ScriptableObject) thisObj).getGetterOrSetter(s, 0, false);
if (o == null) {
o = ((ScriptableObject) thisObj).getGetterOrSetter(s, 0, true);
if (o != null && o instanceof Callable) {
- return "__defineSetter__ " + s;
+ return "__defineSetter__ " + s;
}
}
else if (o != null && o instanceof Callable) {
- return "__defineGetter__ " + s;
+ return "__defineGetter__ " + s;
}
}
final Object o = thisObj.get(s, thisObj);
if (o instanceof NativeFunction) {
final NativeFunction f = (NativeFunction) o;
if (f.getDebuggableView() == this.functionOrScript_) {
return s;
}
}
}
}
// Unable to intuit a name -- doh!
return "[anonymous]";
}
}
else {
// Just a script -- no function name.
return "[script]";
}
}
/**
* Returns the name of the parameter at the specified index, or <tt>???</tt> if there is no
* corresponding name.
*
* @param index the index of the parameter whose name is to be returned
* @return the name of the parameter at the specified index, or <tt>???</tt> if there is no corresponding name
*/
private String getParamName(final int index) {
if (index >= 0 && this.functionOrScript_.getParamCount() > index) {
return this.functionOrScript_.getParamOrVarName(index);
}
else {
return "???";
}
}
/**
* Returns the name of this frame's source.
*
* @return the name of this frame's source
*/
private String getSourceName() {
return this.functionOrScript_.getSourceName().trim();
}
/**
* Returns the line number of the first line in this frame's function or script, or <tt>???</tt>
* if it cannot be determined. This is necessary because the line numbers provided by Rhino are unordered.
*
* @return the line number of the first line in this frame's function or script, or <tt>???</tt>
* if it cannot be determined
*/
private String getFirstLine() {
int first = Integer.MAX_VALUE;
final int[] lines = this.functionOrScript_.getLineNumbers();
for (int i = 0; i < lines.length; i++) {
final int current = lines[i];
if (current < first) {
first = current;
}
}
if (first != Integer.MAX_VALUE) {
return String.valueOf(first);
}
else {
return "???";
}
}
}
| false | true | private String getFunctionName(final Scriptable thisObj) {
if (this.functionOrScript_.isFunction()) {
final String name = this.functionOrScript_.getFunctionName();
if (name != null && name.length() > 0) {
// A named function -- we can just return the name.
return name;
}
else {
// An anonymous function -- try to figure out how it was referenced.
// For example, someone may have set foo.prototype.bar = function() { ... };
// And then called fooInstance.bar() -- in which case it's "named" bar.
final Object[] ids = thisObj.getIds();
for (int i = 0; i < ids.length; i++) {
final Object id = ids[i];
if (id instanceof String) {
final String s = (String) id;
if (thisObj instanceof ScriptableObject) {
Object o = ((ScriptableObject) thisObj).getGetterOrSetter(s, 0, false);
if (o == null) {
o = ((ScriptableObject) thisObj).getGetterOrSetter(s, 0, true);
if (o != null && o instanceof Callable) {
return "__defineSetter__ " + s;
}
}
else if (o != null && o instanceof Callable) {
return "__defineGetter__ " + s;
}
}
final Object o = thisObj.get(s, thisObj);
if (o instanceof NativeFunction) {
final NativeFunction f = (NativeFunction) o;
if (f.getDebuggableView() == this.functionOrScript_) {
return s;
}
}
}
}
// Unable to intuit a name -- doh!
return "[anonymous]";
}
}
else {
// Just a script -- no function name.
return "[script]";
}
}
| private String getFunctionName(final Scriptable thisObj) {
if (this.functionOrScript_.isFunction()) {
final String name = this.functionOrScript_.getFunctionName();
if (name != null && name.length() > 0) {
// A named function -- we can just return the name.
return name;
}
else {
// An anonymous function -- try to figure out how it was referenced.
// For example, someone may have set foo.prototype.bar = function() { ... };
// And then called fooInstance.bar() -- in which case it's "named" bar.
final Object[] ids = thisObj.getIds();
for (int i = 0; i < ids.length; i++) {
final Object id = ids[i];
if (id instanceof String) {
final String s = (String) id;
if (thisObj instanceof ScriptableObject) {
Object o = ((ScriptableObject) thisObj).getGetterOrSetter(s, 0, false);
if (o == null) {
o = ((ScriptableObject) thisObj).getGetterOrSetter(s, 0, true);
if (o != null && o instanceof Callable) {
return "__defineSetter__ " + s;
}
}
else if (o != null && o instanceof Callable) {
return "__defineGetter__ " + s;
}
}
final Object o = thisObj.get(s, thisObj);
if (o instanceof NativeFunction) {
final NativeFunction f = (NativeFunction) o;
if (f.getDebuggableView() == this.functionOrScript_) {
return s;
}
}
}
}
// Unable to intuit a name -- doh!
return "[anonymous]";
}
}
else {
// Just a script -- no function name.
return "[script]";
}
}
|
diff --git a/src/main/java/edu/cshl/schatz/jnomics/manager/client/compute/Cufflinks.java b/src/main/java/edu/cshl/schatz/jnomics/manager/client/compute/Cufflinks.java
index bf036d2..c0511a8 100644
--- a/src/main/java/edu/cshl/schatz/jnomics/manager/client/compute/Cufflinks.java
+++ b/src/main/java/edu/cshl/schatz/jnomics/manager/client/compute/Cufflinks.java
@@ -1,84 +1,84 @@
package edu.cshl.schatz.jnomics.manager.client.compute;
import edu.cshl.schatz.jnomics.manager.api.JnomicsThriftFileStatus;
import edu.cshl.schatz.jnomics.manager.api.JnomicsThriftJobID;
import edu.cshl.schatz.jnomics.manager.client.Utility;
import edu.cshl.schatz.jnomics.manager.client.ann.Flag;
import edu.cshl.schatz.jnomics.manager.client.ann.FunctionDescription;
import edu.cshl.schatz.jnomics.manager.client.ann.Parameter;
import edu.cshl.schatz.jnomics.manager.common.KBaseIDTranslator;
import edu.cshl.schatz.jnomics.manager.client.fs.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
/**
* User: Sri
*/
@FunctionDescription(description = "Cufflinks Transcript Assembler\n"+
"Assembles transcripts for each sample.\n"+
"Input and Output must reside on the Cluster's filesystem. \n"+
"Optional additonal arguments may be supplied to \n"+
"cufflinks. These options are passed as a string to cufflinks and should include hyphens(-)\n"+
"if necessary.\n"
)
public class Cufflinks extends ComputeBase {
@Flag(shortForm = "-h",longForm = "--help")
public boolean help;
@Parameter(shortForm = "-in", longForm = "--input", description = "input (bam file)")
public String in;
@Parameter(shortForm = "-out", longForm= "--output", description = "output (directory)")
public String out;
@Parameter(shortForm = "-ref_gtf", longForm= "--reference_gtf", description = "reference gtf(.gtf)")
public String ref_gtf;
@Parameter(shortForm = "-assembly_opts", longForm = "--assembly_options", description = "options to pass to Cufflinks (optional)")
public String assembly_opts;
@Parameter(shortForm = "-working_dir", longForm = "--working_dir", description = "workingdir (optional)")
public String working_dir;
@Override
public void handle(List<String> remainingArgs,Properties properties) throws Exception {
super.handle(remainingArgs,properties);
if(help){
System.out.println(Utility.helpFromParameters(this.getClass()));
return;
}else if(null == in){
System.out.println("missing -in parameter");
}else if(null == out){
System.out.println("missing -out parameter");
}else if(!fsclient.checkFileStatus(in, auth)){
System.out.println("ERROR : " + in + " file does'nt exist ");
}else if(fsclient.checkFileStatus(out, auth)){
System.out.println("ERROR : Output directory already exists");
}else{
-// String clean_org = KBaseIDTranslator.translate(organism);
+ //String clean_org = KBaseIDTranslator.translate(organism);
// List<JnomicsThriftFileStatus> stats = client.listStatus(organism, auth);
// StringBuilder sb = new StringBuilder();
// for(String opts : align_opts){
// sb.append(" " + opts);
// }
// System.out.println("align_opts is " + assembly_opts + " in path is " + "outpath is " + out + "workingdir is " + working_dir);
JnomicsThriftJobID jobID = client.callCufflinks(
in,
out,
Utility.nullToString(ref_gtf),
Utility.nullToString(assembly_opts),
Utility.nullToString(working_dir),
auth);
System.out.println("Submitted Job: " + jobID.getJob_id());
return;
}
System.out.println(Utility.helpFromParameters(this.getClass()));
}
}
| true | true | public void handle(List<String> remainingArgs,Properties properties) throws Exception {
super.handle(remainingArgs,properties);
if(help){
System.out.println(Utility.helpFromParameters(this.getClass()));
return;
}else if(null == in){
System.out.println("missing -in parameter");
}else if(null == out){
System.out.println("missing -out parameter");
}else if(!fsclient.checkFileStatus(in, auth)){
System.out.println("ERROR : " + in + " file does'nt exist ");
}else if(fsclient.checkFileStatus(out, auth)){
System.out.println("ERROR : Output directory already exists");
}else{
// String clean_org = KBaseIDTranslator.translate(organism);
// List<JnomicsThriftFileStatus> stats = client.listStatus(organism, auth);
// StringBuilder sb = new StringBuilder();
// for(String opts : align_opts){
// sb.append(" " + opts);
// }
// System.out.println("align_opts is " + assembly_opts + " in path is " + "outpath is " + out + "workingdir is " + working_dir);
JnomicsThriftJobID jobID = client.callCufflinks(
in,
out,
Utility.nullToString(ref_gtf),
Utility.nullToString(assembly_opts),
Utility.nullToString(working_dir),
auth);
System.out.println("Submitted Job: " + jobID.getJob_id());
return;
}
System.out.println(Utility.helpFromParameters(this.getClass()));
}
| public void handle(List<String> remainingArgs,Properties properties) throws Exception {
super.handle(remainingArgs,properties);
if(help){
System.out.println(Utility.helpFromParameters(this.getClass()));
return;
}else if(null == in){
System.out.println("missing -in parameter");
}else if(null == out){
System.out.println("missing -out parameter");
}else if(!fsclient.checkFileStatus(in, auth)){
System.out.println("ERROR : " + in + " file does'nt exist ");
}else if(fsclient.checkFileStatus(out, auth)){
System.out.println("ERROR : Output directory already exists");
}else{
//String clean_org = KBaseIDTranslator.translate(organism);
// List<JnomicsThriftFileStatus> stats = client.listStatus(organism, auth);
// StringBuilder sb = new StringBuilder();
// for(String opts : align_opts){
// sb.append(" " + opts);
// }
// System.out.println("align_opts is " + assembly_opts + " in path is " + "outpath is " + out + "workingdir is " + working_dir);
JnomicsThriftJobID jobID = client.callCufflinks(
in,
out,
Utility.nullToString(ref_gtf),
Utility.nullToString(assembly_opts),
Utility.nullToString(working_dir),
auth);
System.out.println("Submitted Job: " + jobID.getJob_id());
return;
}
System.out.println(Utility.helpFromParameters(this.getClass()));
}
|
diff --git a/bukkit/cpw/mods/fml/server/FMLBukkitHandler.java b/bukkit/cpw/mods/fml/server/FMLBukkitHandler.java
index f552501c..5e0286bb 100644
--- a/bukkit/cpw/mods/fml/server/FMLBukkitHandler.java
+++ b/bukkit/cpw/mods/fml/server/FMLBukkitHandler.java
@@ -1,514 +1,514 @@
/*
* The FML Forge Mod Loader suite. Copyright (C) 2012 cpw
*
* 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 any later version.
*
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
package cpw.mods.fml.server;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Random;
import java.util.logging.Logger;
import net.minecraft.server.MinecraftServer;
import net.minecraft.server.BaseMod;
import net.minecraft.server.BiomeBase;
import net.minecraft.server.CommonRegistry;
import net.minecraft.server.EntityItem;
import net.minecraft.server.EntityHuman;
import net.minecraft.server.IChunkProvider;
import net.minecraft.server.ICommandListener;
import net.minecraft.server.IInventory;
import net.minecraft.server.ItemStack;
import net.minecraft.server.NetworkManager;
import net.minecraft.server.Packet1Login;
import net.minecraft.server.Packet250CustomPayload;
import net.minecraft.server.Packet3Chat;
import net.minecraft.server.BukkitRegistry;
import net.minecraft.server.World;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.IFMLSidedHandler;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.ModContainer;
/**
* Handles primary communication from hooked code into the system
*
* The FML entry point is {@link #onPreLoad(MinecraftServer)} called from {@link MinecraftServer}
*
* Obfuscated code should focus on this class and other members of the "server" (or "client") code
*
* The actual mod loading is handled at arms length by {@link Loader}
*
* It is expected that a similar class will exist for each target environment: Bukkit and Client side.
*
* It should not be directly modified.
*
* @author cpw
*
*/
public class FMLBukkitHandler implements IFMLSidedHandler
{
/**
* The singleton
*/
private static final FMLBukkitHandler INSTANCE = new FMLBukkitHandler();
/**
* A reference to the server itself
*/
private MinecraftServer server;
/**
* A handy list of the default overworld biomes
*/
private BiomeBase[] defaultOverworldBiomes;
/**
* Called to start the whole game off from {@link MinecraftServer#startServer}
* @param minecraftServer
*/
public void onPreLoad(MinecraftServer minecraftServer)
{
try
{
Class.forName("BaseModMp", false, getClass().getClassLoader());
- MinecraftServer.field_6038_a.severe(""
+ MinecraftServer.log.severe(""
+ "Forge Mod Loader has detected that this server has an ModLoaderMP installed alongside Forge Mod Loader.\n"
+ "This will cause a serious problem with compatibility. To protect your worlds, this minecraft server will now shutdown.\n"
+ "You should follow the installation instructions of either Minecraft Forge of Forge Mod Loader and NOT install ModLoaderMP \n"
+ "into the minecraft_server.jar file "
+ "before this server will be allowed to start up.\n\nFailure to do so will simply result in more startup failures.\n\n"
+ "The authors of Minecraft Forge and Forge Mod Loader strongly suggest you talk to your mod's authors and get them to\nupdate their "
+ "requirements. ModLoaderMP is not compatible with Minecraft Forge on the server and they will need to update their mod\n"
+ "for Minecraft Forge and other server compatibility, unless they are Minecraft Forge mods, in which case they already\n"
+ "don't need ModLoaderMP and the mod author simply has failed to update his requirements and should be informed appropriately.\n\n"
+ "The authors of Forge Mod Loader would like to be compatible with ModLoaderMP but it is closed source and owned by SDK.\n"
+ "SDK, the author of ModLoaderMP, has a standing invitation to submit compatibility patches \n"
+ "to the open source community project that is Forge Mod Loader so that this incompatibility doesn't last. \n"
+ "Users who wish to enjoy mods of both types are "
+ "encouraged to request of SDK that he submit a\ncompatibility patch to the Forge Mod Loader project at \n"
+ "http://github.com/cpw/FML.\nPosting on the minecraft forums at\nhttp://www.minecraftforum.net/topic/86765- (the MLMP thread)\n"
+ "may encourage him in this effort. However, I ask that your requests be polite.\n"
+ "Now, the server has to shutdown so you can reinstall your minecraft_server.jar\nproperly, until such time as we can work together.");
throw new RuntimeException(
"This FML based server has detected an installation of ModLoaderMP alongside. This will cause serious compatibility issues, so the server will now shut down.");
}
catch (ClassNotFoundException e)
{
// We're safe. continue
}
server = minecraftServer;
FMLCommonHandler.instance().registerSidedDelegate(this);
CommonRegistry.registerRegistry(new BukkitRegistry());
Loader.instance().loadMods();
}
/**
* Called a bit later on during server initialization to finish loading mods
*/
public void onLoadComplete()
{
Loader.instance().initializeMods();
}
/**
* Every tick just before world and other ticks occur
*/
public void onPreTick()
{
FMLCommonHandler.instance().gameTickStart();
}
/**
* Every tick just after world and other ticks occur
*/
public void onPostTick()
{
FMLCommonHandler.instance().gameTickEnd();
}
/**
* Get the server instance
* @return
*/
public MinecraftServer getServer()
{
return server;
}
/**
* Get a handle to the server's logger instance
*/
public Logger getMinecraftLogger()
{
return MinecraftServer.log;
}
/**
* Called from ChunkProviderServer when a chunk needs to be populated
*
* To avoid polluting the worldgen seed, we generate a new random from the world seed and
* generate a seed from that
*
* @param chunkProvider
* @param chunkX
* @param chunkZ
* @param world
* @param generator
*/
public void onChunkPopulate(IChunkProvider chunkProvider, int chunkX, int chunkZ, World world, IChunkProvider generator)
{
Random fmlRandom = new Random(world.getSeed());
long xSeed = fmlRandom.nextLong() >> 2 + 1L;
long zSeed = fmlRandom.nextLong() >> 2 + 1L;
fmlRandom.setSeed((xSeed * chunkX + zSeed * chunkZ) ^ world.getSeed());
for (ModContainer mod : Loader.getModList())
{
if (mod.generatesWorld())
{
mod.getWorldGenerator().generate(fmlRandom, chunkX, chunkZ, world, generator, chunkProvider);
}
}
}
/**
* Called from the furnace to lookup fuel values
*
* @param itemId
* @param itemDamage
* @return
*/
public int fuelLookup(int itemId, int itemDamage)
{
int fv = 0;
for (ModContainer mod : Loader.getModList())
{
fv = Math.max(fv, mod.lookupFuelValue(itemId, itemDamage));
}
return fv;
}
/**
* Is the offered class and instance of BaseMod and therefore a ModLoader mod?
*/
public boolean isModLoaderMod(Class<?> clazz)
{
return BaseMod.class.isAssignableFrom(clazz);
}
/**
* Load the supplied mod class into a mod container
*/
public ModContainer loadBaseModMod(Class<?> clazz, File canonicalFile)
{
@SuppressWarnings("unchecked")
Class <? extends BaseMod > bmClazz = (Class <? extends BaseMod >) clazz;
return new ModLoaderModContainer(bmClazz, canonicalFile);
}
/**
* Called to notify that an item was picked up from the world
* @param entityItem
* @param entityPlayer
*/
public void notifyItemPickup(EntityItem entityItem, EntityHuman entityPlayer)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsPickupNotification())
{
mod.getPickupNotifier().notifyPickup(entityItem, entityPlayer);
}
}
}
/**
* Raise an exception
* @param exception
* @param message
* @param stopGame
*/
public void raiseException(Throwable exception, String message, boolean stopGame)
{
FMLCommonHandler.instance().getFMLLogger().throwing("FMLHandler", "raiseException", exception);
throw new RuntimeException(exception);
}
/**
* Attempt to dispense the item as an entity other than just as a the item itself
*
* @param world
* @param x
* @param y
* @param z
* @param xVelocity
* @param zVelocity
* @param item
* @return
*/
public boolean tryDispensingEntity(World world, double x, double y, double z, byte xVelocity, byte zVelocity, ItemStack item)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsToDispense() && mod.getDispenseHandler().dispense(x, y, z, xVelocity, zVelocity, world, item))
{
return true;
}
}
return false;
}
/**
* @return the instance
*/
public static FMLBukkitHandler instance()
{
return INSTANCE;
}
/**
* Build a list of default overworld biomes
* @return
*/
public BiomeBase[] getDefaultOverworldBiomes()
{
if (defaultOverworldBiomes == null)
{
ArrayList<BiomeBase> biomes = new ArrayList<BiomeBase>(20);
for (int i = 0; i < 23; i++)
{
if ("Sky".equals(BiomeBase.biomes[i].y) || "Hell".equals(BiomeBase.biomes[i].y))
{
continue;
}
biomes.add(BiomeBase.biomes[i]);
}
defaultOverworldBiomes = new BiomeBase[biomes.size()];
biomes.toArray(defaultOverworldBiomes);
}
return defaultOverworldBiomes;
}
/**
* Called when an item is crafted
* @param player
* @param craftedItem
* @param craftingGrid
*/
public void onItemCrafted(EntityHuman player, ItemStack craftedItem, IInventory craftingGrid)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsCraftingNotification())
{
mod.getCraftingHandler().onCrafting(player, craftedItem, craftingGrid);
}
}
}
/**
* Called when an item is smelted
*
* @param player
* @param smeltedItem
*/
public void onItemSmelted(EntityHuman player, ItemStack smeltedItem)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsCraftingNotification())
{
mod.getCraftingHandler().onSmelting(player, smeltedItem);
}
}
}
/**
* Called when a chat packet is received
*
* @param chat
* @param player
* @return true if you want the packet to stop processing and not echo to the rest of the world
*/
public boolean handleChatPacket(Packet3Chat chat, EntityHuman player)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsNetworkPackets() && mod.getNetworkHandler().onChat(chat, player))
{
return true;
}
}
return false;
}
/**
* Called when a packet 250 packet is received from the player
* @param packet
* @param player
*/
public void handlePacket250(Packet250CustomPayload packet, EntityHuman player)
{
if ("REGISTER".equals(packet.tag) || "UNREGISTER".equals(packet.tag))
{
handleClientRegistration(packet, player);
return;
}
ModContainer mod = FMLCommonHandler.instance().getModForChannel(packet.tag);
if (mod != null)
{
mod.getNetworkHandler().onPacket250Packet(packet, player);
}
}
/**
* Handle register requests for packet 250 channels
* @param packet
*/
private void handleClientRegistration(Packet250CustomPayload packet, EntityHuman player)
{
if (packet.data==null) {
return;
}
try
{
for (String channel : new String(packet.data, "UTF8").split("\0"))
{
// Skip it if we don't know it
if (FMLCommonHandler.instance().getModForChannel(channel) == null)
{
continue;
}
if ("REGISTER".equals(packet.tag))
{
FMLCommonHandler.instance().activateChannel(player, channel);
}
else
{
FMLCommonHandler.instance().deactivateChannel(player, channel);
}
}
}
catch (UnsupportedEncodingException e)
{
getMinecraftLogger().warning("Received invalid registration packet");
}
}
/**
* Handle a login
* @param loginPacket
* @param networkManager
*/
public void handleLogin(Packet1Login loginPacket, NetworkManager networkManager)
{
Packet250CustomPayload packet = new Packet250CustomPayload();
packet.tag = "REGISTER";
packet.data = FMLCommonHandler.instance().getPacketRegistry();
packet.length = packet.data.length;
if (packet.length>0) {
networkManager.queue(packet);
}
}
public void announceLogin(EntityHuman player) {
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsPlayerTracking())
{
mod.getPlayerTracker().onPlayerLogin(player);
}
}
}
/**
* Are we a server?
*/
@Override
public boolean isServer()
{
return true;
}
/**
* Are we a client?
*/
@Override
public boolean isClient()
{
return false;
}
@Override
public File getMinecraftRootDirectory()
{
try {
return server.a(".").getCanonicalFile();
} catch (IOException ioe) {
return new File(".");
}
}
/**
* @param var2
* @return
*/
public boolean handleServerCommand(String command, String player, ICommandListener listener)
{
for (ModContainer mod : Loader.getModList()) {
if (mod.wantsConsoleCommands() && mod.getConsoleHandler().handleCommand(command, player, listener)) {
return true;
}
}
return false;
}
/**
* @param player
*/
public void announceLogout(EntityHuman player)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsPlayerTracking())
{
mod.getPlayerTracker().onPlayerLogout(player);
}
}
}
/**
* @param p_28168_1_
*/
public void announceDimensionChange(EntityHuman player)
{
for (ModContainer mod : Loader.getModList())
{
if (mod.wantsPlayerTracking())
{
mod.getPlayerTracker().onPlayerChangedDimension(player);
}
}
}
}
| true | true | public void onPreLoad(MinecraftServer minecraftServer)
{
try
{
Class.forName("BaseModMp", false, getClass().getClassLoader());
MinecraftServer.field_6038_a.severe(""
+ "Forge Mod Loader has detected that this server has an ModLoaderMP installed alongside Forge Mod Loader.\n"
+ "This will cause a serious problem with compatibility. To protect your worlds, this minecraft server will now shutdown.\n"
+ "You should follow the installation instructions of either Minecraft Forge of Forge Mod Loader and NOT install ModLoaderMP \n"
+ "into the minecraft_server.jar file "
+ "before this server will be allowed to start up.\n\nFailure to do so will simply result in more startup failures.\n\n"
+ "The authors of Minecraft Forge and Forge Mod Loader strongly suggest you talk to your mod's authors and get them to\nupdate their "
+ "requirements. ModLoaderMP is not compatible with Minecraft Forge on the server and they will need to update their mod\n"
+ "for Minecraft Forge and other server compatibility, unless they are Minecraft Forge mods, in which case they already\n"
+ "don't need ModLoaderMP and the mod author simply has failed to update his requirements and should be informed appropriately.\n\n"
+ "The authors of Forge Mod Loader would like to be compatible with ModLoaderMP but it is closed source and owned by SDK.\n"
+ "SDK, the author of ModLoaderMP, has a standing invitation to submit compatibility patches \n"
+ "to the open source community project that is Forge Mod Loader so that this incompatibility doesn't last. \n"
+ "Users who wish to enjoy mods of both types are "
+ "encouraged to request of SDK that he submit a\ncompatibility patch to the Forge Mod Loader project at \n"
+ "http://github.com/cpw/FML.\nPosting on the minecraft forums at\nhttp://www.minecraftforum.net/topic/86765- (the MLMP thread)\n"
+ "may encourage him in this effort. However, I ask that your requests be polite.\n"
+ "Now, the server has to shutdown so you can reinstall your minecraft_server.jar\nproperly, until such time as we can work together.");
throw new RuntimeException(
"This FML based server has detected an installation of ModLoaderMP alongside. This will cause serious compatibility issues, so the server will now shut down.");
}
catch (ClassNotFoundException e)
{
// We're safe. continue
}
server = minecraftServer;
FMLCommonHandler.instance().registerSidedDelegate(this);
CommonRegistry.registerRegistry(new BukkitRegistry());
Loader.instance().loadMods();
}
| public void onPreLoad(MinecraftServer minecraftServer)
{
try
{
Class.forName("BaseModMp", false, getClass().getClassLoader());
MinecraftServer.log.severe(""
+ "Forge Mod Loader has detected that this server has an ModLoaderMP installed alongside Forge Mod Loader.\n"
+ "This will cause a serious problem with compatibility. To protect your worlds, this minecraft server will now shutdown.\n"
+ "You should follow the installation instructions of either Minecraft Forge of Forge Mod Loader and NOT install ModLoaderMP \n"
+ "into the minecraft_server.jar file "
+ "before this server will be allowed to start up.\n\nFailure to do so will simply result in more startup failures.\n\n"
+ "The authors of Minecraft Forge and Forge Mod Loader strongly suggest you talk to your mod's authors and get them to\nupdate their "
+ "requirements. ModLoaderMP is not compatible with Minecraft Forge on the server and they will need to update their mod\n"
+ "for Minecraft Forge and other server compatibility, unless they are Minecraft Forge mods, in which case they already\n"
+ "don't need ModLoaderMP and the mod author simply has failed to update his requirements and should be informed appropriately.\n\n"
+ "The authors of Forge Mod Loader would like to be compatible with ModLoaderMP but it is closed source and owned by SDK.\n"
+ "SDK, the author of ModLoaderMP, has a standing invitation to submit compatibility patches \n"
+ "to the open source community project that is Forge Mod Loader so that this incompatibility doesn't last. \n"
+ "Users who wish to enjoy mods of both types are "
+ "encouraged to request of SDK that he submit a\ncompatibility patch to the Forge Mod Loader project at \n"
+ "http://github.com/cpw/FML.\nPosting on the minecraft forums at\nhttp://www.minecraftforum.net/topic/86765- (the MLMP thread)\n"
+ "may encourage him in this effort. However, I ask that your requests be polite.\n"
+ "Now, the server has to shutdown so you can reinstall your minecraft_server.jar\nproperly, until such time as we can work together.");
throw new RuntimeException(
"This FML based server has detected an installation of ModLoaderMP alongside. This will cause serious compatibility issues, so the server will now shut down.");
}
catch (ClassNotFoundException e)
{
// We're safe. continue
}
server = minecraftServer;
FMLCommonHandler.instance().registerSidedDelegate(this);
CommonRegistry.registerRegistry(new BukkitRegistry());
Loader.instance().loadMods();
}
|
diff --git a/src/main/java/net/i2cat/netconf/transport/MockTransport.java b/src/main/java/net/i2cat/netconf/transport/MockTransport.java
index fb428a1..57fb23a 100644
--- a/src/main/java/net/i2cat/netconf/transport/MockTransport.java
+++ b/src/main/java/net/i2cat/netconf/transport/MockTransport.java
@@ -1,312 +1,314 @@
/**
* This file is part of Netconf4j.
*
* Netconf4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Netconf4j 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 Netconf4j. If not, see <http://www.gnu.org/licenses/>.
*/
package net.i2cat.netconf.transport;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Vector;
import net.i2cat.netconf.SessionContext;
import net.i2cat.netconf.errors.TransportException;
import net.i2cat.netconf.messageQueue.MessageQueue;
import net.i2cat.netconf.rpc.Capability;
import net.i2cat.netconf.rpc.Error;
import net.i2cat.netconf.rpc.ErrorSeverity;
import net.i2cat.netconf.rpc.ErrorTag;
import net.i2cat.netconf.rpc.ErrorType;
import net.i2cat.netconf.rpc.Hello;
import net.i2cat.netconf.rpc.Operation;
import net.i2cat.netconf.rpc.Query;
import net.i2cat.netconf.rpc.RPCElement;
import net.i2cat.netconf.rpc.Reply;
import net.i2cat.netconf.utils.FileHelper;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
* This class was implemented to be a dummy transport which could simulate a
* real connection with a device. This connection via SSH with netconf
*/
public class MockTransport implements Transport {
private Log log = LogFactory.getLog(MockTransport.class);
Vector<TransportListener> listeners = new Vector<TransportListener>();
SessionContext context;
ArrayList<Capability> supportedCapabilities;
MessageQueue queue;
int lastMessageId = 0;
String subsystem = "";
boolean modeErrors = false;
private static String path = "src" + File.separator
+ "main" + File.separator
+ "resources" + File.separator
+ "mock";
public static final String fileIPConfiguration = path + File.separator + "ipconfiguration.xml";
/* Extra capabilities */
public static final String fileIPLogicalRouterConfig = path + File.separator + "iplogicalconfiguration.xml";
boolean insideLogicalRouter = true;
public void addListener(TransportListener handler) {
listeners.add(handler);
}
public void setMessageQueue(MessageQueue queue) {
this.queue = queue;
}
public void connect(SessionContext sessionContext) throws TransportException {
context = sessionContext;
if (!context.getScheme().equals("mock"))
throw new TransportException("Mock transport initialized with other scheme: " + context.getScheme());
subsystem = sessionContext.getSubsystem();
Hello hello = new Hello();
hello.setMessageId(String.valueOf(lastMessageId));
hello.setSessionId("1234");
supportedCapabilities = new ArrayList<Capability>();
// FIXME more capabilities?
supportedCapabilities.add(Capability.BASE);
hello.setCapabilities(supportedCapabilities);
queue.put(hello);
for (TransportListener listener : listeners)
listener.transportOpenned();
}
public void disconnect() throws TransportException {
for (TransportListener listener : listeners)
listener.transportClosed();
}
public void sendAsyncQuery(RPCElement elem) throws TransportException {
Reply reply = new Reply();
Vector<Error> errors = new Vector<Error>();
if (elem instanceof Hello) {
// Capability b
ArrayList<Capability> capabilities = ((Hello) elem).getCapabilities();
capabilities.retainAll(this.supportedCapabilities);
context.setActiveCapabilities(capabilities);
}
if (elem instanceof Query) {
Query query = (Query) elem;
Operation op = query.getOperation();
if (op.equals(Operation.COPY_CONFIG)) {
} else if (op.equals(Operation.DELETE_CONFIG)) {
reply.setOk(true);
} else if (op.equals(Operation.EDIT_CONFIG)) {
reply.setOk(true);
} else if (op.equals(Operation.GET)) {
if (query.getFilter() != null && query.getFilterType() != null) {
if (context.getActiveCapabilities().contains(Capability.XPATH)) {
if (!(query.getFilterType().equals("xpath") || query.getFilterType().equals("subtree")))
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : Wrong filter type. Neither xpath nor subtree.");
}
});
else if (query.getFilterType().equals("subtree"))
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : Wrong filter type. Not subtree.");
}
});
}
}
reply.setMessageId(query.getMessageId());
reply.setContain(getDataFromFile(fileIPConfiguration));
} else if (op.equals(Operation.GET_CONFIG)) {
if (query.getSource() == null)
errors.add(new Error() {
{
setTag(ErrorTag.MISSING_ELEMENT);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-element> : No source configuration specified");
}
});
if (query.getSource() == null && query.getSource().equals("running")) {
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ELEMENT);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-element> : Wrong configuration.");
}
});
}
if (query.getFilter() != null && query.getFilterType() != null) {
if (context.getActiveCapabilities().contains(Capability.XPATH)) {
if (!(query.getFilterType().equals("xpath") || query.getFilterType().equals("subtree")))
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : Wrong filter type. Neither xpath nor subtree.");
}
});
else if (query.getFilterType().equals("subtree"))
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : Wrong filter type. Not subtree.");
}
});
}
}
reply.setMessageId(query.getMessageId());
if (!insideLogicalRouter) {
reply.setContain(getDataFromFile(fileIPConfiguration));
} else {
reply.setContain(getDataFromFile(fileIPLogicalRouterConfig));
}
} else if (op.equals(Operation.KILL_SESSION)) {
+ insideLogicalRouter = false;
disconnect();
return;
} else if (op.equals(Operation.CLOSE_SESSION)) {
reply.setMessageId(query.getMessageId());
reply.setOk(true);
+ insideLogicalRouter = false;
disconnect();
} else if (op.equals(Operation.LOCK)) {
error("LOCK not implemented");
} else if (op.equals(Operation.UNLOCK)) {
error("UNLOCK not implemented");
}
/* include junos capabilities operations */
else if (op.equals(Operation.SET_LOGICAL_ROUTER)) {
reply.setMessageId(query.getMessageId());
reply.setContain("<cli><logical-system>" + query.getIdLogicalRouter() + "</logical-system></cli>");
insideLogicalRouter = true;
}
}
// force to add errors in the response message
if (subsystem.equals("errorServer"))
addErrors(errors);
if (errors.size() > 0)
reply.setErrors(errors);
queue.put(reply);
}
public String getDataFromFile(String fileConfig) throws TransportException {
String str = "";
String currentPath = System.getProperty("user.dir");
log.info("Trying to open " + currentPath + File.separator + fileConfig);
try {
FileInputStream inputFile = new FileInputStream(fileConfig);
return FileHelper.readStringFromFile(inputFile);
} catch (FileNotFoundException e) {
throw new TransportException(e.getMessage());
}
}
private void error(String msg) throws TransportException {
throw new TransportException(msg);
}
private void addErrors(Vector<Error> errors) {
errors.add(new Error() {
{
setTag(ErrorTag.INVALID_VALUE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("");
}
});
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : ");
}
});
errors.add(new Error() {
{
setTag(ErrorTag.MISSING_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : ");
}
});
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ELEMENT);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-element> : ");
}
});
errors.add(new Error() {
{
setTag(ErrorTag.MISSING_ELEMENT);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-element> : ");
}
});
}
}
| false | true | public void sendAsyncQuery(RPCElement elem) throws TransportException {
Reply reply = new Reply();
Vector<Error> errors = new Vector<Error>();
if (elem instanceof Hello) {
// Capability b
ArrayList<Capability> capabilities = ((Hello) elem).getCapabilities();
capabilities.retainAll(this.supportedCapabilities);
context.setActiveCapabilities(capabilities);
}
if (elem instanceof Query) {
Query query = (Query) elem;
Operation op = query.getOperation();
if (op.equals(Operation.COPY_CONFIG)) {
} else if (op.equals(Operation.DELETE_CONFIG)) {
reply.setOk(true);
} else if (op.equals(Operation.EDIT_CONFIG)) {
reply.setOk(true);
} else if (op.equals(Operation.GET)) {
if (query.getFilter() != null && query.getFilterType() != null) {
if (context.getActiveCapabilities().contains(Capability.XPATH)) {
if (!(query.getFilterType().equals("xpath") || query.getFilterType().equals("subtree")))
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : Wrong filter type. Neither xpath nor subtree.");
}
});
else if (query.getFilterType().equals("subtree"))
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : Wrong filter type. Not subtree.");
}
});
}
}
reply.setMessageId(query.getMessageId());
reply.setContain(getDataFromFile(fileIPConfiguration));
} else if (op.equals(Operation.GET_CONFIG)) {
if (query.getSource() == null)
errors.add(new Error() {
{
setTag(ErrorTag.MISSING_ELEMENT);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-element> : No source configuration specified");
}
});
if (query.getSource() == null && query.getSource().equals("running")) {
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ELEMENT);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-element> : Wrong configuration.");
}
});
}
if (query.getFilter() != null && query.getFilterType() != null) {
if (context.getActiveCapabilities().contains(Capability.XPATH)) {
if (!(query.getFilterType().equals("xpath") || query.getFilterType().equals("subtree")))
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : Wrong filter type. Neither xpath nor subtree.");
}
});
else if (query.getFilterType().equals("subtree"))
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : Wrong filter type. Not subtree.");
}
});
}
}
reply.setMessageId(query.getMessageId());
if (!insideLogicalRouter) {
reply.setContain(getDataFromFile(fileIPConfiguration));
} else {
reply.setContain(getDataFromFile(fileIPLogicalRouterConfig));
}
} else if (op.equals(Operation.KILL_SESSION)) {
disconnect();
return;
} else if (op.equals(Operation.CLOSE_SESSION)) {
reply.setMessageId(query.getMessageId());
reply.setOk(true);
disconnect();
} else if (op.equals(Operation.LOCK)) {
error("LOCK not implemented");
} else if (op.equals(Operation.UNLOCK)) {
error("UNLOCK not implemented");
}
/* include junos capabilities operations */
else if (op.equals(Operation.SET_LOGICAL_ROUTER)) {
reply.setMessageId(query.getMessageId());
reply.setContain("<cli><logical-system>" + query.getIdLogicalRouter() + "</logical-system></cli>");
insideLogicalRouter = true;
}
}
// force to add errors in the response message
if (subsystem.equals("errorServer"))
addErrors(errors);
if (errors.size() > 0)
reply.setErrors(errors);
queue.put(reply);
}
| public void sendAsyncQuery(RPCElement elem) throws TransportException {
Reply reply = new Reply();
Vector<Error> errors = new Vector<Error>();
if (elem instanceof Hello) {
// Capability b
ArrayList<Capability> capabilities = ((Hello) elem).getCapabilities();
capabilities.retainAll(this.supportedCapabilities);
context.setActiveCapabilities(capabilities);
}
if (elem instanceof Query) {
Query query = (Query) elem;
Operation op = query.getOperation();
if (op.equals(Operation.COPY_CONFIG)) {
} else if (op.equals(Operation.DELETE_CONFIG)) {
reply.setOk(true);
} else if (op.equals(Operation.EDIT_CONFIG)) {
reply.setOk(true);
} else if (op.equals(Operation.GET)) {
if (query.getFilter() != null && query.getFilterType() != null) {
if (context.getActiveCapabilities().contains(Capability.XPATH)) {
if (!(query.getFilterType().equals("xpath") || query.getFilterType().equals("subtree")))
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : Wrong filter type. Neither xpath nor subtree.");
}
});
else if (query.getFilterType().equals("subtree"))
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : Wrong filter type. Not subtree.");
}
});
}
}
reply.setMessageId(query.getMessageId());
reply.setContain(getDataFromFile(fileIPConfiguration));
} else if (op.equals(Operation.GET_CONFIG)) {
if (query.getSource() == null)
errors.add(new Error() {
{
setTag(ErrorTag.MISSING_ELEMENT);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-element> : No source configuration specified");
}
});
if (query.getSource() == null && query.getSource().equals("running")) {
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ELEMENT);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-element> : Wrong configuration.");
}
});
}
if (query.getFilter() != null && query.getFilterType() != null) {
if (context.getActiveCapabilities().contains(Capability.XPATH)) {
if (!(query.getFilterType().equals("xpath") || query.getFilterType().equals("subtree")))
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : Wrong filter type. Neither xpath nor subtree.");
}
});
else if (query.getFilterType().equals("subtree"))
errors.add(new Error() {
{
setTag(ErrorTag.BAD_ATTRIBUTE);
setType(ErrorType.PROTOCOL);
setSeverity(ErrorSeverity.ERROR);
setInfo("<bad-attribute> : Wrong filter type. Not subtree.");
}
});
}
}
reply.setMessageId(query.getMessageId());
if (!insideLogicalRouter) {
reply.setContain(getDataFromFile(fileIPConfiguration));
} else {
reply.setContain(getDataFromFile(fileIPLogicalRouterConfig));
}
} else if (op.equals(Operation.KILL_SESSION)) {
insideLogicalRouter = false;
disconnect();
return;
} else if (op.equals(Operation.CLOSE_SESSION)) {
reply.setMessageId(query.getMessageId());
reply.setOk(true);
insideLogicalRouter = false;
disconnect();
} else if (op.equals(Operation.LOCK)) {
error("LOCK not implemented");
} else if (op.equals(Operation.UNLOCK)) {
error("UNLOCK not implemented");
}
/* include junos capabilities operations */
else if (op.equals(Operation.SET_LOGICAL_ROUTER)) {
reply.setMessageId(query.getMessageId());
reply.setContain("<cli><logical-system>" + query.getIdLogicalRouter() + "</logical-system></cli>");
insideLogicalRouter = true;
}
}
// force to add errors in the response message
if (subsystem.equals("errorServer"))
addErrors(errors);
if (errors.size() > 0)
reply.setErrors(errors);
queue.put(reply);
}
|
diff --git a/main/src/java/chord/analyses/datarace/DataraceAnalysis.java b/main/src/java/chord/analyses/datarace/DataraceAnalysis.java
index f5fe60d4..9f3735a3 100644
--- a/main/src/java/chord/analyses/datarace/DataraceAnalysis.java
+++ b/main/src/java/chord/analyses/datarace/DataraceAnalysis.java
@@ -1,310 +1,313 @@
/*
* Copyright (c) 2008-2009, Intel Corporation.
* Copyright (c) 2006-2007, The Trustees of Stanford University.
* All rights reserved.
*/
package chord.analyses.datarace;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import joeq.Class.jq_Field;
import joeq.Class.jq_Method;
import joeq.Compiler.Quad.Inst;
import joeq.Compiler.Quad.Quad;
import chord.util.ArraySet;
import chord.util.graph.IPathVisitor;
import chord.util.graph.ShortestPathBuilder;
import chord.analyses.alias.ICSCG;
import chord.analyses.alias.Ctxt;
import chord.analyses.alias.Obj;
import chord.analyses.alias.CtxtsAnalysis;
import chord.analyses.alias.CSAliasAnalysis;
import chord.analyses.alias.ThrSenAbbrCSCGAnalysis;
import chord.analyses.alias.DomO;
import chord.analyses.alias.DomC;
import chord.bddbddb.Rel.RelView;
import chord.program.Program;
import chord.analyses.thread.DomA;
import chord.doms.DomL;
import chord.doms.DomE;
import chord.doms.DomF;
import chord.doms.DomH;
import chord.doms.DomI;
import chord.doms.DomM;
import chord.project.Chord;
import chord.project.Project;
import chord.project.Properties;
import chord.project.OutDirUtils;
import chord.project.analyses.JavaAnalysis;
import chord.project.analyses.ProgramDom;
import chord.project.analyses.ProgramRel;
import chord.util.SetUtils;
import chord.util.tuple.object.Hext;
import chord.util.tuple.object.Pair;
import chord.util.tuple.object.Trio;
/**
* Static datarace analysis.
* <p>
* Outputs relation <tt>datarace</tt> containing each tuple
* <tt>(a1,c1,e1,a2,c2,e2)</tt> denoting a possible race between
* abstract threads <tt>a1</tt> and <tt>a2</tt> executing
* accesses <tt>e1</tt> and <tt>e2</tt>, respectively, in
* abstract contexts <tt>c1</tt> and <tt>c2</tt> of their
* containing methods, respectively.
* <p>
* Recognized system properties:
* <ul>
* <li><tt>chord.exclude.escaping</tt> (default is false).</li>
* <li><tt>chord.exclude.parallel</tt> (default is false).</li>
* <li><tt>chord.exclude.nongrded</tt> (default is false).</li>
* <li><tt>chord.publish.results</tt> (default is false).</li>
* <li>All system properties recognized by abstract contexts analysis
* (see {@link chord.analyses.alias.CtxtsAnalysis}).</li>
* </ul>
*
* @author Mayur Naik ([email protected])
*/
@Chord(
name="datarace-java"
)
public class DataraceAnalysis extends JavaAnalysis {
private DomM domM;
private DomI domI;
private DomF domF;
private DomE domE;
private DomA domA;
private DomH domH;
private DomC domC;
private DomL domL;
private CSAliasAnalysis hybridAnalysis;
private ThrSenAbbrCSCGAnalysis thrSenAbbrCSCGAnalysis;
private void init() {
domM = (DomM) Project.getTrgt("M");
domI = (DomI) Project.getTrgt("I");
domF = (DomF) Project.getTrgt("F");
domE = (DomE) Project.getTrgt("E");
domA = (DomA) Project.getTrgt("A");
domH = (DomH) Project.getTrgt("H");
domC = (DomC) Project.getTrgt("C");
domL = (DomL) Project.getTrgt("L");
hybridAnalysis = (CSAliasAnalysis) Project.getTrgt("cs-alias-java");
thrSenAbbrCSCGAnalysis = (ThrSenAbbrCSCGAnalysis)
Project.getTrgt("thrsen-abbr-cscg-java");
}
public void run() {
boolean excludeParallel = Boolean.getBoolean("chord.exclude.parallel");
boolean excludeEscaping = Boolean.getBoolean("chord.exclude.escaping");
boolean excludeNongrded = Boolean.getBoolean("chord.exclude.nongrded");
init();
Project.runTask(CtxtsAnalysis.getCspaKind());
Project.runTask("datarace-prologue-dlog");
if (excludeParallel)
Project.runTask("datarace-parallel-exclude-dlog");
else
Project.runTask("datarace-parallel-include-dlog");
if (excludeEscaping)
Project.runTask("datarace-escaping-exclude-dlog");
else
Project.runTask("datarace-escaping-include-dlog");
if (excludeNongrded)
Project.runTask("datarace-nongrded-exclude-dlog");
else
Project.runTask("datarace-nongrded-include-dlog");
Project.runTask("datarace-dlog");
Project.runTask("datarace-stats-dlog");
if (Properties.publishResults)
publishResults();
}
private void publishResults() {
Project.runTask(hybridAnalysis);
Project.runTask(thrSenAbbrCSCGAnalysis);
final ICSCG thrSenAbbrCSCG = thrSenAbbrCSCGAnalysis.getCallGraph();
Project.runTask("datarace-epilogue-dlog");
final ProgramDom<Trio<Pair<Ctxt, jq_Method>, Ctxt, Quad>> domTCE =
new ProgramDom<Trio<Pair<Ctxt, jq_Method>, Ctxt, Quad>>();
domTCE.setName("TCE");
final DomO domO = new DomO();
domO.setName("O");
PrintWriter out;
out = OutDirUtils.newPrintWriter("dataracelist.xml");
out.println("<dataracelist>");
final ProgramRel relDatarace = (ProgramRel) Project.getTrgt("datarace");
relDatarace.load();
final ProgramRel relRaceCEC = (ProgramRel) Project.getTrgt("raceCEC");
relRaceCEC.load();
final Iterable<Hext<Pair<Ctxt, jq_Method>, Ctxt, Quad,
Pair<Ctxt, jq_Method>, Ctxt, Quad>> tuples = relDatarace.getAry6ValTuples();
for (Hext<Pair<Ctxt, jq_Method>, Ctxt, Quad,
Pair<Ctxt, jq_Method>, Ctxt, Quad> tuple : tuples) {
int tce1 = domTCE.getOrAdd(new Trio<Pair<Ctxt, jq_Method>, Ctxt, Quad>(
tuple.val0, tuple.val1, tuple.val2));
int tce2 = domTCE.getOrAdd(new Trio<Pair<Ctxt, jq_Method>, Ctxt, Quad>(
tuple.val3, tuple.val4, tuple.val5));
RelView view = relRaceCEC.getView();
view.selectAndDelete(0, tuple.val1);
view.selectAndDelete(1, tuple.val2);
view.selectAndDelete(2, tuple.val4);
view.selectAndDelete(3, tuple.val5);
Set<Ctxt> pts = new ArraySet<Ctxt>(view.size());
Iterable<Ctxt> res = view.getAry1ValTuples();
for (Ctxt ctxt : res) {
pts.add(ctxt);
}
view.free();
int p = domO.getOrAdd(new Obj(pts));
jq_Field fld = Program.getField(tuple.val2);
int f = domF.indexOf(fld);
out.println("<datarace Oid=\"O" + p +
"\" Fid=\"F" + f + "\" " +
"TCE1id=\"TCE" + tce1 + "\" " +
"TCE2id=\"TCE" + tce2 + "\"/>");
}
relDatarace.close();
relRaceCEC.close();
out.println("</dataracelist>");
out.close();
+ Project.runTask("LI");
+ Project.runTask("LE");
+ Project.runTask("syncCLC-dlog");
final ProgramRel relLI = (ProgramRel) Project.getTrgt("LI");
final ProgramRel relLE = (ProgramRel) Project.getTrgt("LE");
final ProgramRel relSyncCLC = (ProgramRel) Project.getTrgt("syncCLC");
relLI.load();
relLE.load();
relSyncCLC.load();
final Map<Pair<Ctxt, jq_Method>, ShortestPathBuilder> srcNodeToSPB =
new HashMap<Pair<Ctxt, jq_Method>, ShortestPathBuilder>();
final IPathVisitor<Pair<Ctxt, jq_Method>> visitor =
new IPathVisitor<Pair<Ctxt, jq_Method>>() {
public String visit(Pair<Ctxt, jq_Method> origNode,
Pair<Ctxt, jq_Method> destNode) {
Set<Quad> insts = thrSenAbbrCSCG.getLabels(origNode, destNode);
jq_Method srcM = origNode.val1;
int mIdx = domM.indexOf(srcM);
Ctxt srcC = origNode.val0;
int cIdx = domC.indexOf(srcC);
String lockStr = "";
Quad inst = insts.iterator().next();
int iIdx = domI.indexOf(inst);
RelView view = relLI.getView();
view.selectAndDelete(1, iIdx);
Iterable<Inst> locks = view.getAry1ValTuples();
for (Inst lock : locks) {
int lIdx = domL.indexOf(lock);
RelView view2 = relSyncCLC.getView();
view2.selectAndDelete(0, cIdx);
view2.selectAndDelete(1, lIdx);
Iterable<Ctxt> ctxts = view2.getAry1ValTuples();
Set<Ctxt> pts = SetUtils.newSet(view2.size());
for (Ctxt ctxt : ctxts)
pts.add(ctxt);
int oIdx = domO.getOrAdd(new Obj(pts));
view2.free();
lockStr += "<lock Lid=\"L" + lIdx + "\" Mid=\"M" +
mIdx + "\" Oid=\"O" + oIdx + "\"/>";
}
view.free();
return lockStr + "<elem Cid=\"C" + cIdx + "\" " +
"Iid=\"I" + iIdx + "\"/>";
}
};
out = OutDirUtils.newPrintWriter("TCElist.xml");
out.println("<TCElist>");
for (Trio<Pair<Ctxt, jq_Method>, Ctxt, Quad> tce : domTCE) {
Pair<Ctxt, jq_Method> srcCM = tce.val0;
Ctxt methCtxt = tce.val1;
Quad heapInst = tce.val2;
int cIdx = domC.indexOf(methCtxt);
int eIdx = domE.indexOf(heapInst);
out.println("<TCE id=\"TCE" + domTCE.indexOf(tce) + "\" " +
"Tid=\"A" + domA.indexOf(srcCM) + "\" " +
"Cid=\"C" + cIdx + "\" " +
"Eid=\"E" + eIdx + "\">");
jq_Method dstM = Program.v().getMethod(heapInst);
int mIdx = domM.indexOf(dstM);
RelView view = relLE.getView();
view.selectAndDelete(1, eIdx);
Iterable<Inst> locks = view.getAry1ValTuples();
for (Inst lock : locks) {
int lIdx = domL.indexOf(lock);
RelView view2 = relSyncCLC.getView();
view2.selectAndDelete(0, cIdx);
view2.selectAndDelete(1, lIdx);
Iterable<Ctxt> ctxts = view2.getAry1ValTuples();
Set<Ctxt> pts = SetUtils.newSet(view2.size());
for (Ctxt ctxt : ctxts)
pts.add(ctxt);
int oIdx = domO.getOrAdd(new Obj(pts));
view2.free();
out.println("<lock Lid=\"L" + lIdx + "\" Mid=\"M" +
mIdx + "\" Oid=\"O" + oIdx + "\"/>");
}
view.free();
ShortestPathBuilder spb = srcNodeToSPB.get(srcCM);
if (spb == null) {
spb = new ShortestPathBuilder(thrSenAbbrCSCG, srcCM, visitor);
srcNodeToSPB.put(srcCM, spb);
}
Pair<Ctxt, jq_Method> dstCM =
new Pair<Ctxt, jq_Method>(methCtxt, dstM);
String path = spb.getShortestPathTo(dstCM);
out.println("<path>");
out.println(path);
out.println("</path>");
out.println("</TCE>");
}
out.println("</TCElist>");
out.close();
relLI.close();
relLE.close();
relSyncCLC.close();
domO.saveToXMLFile();
domC.saveToXMLFile();
domA.saveToXMLFile();
domH.saveToXMLFile();
domI.saveToXMLFile();
domM.saveToXMLFile();
domE.saveToXMLFile();
domF.saveToXMLFile();
domL.saveToXMLFile();
OutDirUtils.copyFileFromMainDir("src/web/Olist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/Clist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/Alist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/Hlist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/Ilist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/Mlist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/Elist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/Flist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/Llist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/style.css");
OutDirUtils.copyFileFromMainDir("src/web/misc.xsl");
OutDirUtils.copyFileFromMainDir("src/web/datarace/results.dtd");
OutDirUtils.copyFileFromMainDir("src/web/datarace/results.xml");
OutDirUtils.copyFileFromMainDir("src/web/datarace/group.xsl");
OutDirUtils.copyFileFromMainDir("src/web/datarace/paths.xsl");
OutDirUtils.copyFileFromMainDir("src/web/datarace/races.xsl");
OutDirUtils.runSaxon("results.xml", "group.xsl");
OutDirUtils.runSaxon("results.xml", "paths.xsl");
OutDirUtils.runSaxon("results.xml", "races.xsl");
Program.v().HTMLizeJavaSrcFiles();
}
}
| true | true | private void publishResults() {
Project.runTask(hybridAnalysis);
Project.runTask(thrSenAbbrCSCGAnalysis);
final ICSCG thrSenAbbrCSCG = thrSenAbbrCSCGAnalysis.getCallGraph();
Project.runTask("datarace-epilogue-dlog");
final ProgramDom<Trio<Pair<Ctxt, jq_Method>, Ctxt, Quad>> domTCE =
new ProgramDom<Trio<Pair<Ctxt, jq_Method>, Ctxt, Quad>>();
domTCE.setName("TCE");
final DomO domO = new DomO();
domO.setName("O");
PrintWriter out;
out = OutDirUtils.newPrintWriter("dataracelist.xml");
out.println("<dataracelist>");
final ProgramRel relDatarace = (ProgramRel) Project.getTrgt("datarace");
relDatarace.load();
final ProgramRel relRaceCEC = (ProgramRel) Project.getTrgt("raceCEC");
relRaceCEC.load();
final Iterable<Hext<Pair<Ctxt, jq_Method>, Ctxt, Quad,
Pair<Ctxt, jq_Method>, Ctxt, Quad>> tuples = relDatarace.getAry6ValTuples();
for (Hext<Pair<Ctxt, jq_Method>, Ctxt, Quad,
Pair<Ctxt, jq_Method>, Ctxt, Quad> tuple : tuples) {
int tce1 = domTCE.getOrAdd(new Trio<Pair<Ctxt, jq_Method>, Ctxt, Quad>(
tuple.val0, tuple.val1, tuple.val2));
int tce2 = domTCE.getOrAdd(new Trio<Pair<Ctxt, jq_Method>, Ctxt, Quad>(
tuple.val3, tuple.val4, tuple.val5));
RelView view = relRaceCEC.getView();
view.selectAndDelete(0, tuple.val1);
view.selectAndDelete(1, tuple.val2);
view.selectAndDelete(2, tuple.val4);
view.selectAndDelete(3, tuple.val5);
Set<Ctxt> pts = new ArraySet<Ctxt>(view.size());
Iterable<Ctxt> res = view.getAry1ValTuples();
for (Ctxt ctxt : res) {
pts.add(ctxt);
}
view.free();
int p = domO.getOrAdd(new Obj(pts));
jq_Field fld = Program.getField(tuple.val2);
int f = domF.indexOf(fld);
out.println("<datarace Oid=\"O" + p +
"\" Fid=\"F" + f + "\" " +
"TCE1id=\"TCE" + tce1 + "\" " +
"TCE2id=\"TCE" + tce2 + "\"/>");
}
relDatarace.close();
relRaceCEC.close();
out.println("</dataracelist>");
out.close();
final ProgramRel relLI = (ProgramRel) Project.getTrgt("LI");
final ProgramRel relLE = (ProgramRel) Project.getTrgt("LE");
final ProgramRel relSyncCLC = (ProgramRel) Project.getTrgt("syncCLC");
relLI.load();
relLE.load();
relSyncCLC.load();
final Map<Pair<Ctxt, jq_Method>, ShortestPathBuilder> srcNodeToSPB =
new HashMap<Pair<Ctxt, jq_Method>, ShortestPathBuilder>();
final IPathVisitor<Pair<Ctxt, jq_Method>> visitor =
new IPathVisitor<Pair<Ctxt, jq_Method>>() {
public String visit(Pair<Ctxt, jq_Method> origNode,
Pair<Ctxt, jq_Method> destNode) {
Set<Quad> insts = thrSenAbbrCSCG.getLabels(origNode, destNode);
jq_Method srcM = origNode.val1;
int mIdx = domM.indexOf(srcM);
Ctxt srcC = origNode.val0;
int cIdx = domC.indexOf(srcC);
String lockStr = "";
Quad inst = insts.iterator().next();
int iIdx = domI.indexOf(inst);
RelView view = relLI.getView();
view.selectAndDelete(1, iIdx);
Iterable<Inst> locks = view.getAry1ValTuples();
for (Inst lock : locks) {
int lIdx = domL.indexOf(lock);
RelView view2 = relSyncCLC.getView();
view2.selectAndDelete(0, cIdx);
view2.selectAndDelete(1, lIdx);
Iterable<Ctxt> ctxts = view2.getAry1ValTuples();
Set<Ctxt> pts = SetUtils.newSet(view2.size());
for (Ctxt ctxt : ctxts)
pts.add(ctxt);
int oIdx = domO.getOrAdd(new Obj(pts));
view2.free();
lockStr += "<lock Lid=\"L" + lIdx + "\" Mid=\"M" +
mIdx + "\" Oid=\"O" + oIdx + "\"/>";
}
view.free();
return lockStr + "<elem Cid=\"C" + cIdx + "\" " +
"Iid=\"I" + iIdx + "\"/>";
}
};
out = OutDirUtils.newPrintWriter("TCElist.xml");
out.println("<TCElist>");
for (Trio<Pair<Ctxt, jq_Method>, Ctxt, Quad> tce : domTCE) {
Pair<Ctxt, jq_Method> srcCM = tce.val0;
Ctxt methCtxt = tce.val1;
Quad heapInst = tce.val2;
int cIdx = domC.indexOf(methCtxt);
int eIdx = domE.indexOf(heapInst);
out.println("<TCE id=\"TCE" + domTCE.indexOf(tce) + "\" " +
"Tid=\"A" + domA.indexOf(srcCM) + "\" " +
"Cid=\"C" + cIdx + "\" " +
"Eid=\"E" + eIdx + "\">");
jq_Method dstM = Program.v().getMethod(heapInst);
int mIdx = domM.indexOf(dstM);
RelView view = relLE.getView();
view.selectAndDelete(1, eIdx);
Iterable<Inst> locks = view.getAry1ValTuples();
for (Inst lock : locks) {
int lIdx = domL.indexOf(lock);
RelView view2 = relSyncCLC.getView();
view2.selectAndDelete(0, cIdx);
view2.selectAndDelete(1, lIdx);
Iterable<Ctxt> ctxts = view2.getAry1ValTuples();
Set<Ctxt> pts = SetUtils.newSet(view2.size());
for (Ctxt ctxt : ctxts)
pts.add(ctxt);
int oIdx = domO.getOrAdd(new Obj(pts));
view2.free();
out.println("<lock Lid=\"L" + lIdx + "\" Mid=\"M" +
mIdx + "\" Oid=\"O" + oIdx + "\"/>");
}
view.free();
ShortestPathBuilder spb = srcNodeToSPB.get(srcCM);
if (spb == null) {
spb = new ShortestPathBuilder(thrSenAbbrCSCG, srcCM, visitor);
srcNodeToSPB.put(srcCM, spb);
}
Pair<Ctxt, jq_Method> dstCM =
new Pair<Ctxt, jq_Method>(methCtxt, dstM);
String path = spb.getShortestPathTo(dstCM);
out.println("<path>");
out.println(path);
out.println("</path>");
out.println("</TCE>");
}
out.println("</TCElist>");
out.close();
relLI.close();
relLE.close();
relSyncCLC.close();
domO.saveToXMLFile();
domC.saveToXMLFile();
domA.saveToXMLFile();
domH.saveToXMLFile();
domI.saveToXMLFile();
domM.saveToXMLFile();
domE.saveToXMLFile();
domF.saveToXMLFile();
domL.saveToXMLFile();
OutDirUtils.copyFileFromMainDir("src/web/Olist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/Clist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/Alist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/Hlist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/Ilist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/Mlist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/Elist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/Flist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/Llist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/style.css");
OutDirUtils.copyFileFromMainDir("src/web/misc.xsl");
OutDirUtils.copyFileFromMainDir("src/web/datarace/results.dtd");
OutDirUtils.copyFileFromMainDir("src/web/datarace/results.xml");
OutDirUtils.copyFileFromMainDir("src/web/datarace/group.xsl");
OutDirUtils.copyFileFromMainDir("src/web/datarace/paths.xsl");
OutDirUtils.copyFileFromMainDir("src/web/datarace/races.xsl");
OutDirUtils.runSaxon("results.xml", "group.xsl");
OutDirUtils.runSaxon("results.xml", "paths.xsl");
OutDirUtils.runSaxon("results.xml", "races.xsl");
Program.v().HTMLizeJavaSrcFiles();
}
| private void publishResults() {
Project.runTask(hybridAnalysis);
Project.runTask(thrSenAbbrCSCGAnalysis);
final ICSCG thrSenAbbrCSCG = thrSenAbbrCSCGAnalysis.getCallGraph();
Project.runTask("datarace-epilogue-dlog");
final ProgramDom<Trio<Pair<Ctxt, jq_Method>, Ctxt, Quad>> domTCE =
new ProgramDom<Trio<Pair<Ctxt, jq_Method>, Ctxt, Quad>>();
domTCE.setName("TCE");
final DomO domO = new DomO();
domO.setName("O");
PrintWriter out;
out = OutDirUtils.newPrintWriter("dataracelist.xml");
out.println("<dataracelist>");
final ProgramRel relDatarace = (ProgramRel) Project.getTrgt("datarace");
relDatarace.load();
final ProgramRel relRaceCEC = (ProgramRel) Project.getTrgt("raceCEC");
relRaceCEC.load();
final Iterable<Hext<Pair<Ctxt, jq_Method>, Ctxt, Quad,
Pair<Ctxt, jq_Method>, Ctxt, Quad>> tuples = relDatarace.getAry6ValTuples();
for (Hext<Pair<Ctxt, jq_Method>, Ctxt, Quad,
Pair<Ctxt, jq_Method>, Ctxt, Quad> tuple : tuples) {
int tce1 = domTCE.getOrAdd(new Trio<Pair<Ctxt, jq_Method>, Ctxt, Quad>(
tuple.val0, tuple.val1, tuple.val2));
int tce2 = domTCE.getOrAdd(new Trio<Pair<Ctxt, jq_Method>, Ctxt, Quad>(
tuple.val3, tuple.val4, tuple.val5));
RelView view = relRaceCEC.getView();
view.selectAndDelete(0, tuple.val1);
view.selectAndDelete(1, tuple.val2);
view.selectAndDelete(2, tuple.val4);
view.selectAndDelete(3, tuple.val5);
Set<Ctxt> pts = new ArraySet<Ctxt>(view.size());
Iterable<Ctxt> res = view.getAry1ValTuples();
for (Ctxt ctxt : res) {
pts.add(ctxt);
}
view.free();
int p = domO.getOrAdd(new Obj(pts));
jq_Field fld = Program.getField(tuple.val2);
int f = domF.indexOf(fld);
out.println("<datarace Oid=\"O" + p +
"\" Fid=\"F" + f + "\" " +
"TCE1id=\"TCE" + tce1 + "\" " +
"TCE2id=\"TCE" + tce2 + "\"/>");
}
relDatarace.close();
relRaceCEC.close();
out.println("</dataracelist>");
out.close();
Project.runTask("LI");
Project.runTask("LE");
Project.runTask("syncCLC-dlog");
final ProgramRel relLI = (ProgramRel) Project.getTrgt("LI");
final ProgramRel relLE = (ProgramRel) Project.getTrgt("LE");
final ProgramRel relSyncCLC = (ProgramRel) Project.getTrgt("syncCLC");
relLI.load();
relLE.load();
relSyncCLC.load();
final Map<Pair<Ctxt, jq_Method>, ShortestPathBuilder> srcNodeToSPB =
new HashMap<Pair<Ctxt, jq_Method>, ShortestPathBuilder>();
final IPathVisitor<Pair<Ctxt, jq_Method>> visitor =
new IPathVisitor<Pair<Ctxt, jq_Method>>() {
public String visit(Pair<Ctxt, jq_Method> origNode,
Pair<Ctxt, jq_Method> destNode) {
Set<Quad> insts = thrSenAbbrCSCG.getLabels(origNode, destNode);
jq_Method srcM = origNode.val1;
int mIdx = domM.indexOf(srcM);
Ctxt srcC = origNode.val0;
int cIdx = domC.indexOf(srcC);
String lockStr = "";
Quad inst = insts.iterator().next();
int iIdx = domI.indexOf(inst);
RelView view = relLI.getView();
view.selectAndDelete(1, iIdx);
Iterable<Inst> locks = view.getAry1ValTuples();
for (Inst lock : locks) {
int lIdx = domL.indexOf(lock);
RelView view2 = relSyncCLC.getView();
view2.selectAndDelete(0, cIdx);
view2.selectAndDelete(1, lIdx);
Iterable<Ctxt> ctxts = view2.getAry1ValTuples();
Set<Ctxt> pts = SetUtils.newSet(view2.size());
for (Ctxt ctxt : ctxts)
pts.add(ctxt);
int oIdx = domO.getOrAdd(new Obj(pts));
view2.free();
lockStr += "<lock Lid=\"L" + lIdx + "\" Mid=\"M" +
mIdx + "\" Oid=\"O" + oIdx + "\"/>";
}
view.free();
return lockStr + "<elem Cid=\"C" + cIdx + "\" " +
"Iid=\"I" + iIdx + "\"/>";
}
};
out = OutDirUtils.newPrintWriter("TCElist.xml");
out.println("<TCElist>");
for (Trio<Pair<Ctxt, jq_Method>, Ctxt, Quad> tce : domTCE) {
Pair<Ctxt, jq_Method> srcCM = tce.val0;
Ctxt methCtxt = tce.val1;
Quad heapInst = tce.val2;
int cIdx = domC.indexOf(methCtxt);
int eIdx = domE.indexOf(heapInst);
out.println("<TCE id=\"TCE" + domTCE.indexOf(tce) + "\" " +
"Tid=\"A" + domA.indexOf(srcCM) + "\" " +
"Cid=\"C" + cIdx + "\" " +
"Eid=\"E" + eIdx + "\">");
jq_Method dstM = Program.v().getMethod(heapInst);
int mIdx = domM.indexOf(dstM);
RelView view = relLE.getView();
view.selectAndDelete(1, eIdx);
Iterable<Inst> locks = view.getAry1ValTuples();
for (Inst lock : locks) {
int lIdx = domL.indexOf(lock);
RelView view2 = relSyncCLC.getView();
view2.selectAndDelete(0, cIdx);
view2.selectAndDelete(1, lIdx);
Iterable<Ctxt> ctxts = view2.getAry1ValTuples();
Set<Ctxt> pts = SetUtils.newSet(view2.size());
for (Ctxt ctxt : ctxts)
pts.add(ctxt);
int oIdx = domO.getOrAdd(new Obj(pts));
view2.free();
out.println("<lock Lid=\"L" + lIdx + "\" Mid=\"M" +
mIdx + "\" Oid=\"O" + oIdx + "\"/>");
}
view.free();
ShortestPathBuilder spb = srcNodeToSPB.get(srcCM);
if (spb == null) {
spb = new ShortestPathBuilder(thrSenAbbrCSCG, srcCM, visitor);
srcNodeToSPB.put(srcCM, spb);
}
Pair<Ctxt, jq_Method> dstCM =
new Pair<Ctxt, jq_Method>(methCtxt, dstM);
String path = spb.getShortestPathTo(dstCM);
out.println("<path>");
out.println(path);
out.println("</path>");
out.println("</TCE>");
}
out.println("</TCElist>");
out.close();
relLI.close();
relLE.close();
relSyncCLC.close();
domO.saveToXMLFile();
domC.saveToXMLFile();
domA.saveToXMLFile();
domH.saveToXMLFile();
domI.saveToXMLFile();
domM.saveToXMLFile();
domE.saveToXMLFile();
domF.saveToXMLFile();
domL.saveToXMLFile();
OutDirUtils.copyFileFromMainDir("src/web/Olist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/Clist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/Alist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/Hlist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/Ilist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/Mlist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/Elist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/Flist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/Llist.dtd");
OutDirUtils.copyFileFromMainDir("src/web/style.css");
OutDirUtils.copyFileFromMainDir("src/web/misc.xsl");
OutDirUtils.copyFileFromMainDir("src/web/datarace/results.dtd");
OutDirUtils.copyFileFromMainDir("src/web/datarace/results.xml");
OutDirUtils.copyFileFromMainDir("src/web/datarace/group.xsl");
OutDirUtils.copyFileFromMainDir("src/web/datarace/paths.xsl");
OutDirUtils.copyFileFromMainDir("src/web/datarace/races.xsl");
OutDirUtils.runSaxon("results.xml", "group.xsl");
OutDirUtils.runSaxon("results.xml", "paths.xsl");
OutDirUtils.runSaxon("results.xml", "races.xsl");
Program.v().HTMLizeJavaSrcFiles();
}
|
diff --git a/uk.ac.gda.epics/src/gda/device/scannable/PIE725ConstantVelocityRasterScannable.java b/uk.ac.gda.epics/src/gda/device/scannable/PIE725ConstantVelocityRasterScannable.java
index 235111ff..d2dd8d55 100644
--- a/uk.ac.gda.epics/src/gda/device/scannable/PIE725ConstantVelocityRasterScannable.java
+++ b/uk.ac.gda.epics/src/gda/device/scannable/PIE725ConstantVelocityRasterScannable.java
@@ -1,379 +1,379 @@
/*-
* Copyright © 2014 Diamond Light Source Ltd.
*
* This file is part of GDA.
*
* GDA is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 3 as published by the Free
* Software Foundation.
*
* GDA 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 GDA. If not, see <http://www.gnu.org/licenses/>.
*/
package gda.device.scannable;
import gda.device.DeviceBase;
import gda.device.DeviceException;
import gda.device.continuouscontroller.ConstantVelocityRasterMoveController;
import gda.device.scannable.scannablegroup.ScannableMotionWithScannableFieldsBase;
import gda.epics.LazyPVFactory;
import gda.epics.PV;
import gda.epics.PVWithSeparateReadback;
import gda.factory.FactoryException;
import gda.jython.JythonServerFacade;
import gda.scan.ConstantVelocityRasterScan;
import java.io.IOException;
import java.text.MessageFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A Scannable suitable for use in {@link ConstantVelocityRasterScan}s inorder to control a PIE725 2d piezo controller.
* <p>
* WFrom Jython two fields will be made, name.nameX and name.nameY which represent the x and y dimensions of stage
* respectively. Us e.g.:
* <p>
* ConstantVelocityRasterScan([name.nameY, s, s, s, name.nameX, s, s, s, deta, time ...])
*/
public class PIE725ConstantVelocityRasterScannable extends ScannableMotionWithScannableFieldsBase implements
ContinuouslyScannableViaController {
private static final Logger logger = LoggerFactory.getLogger(PIE725ConstantVelocityRasterScannable.class);
protected PVWithSeparateReadback<Double> pvXpair;
protected PVWithSeparateReadback<Double> pvYpair;
private Double[] lastRasterTarget = new Double[2];
/**
* @param name
* @param pvName
* e.g. BL16I-EA-PIEZO-01:C1:
*/
public PIE725ConstantVelocityRasterScannable(String name, String pvName) {
setName(name);
setInputNames(new String[] { name + 'X', name + 'Y' });
setExtraNames(new String[] {});
setOutputFormat(new String[] { "%.4f", "%.4f" });
pvXpair = new PVWithSeparateReadback<Double>(LazyPVFactory.newDoublePV(pvName + "X:MOV:WR"),
LazyPVFactory.newReadOnlyDoublePV(pvName + "X:POS:RD"));
pvYpair = new PVWithSeparateReadback<Double>(LazyPVFactory.newDoublePV(pvName + "Y:MOV:WR"),
LazyPVFactory.newReadOnlyDoublePV(pvName + "Y:POS:RD"));
setContinuousMoveController(new PIE725ConstantVelocityRasterMoveController(pvName));
}
@Override
public void rawAsynchronousMoveTo(Object position) throws gda.device.DeviceException {
Double[] xytarget = PositionConvertorFunctions.toDoubleArray(position);
if (xytarget.length != 2) {
throw new AssertionError("Target position must have 2 fields, not " + xytarget.length);
}
if (isOperatingContinously()) {
// Record position for the subsequent getPosition() call
if (xytarget[0] != null) {
lastRasterTarget[0] = xytarget[0];
}
if (xytarget[1] != null) {
lastRasterTarget[1] = xytarget[1];
}
} else {
try {
if (xytarget[0] != null) {
pvXpair.putWait(xytarget[0]);
}
if (xytarget[1] != null) {
pvYpair.putWait(xytarget[1]);
}
} catch (IOException e) {
throw new DeviceException(e);
}
}
}
@Override
public Object rawGetPosition() throws DeviceException {
if (isOperatingContinously()) {
if (lastRasterTarget == null) {
throw new NullPointerException("lastRasterTargetNotSet ");
}
return lastRasterTarget;
} // else
try {
return new Double[] { pvXpair.get(), pvYpair.get() };
} catch (IOException e) {
throw new DeviceException(e);
}
}
@Override
public boolean isBusy() throws DeviceException {
// when operating continuously this needs to return false. When not operating continuously, then
// we will have blocked in asynchMoveto already.
return false;
}
@Override
public void stop() throws DeviceException {
try {
getContinuousMoveController().stopAndReset();
} catch (InterruptedException e) {
throw new DeviceException(e);
}
}
@Override
public void atCommandFailure() throws DeviceException {
stop();
}
class PIE725ConstantVelocityRasterMoveController extends DeviceBase implements ConstantVelocityRasterMoveController {
private PV<Boolean> sendStartCommandPv;
private PV<Boolean> sendStopCommandPv;
private PV<Boolean> sendWaveformSetupCommand;
private PV<String> startCommandStringPv;
private PV<String> stopCommandStringPv;
private PV<String> waveformSetupCommandString;
private boolean hasBeenStarted = false;
private double xmin;
private double xmax;
private double xstep;
private double ymin;
private double ymax;
private double ystep;
private double periodS;
public PIE725ConstantVelocityRasterMoveController(String pvName) {
sendStartCommandPv = LazyPVFactory.newBooleanFromEnumPV(pvName + "WFSTART:GO");
sendStopCommandPv = LazyPVFactory.newBooleanFromEnumPV(pvName + "WFSTOP:GO");
sendWaveformSetupCommand = LazyPVFactory.newBooleanFromEnumPV(pvName + "WFSETUP:GO");
startCommandStringPv = LazyPVFactory.newStringFromWaveformPV(pvName + "WFSTART:WR");
stopCommandStringPv = LazyPVFactory.newStringFromWaveformPV(pvName + "WFSTOP:WR");
waveformSetupCommandString = LazyPVFactory.newStringFromWaveformPV(pvName + "WFSETUP:WR");
}
@Override
public String getName() {
return "pie725_controller";
}
@Override
public void setTriggerPeriod(double seconds) throws DeviceException {
periodS = seconds;
log(".setTriggerPeriod(" + seconds + ")");
}
@Override
public void setStart(double startExternal) throws DeviceException {
xmin = toInternalX(startExternal);
}
@Override
public void setEnd(double endExternal) throws DeviceException {
xmax = toInternalX(endExternal);
}
@Override
public void setStep(double step) throws DeviceException {
assertAgainstForScalingOrUnitChange();
this.xstep = step;
}
@Override
public void setOuterStart(double startExternal) throws DeviceException {
ymin = toInternalY(startExternal);
}
@Override
public void setOuterEnd(double endExternal) throws DeviceException {
ymax = toInternalY(endExternal);
}
@Override
public void setOuterStep(double step) throws DeviceException {
assertAgainstForScalingOrUnitChange();
ystep = step;
}
@Override
public void prepareForMove() throws DeviceException, InterruptedException {
double cols = ScannableUtils.getNumberSteps(xmin, xmax, xstep) + 1;
double rows = ScannableUtils.getNumberSteps(ymin, ymax, ystep) + 1;
double rate = 1 / periodS;
JythonServerFacade jsf = JythonServerFacade.getInstance();
String instantiateRasterGenerator = MessageFormat.format(
- "RasterGenerator(rate={0} , xmin={1}, xmax={2}, ymin={3}, ymax={4}, rows={5}, cols={6})",
+ "RasterGenerator(_rate={0} , _xmin={1}, _xmax={2}, _ymin={3}, _ymax={4}, _rows={5}, _cols={6})",
rate, xmin, xmax, ymin, ymax, rows, cols);
// TODO: create constant for epics_scripts.device.scannable.pie725.generateRaster
jsf.exec(logAndReturn("from epics_scripts.device.scannable.pie725.generateRaster import RasterGenerator"));
jsf.exec(logAndReturn("_rg = " + instantiateRasterGenerator));
jsf.exec(logAndReturn("_rg.createCommands()"));
String startCommand = jsf.eval(logAndReturn("_rg.startCmd")).toString();
logger.info(startCommand);
String stopCommand = jsf.eval(logAndReturn("_rg.stopCmd")).toString();
logger.info(stopCommand);
String waveformSetupCommand = jsf.eval(logAndReturn("_rg.commands")).toString();
logger.info(waveformSetupCommand);
try {
logger.info("putting string commands");
startCommandStringPv.putWait(startCommand);
// Thread.sleep(1);
stopCommandStringPv.putWait(stopCommand);
// Thread.sleep(1);
waveformSetupCommandString.putWait(waveformSetupCommand);
// Thread.sleep(1);
logger.info("sending waveform string commands to controller");
sendWaveformSetupCommand.putWait(true);
// Thread.sleep(1);
logger.info("complete");
} catch (IOException e) {
throw new DeviceException(e);
}
}
private String logAndReturn(String cmd) {
logger.info(">>> " + cmd);
return cmd;
}
@Override
public void startMove() throws DeviceException {
log(".startMove()");
hasBeenStarted = true;
try {
sendStartCommandPv.putWait(true);
} catch (IOException e) {
throw new DeviceException(e);
}
log(".startMove() complete");
}
@Override
public boolean isMoving() throws DeviceException {
log(".isMoving() *Just returning false as EPICS gives no feedback*");
if (Thread.interrupted())
throw new DeviceException("Thread interrupted during isMoving()");
if (hasBeenStarted) {
try {
Thread.sleep(1000); // Bodge!
} catch (InterruptedException e) {
throw new DeviceException(e);
}
}
return false;
}
@Override
public void waitWhileMoving() throws DeviceException, InterruptedException {
if (hasBeenStarted) {
log(".waitWhileMoving() *Just sleeping 1s as EPICS gives no feedback*");
Thread.sleep(1000);
}
}
@Override
public void stopAndReset() throws DeviceException, InterruptedException {
log(".stopAndReset()");
hasBeenStarted = false;
try {
sendStopCommandPv.putWait(true);
} catch (IOException e) {
throw new DeviceException(e);
}
log(".stopAndReset() complete");
}
// //
@Override
public int getNumberTriggers() {
throw new AssertionError("Assumed unused");
}
@Override
public double getTotalTime() throws DeviceException {
throw new AssertionError("Assumed unused");
}
private void log(String msg) {
logger.info(getName() + msg);
}
@Override
public void configure() throws FactoryException {
// do nothing
}
private double toInternalY(double startExternal) {
// outer is y in [y, x]
Double[] paddedInternal = (Double[]) externalToInternal(new Double[] { startExternal, null });
return paddedInternal[0];
}
private double toInternalX(double endExternal) {
// inner is x in [y, x]
Double[] paddedInternal = (Double[]) externalToInternal(new Double[] { null, endExternal });
return paddedInternal[1];
}
private void assertAgainstForScalingOrUnitChange() throws AssertionError {
if (isNonNullOrZero(getScalingFactor())) {
throw new AssertionError("Scaling factor not supported");
}
}
private boolean isNonNullOrZero(Double[] a) {
if (a == null) {
return false;
}
for (int i = 0; i < a.length; i++) {
if (a[i] != 0) {
return true;
}
}
return false;
}
}
}
| true | true | public void prepareForMove() throws DeviceException, InterruptedException {
double cols = ScannableUtils.getNumberSteps(xmin, xmax, xstep) + 1;
double rows = ScannableUtils.getNumberSteps(ymin, ymax, ystep) + 1;
double rate = 1 / periodS;
JythonServerFacade jsf = JythonServerFacade.getInstance();
String instantiateRasterGenerator = MessageFormat.format(
"RasterGenerator(rate={0} , xmin={1}, xmax={2}, ymin={3}, ymax={4}, rows={5}, cols={6})",
rate, xmin, xmax, ymin, ymax, rows, cols);
// TODO: create constant for epics_scripts.device.scannable.pie725.generateRaster
jsf.exec(logAndReturn("from epics_scripts.device.scannable.pie725.generateRaster import RasterGenerator"));
jsf.exec(logAndReturn("_rg = " + instantiateRasterGenerator));
jsf.exec(logAndReturn("_rg.createCommands()"));
String startCommand = jsf.eval(logAndReturn("_rg.startCmd")).toString();
logger.info(startCommand);
String stopCommand = jsf.eval(logAndReturn("_rg.stopCmd")).toString();
logger.info(stopCommand);
String waveformSetupCommand = jsf.eval(logAndReturn("_rg.commands")).toString();
logger.info(waveformSetupCommand);
try {
logger.info("putting string commands");
startCommandStringPv.putWait(startCommand);
// Thread.sleep(1);
stopCommandStringPv.putWait(stopCommand);
// Thread.sleep(1);
waveformSetupCommandString.putWait(waveformSetupCommand);
// Thread.sleep(1);
logger.info("sending waveform string commands to controller");
sendWaveformSetupCommand.putWait(true);
// Thread.sleep(1);
logger.info("complete");
} catch (IOException e) {
throw new DeviceException(e);
}
}
| public void prepareForMove() throws DeviceException, InterruptedException {
double cols = ScannableUtils.getNumberSteps(xmin, xmax, xstep) + 1;
double rows = ScannableUtils.getNumberSteps(ymin, ymax, ystep) + 1;
double rate = 1 / periodS;
JythonServerFacade jsf = JythonServerFacade.getInstance();
String instantiateRasterGenerator = MessageFormat.format(
"RasterGenerator(_rate={0} , _xmin={1}, _xmax={2}, _ymin={3}, _ymax={4}, _rows={5}, _cols={6})",
rate, xmin, xmax, ymin, ymax, rows, cols);
// TODO: create constant for epics_scripts.device.scannable.pie725.generateRaster
jsf.exec(logAndReturn("from epics_scripts.device.scannable.pie725.generateRaster import RasterGenerator"));
jsf.exec(logAndReturn("_rg = " + instantiateRasterGenerator));
jsf.exec(logAndReturn("_rg.createCommands()"));
String startCommand = jsf.eval(logAndReturn("_rg.startCmd")).toString();
logger.info(startCommand);
String stopCommand = jsf.eval(logAndReturn("_rg.stopCmd")).toString();
logger.info(stopCommand);
String waveformSetupCommand = jsf.eval(logAndReturn("_rg.commands")).toString();
logger.info(waveformSetupCommand);
try {
logger.info("putting string commands");
startCommandStringPv.putWait(startCommand);
// Thread.sleep(1);
stopCommandStringPv.putWait(stopCommand);
// Thread.sleep(1);
waveformSetupCommandString.putWait(waveformSetupCommand);
// Thread.sleep(1);
logger.info("sending waveform string commands to controller");
sendWaveformSetupCommand.putWait(true);
// Thread.sleep(1);
logger.info("complete");
} catch (IOException e) {
throw new DeviceException(e);
}
}
|
diff --git a/src/main/java/org/makersoft/shards/utils/ParameterUtil.java b/src/main/java/org/makersoft/shards/utils/ParameterUtil.java
index b0ef7d3..9c196ab 100644
--- a/src/main/java/org/makersoft/shards/utils/ParameterUtil.java
+++ b/src/main/java/org/makersoft/shards/utils/ParameterUtil.java
@@ -1,243 +1,244 @@
/*
* @(#)ParameterUtil.java 2012-8-1 下午10:00:00
*
* Copyright (c) 2011-2012 Makersoft.org all rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
*
*/
package org.makersoft.shards.utils;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.apache.commons.beanutils.PropertyUtils;
import org.makersoft.shards.ShardId;
import org.makersoft.shards.annotation.PrimaryKey;
/**
* 参数处理类
*/
public abstract class ParameterUtil {
private ParameterUtil() {
}
/**
* 参数解析
*
* @param obj
* @param shardId
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static Object resolve(final Object obj, final ShardId shardId) {
try {
// 基本类型
if (obj instanceof String || obj instanceof Number
|| obj instanceof Boolean || obj instanceof Character) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(HashMap.class);
enhancer.setCallback(new MethodInterceptor() {
private final String prefix = shardId.getPrefix();
private final String suffix = shardId.getSuffix();
private final Object parameter = obj;
@Override
public Object intercept(Object object, Method method,
Object[] args, MethodProxy proxy) throws Throwable {
if("containsKey".equals(method.getName())){
//对所有关于Map中containsKey的调用均返回TRUE
return true;
}
if (args.length > 0 && "get".equals(method.getName())) {
if ("prefix".equals(args[0])) {
return prefix;
} else if ("suffix".equals(args[0])) {
return suffix;
} else {
return parameter;
}
}
return proxy.invokeSuper(object, args);
}
});
return (HashMap) enhancer.create();
} else if (obj instanceof Map) {
Map parameter = (Map) obj;
parameter.put("prefix", shardId.getPrefix());
parameter.put("suffix", shardId.getSuffix());
return parameter;
} else if (obj instanceof List) {
Map<String, Object> parameter = Maps.newHashMap();
parameter.put("list", obj);
parameter.put("prefix", shardId.getPrefix());
parameter.put("suffix", shardId.getSuffix());
return parameter;
} else if (obj != null && obj.getClass().isArray()) {
Map<String, Object> parameter = Maps.newHashMap();
parameter.put("array", obj);
parameter.put("prefix", shardId.getPrefix());
parameter.put("suffix", shardId.getSuffix());
+ return parameter;
} else if (obj instanceof Object) {
Map<String, Object> parameter = PropertyUtils.describe(obj);
parameter.put("prefix", shardId.getPrefix());
parameter.put("suffix", shardId.getSuffix());
return parameter;
} else if (obj != null) {
throw new UnsupportedOperationException(String.format(
"The parameter of type {%s} is not supported.",
obj.getClass()));
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return null;
}
public static Serializable extractPrimaryKey(Object object) {
if (object != null) {
Class<?> clazz = object.getClass();
Field[] first = clazz.getDeclaredFields();
Field[] second = clazz.getSuperclass().getDeclaredFields();
Field[] fields = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, fields, first.length, second.length);
for (Field field : fields) {
field.setAccessible(true);
PrimaryKey primaryKey = field.getAnnotation(PrimaryKey.class);
if (primaryKey != null) {
try {
//去除0的情况
Object result = field.get(object);
if(result != null && "0".equals(result.toString())){
return null;
}
return (Serializable) result;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return null;
}
public static Object generatePrimaryKey(Object object, Serializable id) {
if (object != null) {
Assert.notNull(id, "generated id can not be null.");
Class<?> clazz = object.getClass();
Field[] first = clazz.getDeclaredFields();
Field[] second = clazz.getSuperclass().getDeclaredFields();
Field[] fields = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, fields, first.length, second.length);
for (Field field : fields) {
field.setAccessible(true);
PrimaryKey primaryKey = field.getAnnotation(PrimaryKey.class);
if (primaryKey != null) {
try {
//set id
field.set(object, id);
return object;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return null;
}
public static boolean isNumberic(Type type){
String typeName = type.toString();
if ("long".equalsIgnoreCase(typeName)
|| "java.lang.Long".equals(typeName)
|| "int".equalsIgnoreCase(typeName)
|| "java.lang.Integer".equals(typeName)) {
return true;
}
return false;
}
public static boolean isPrimitiveParameter(Object obj){
if(obj instanceof String || obj instanceof Number){
return true;
}
return false;
}
public static void main(String[] args) {
// Test test = new Test();
// test.setId(111L);
// test.setName("test");
// System.out.println(extractPrimaryKey(test));
long i = 0;
Long j = 1L;
int k = 2;
Integer m = 3;
String string = "ssss";
System.out.println(isPrimitiveParameter(i));
System.out.println(isPrimitiveParameter(j));
System.out.println(isPrimitiveParameter(k));
System.out.println(isPrimitiveParameter(m));
System.out.println(isPrimitiveParameter(string));
}
static class Test{
@PrimaryKey
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
| true | true | public static Object resolve(final Object obj, final ShardId shardId) {
try {
// 基本类型
if (obj instanceof String || obj instanceof Number
|| obj instanceof Boolean || obj instanceof Character) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(HashMap.class);
enhancer.setCallback(new MethodInterceptor() {
private final String prefix = shardId.getPrefix();
private final String suffix = shardId.getSuffix();
private final Object parameter = obj;
@Override
public Object intercept(Object object, Method method,
Object[] args, MethodProxy proxy) throws Throwable {
if("containsKey".equals(method.getName())){
//对所有关于Map中containsKey的调用均返回TRUE
return true;
}
if (args.length > 0 && "get".equals(method.getName())) {
if ("prefix".equals(args[0])) {
return prefix;
} else if ("suffix".equals(args[0])) {
return suffix;
} else {
return parameter;
}
}
return proxy.invokeSuper(object, args);
}
});
return (HashMap) enhancer.create();
} else if (obj instanceof Map) {
Map parameter = (Map) obj;
parameter.put("prefix", shardId.getPrefix());
parameter.put("suffix", shardId.getSuffix());
return parameter;
} else if (obj instanceof List) {
Map<String, Object> parameter = Maps.newHashMap();
parameter.put("list", obj);
parameter.put("prefix", shardId.getPrefix());
parameter.put("suffix", shardId.getSuffix());
return parameter;
} else if (obj != null && obj.getClass().isArray()) {
Map<String, Object> parameter = Maps.newHashMap();
parameter.put("array", obj);
parameter.put("prefix", shardId.getPrefix());
parameter.put("suffix", shardId.getSuffix());
} else if (obj instanceof Object) {
Map<String, Object> parameter = PropertyUtils.describe(obj);
parameter.put("prefix", shardId.getPrefix());
parameter.put("suffix", shardId.getSuffix());
return parameter;
} else if (obj != null) {
throw new UnsupportedOperationException(String.format(
"The parameter of type {%s} is not supported.",
obj.getClass()));
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return null;
}
| public static Object resolve(final Object obj, final ShardId shardId) {
try {
// 基本类型
if (obj instanceof String || obj instanceof Number
|| obj instanceof Boolean || obj instanceof Character) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(HashMap.class);
enhancer.setCallback(new MethodInterceptor() {
private final String prefix = shardId.getPrefix();
private final String suffix = shardId.getSuffix();
private final Object parameter = obj;
@Override
public Object intercept(Object object, Method method,
Object[] args, MethodProxy proxy) throws Throwable {
if("containsKey".equals(method.getName())){
//对所有关于Map中containsKey的调用均返回TRUE
return true;
}
if (args.length > 0 && "get".equals(method.getName())) {
if ("prefix".equals(args[0])) {
return prefix;
} else if ("suffix".equals(args[0])) {
return suffix;
} else {
return parameter;
}
}
return proxy.invokeSuper(object, args);
}
});
return (HashMap) enhancer.create();
} else if (obj instanceof Map) {
Map parameter = (Map) obj;
parameter.put("prefix", shardId.getPrefix());
parameter.put("suffix", shardId.getSuffix());
return parameter;
} else if (obj instanceof List) {
Map<String, Object> parameter = Maps.newHashMap();
parameter.put("list", obj);
parameter.put("prefix", shardId.getPrefix());
parameter.put("suffix", shardId.getSuffix());
return parameter;
} else if (obj != null && obj.getClass().isArray()) {
Map<String, Object> parameter = Maps.newHashMap();
parameter.put("array", obj);
parameter.put("prefix", shardId.getPrefix());
parameter.put("suffix", shardId.getSuffix());
return parameter;
} else if (obj instanceof Object) {
Map<String, Object> parameter = PropertyUtils.describe(obj);
parameter.put("prefix", shardId.getPrefix());
parameter.put("suffix", shardId.getSuffix());
return parameter;
} else if (obj != null) {
throw new UnsupportedOperationException(String.format(
"The parameter of type {%s} is not supported.",
obj.getClass()));
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
return null;
}
|
diff --git a/grails/src/web/org/codehaus/groovy/grails/web/mapping/RegexUrlMapping.java b/grails/src/web/org/codehaus/groovy/grails/web/mapping/RegexUrlMapping.java
index 0bacb6300..cb47bce65 100644
--- a/grails/src/web/org/codehaus/groovy/grails/web/mapping/RegexUrlMapping.java
+++ b/grails/src/web/org/codehaus/groovy/grails/web/mapping/RegexUrlMapping.java
@@ -1,358 +1,360 @@
/* Copyright 2004-2005 Graeme Rocher
*
* 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.codehaus.groovy.grails.web.mapping;
import groovy.lang.Closure;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.groovy.grails.commons.GrailsControllerClass;
import org.codehaus.groovy.grails.validation.ConstrainedProperty;
import org.codehaus.groovy.grails.web.mapping.exceptions.UrlMappingException;
import org.codehaus.groovy.grails.web.servlet.mvc.GrailsWebRequest;
import org.springframework.validation.Errors;
import org.springframework.validation.MapBindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
/**
* <p>A UrlMapping implementation that takes a Grails URL pattern and turns it into a regex matcher so that
* URLs can be matched and information captured from the match.</p>
*
* <p>A Grails URL pattern is not a regex, but is an extension to the form defined by Apache Ant and used by
* Spring AntPathMatcher. Unlike regular Ant paths Grails URL patterns allow for capturing groups in the form:</p>
*
* <code>/blog/(*)/**</code>
*
* <p>The parenthesis define a capturing group. This implementation transforms regular Ant paths into regular expressions
* that are able to use capturing groups</p>
*
*
* @see org.springframework.util.AntPathMatcher
*
* @author Graeme Rocher
* @since 0.5
*
* <p/>
* Created: Feb 28, 2007
* Time: 6:12:52 PM
*/
public class RegexUrlMapping implements UrlMapping {
private Pattern[] patterns;
private ConstrainedProperty[] constraints = new ConstrainedProperty[0];
private Object controllerName;
private Object actionName;
private UrlMappingData urlData;
private static final String WILDCARD = "*";
private static final String CAPTURED_WILDCARD = "(*)";
private static final String SLASH = "/";
private static final Log LOG = LogFactory.getLog(RegexUrlMapping.class);
public ConstrainedProperty[] getConstraints() {
return constraints;
}
public Object getControllerName() {
return controllerName;
}
public Object getActionName() {
return actionName;
}
/**
* Constructs a new RegexUrlMapping for the given pattern, controller name, action name and constraints.
*
* @param data An instance of the UrlMappingData class that holds necessary information of the URL mapping
* @param controllerName The name of the controller the URL maps to (required)
* @param actionName The name of the action the URL maps to
* @param constraints A list of ConstrainedProperty instances that relate to tokens in the URL
*
* @see org.codehaus.groovy.grails.validation.ConstrainedProperty
*/
public RegexUrlMapping(UrlMappingData data, Object controllerName, Object actionName, ConstrainedProperty[] constraints) {
if(data == null) throw new IllegalArgumentException("Argument [pattern] cannot be null");
this.controllerName = controllerName;
this.actionName = actionName;
String[] urls = data.getLogicalUrls();
this.urlData = data;
this.patterns = new Pattern[urls.length];
for (int i = 0; i < urls.length; i++) {
String url = urls[i];
Pattern pattern = convertToRegex(url);
if(pattern == null) throw new IllegalStateException("Cannot use null pattern in regular expression mapping for url ["+data.getUrlPattern()+"]");
this.patterns[i] = pattern;
}
if(constraints != null) {
this.constraints = constraints;
for (int i = 0; i < constraints.length; i++) {
ConstrainedProperty constraint = constraints[i];
if(data.isOptional(i)) {
constraint.setNullable(true);
}
}
}
}
/**
* Converst a Grails URL provides via the UrlMappingData interface to a regular expression
*
* @param url The URL to convert
* @return A regex Pattern objet
*/
protected Pattern convertToRegex(String url) {
Pattern regex;
String pattern = null;
try {
pattern = "^" + url.replaceAll("\\*", "[^/]+");
pattern += "/??$";
regex = Pattern.compile(pattern);
} catch (PatternSyntaxException pse) {
throw new UrlMappingException("Error evaluating mapping for pattern ["+pattern+"] from Grails URL mappings: " + pse.getMessage(), pse);
}
return regex;
}
/**
* Matches the given URI and returns a DefaultUrlMappingInfo instance or null
*
*
* @param uri The URI to match
* @return A UrlMappingInfo instance or null
*
* @see org.codehaus.groovy.grails.web.mapping.UrlMappingInfo
*/
public UrlMappingInfo match(String uri) {
for (int i = 0; i < patterns.length; i++) {
Pattern pattern = patterns[i];
Matcher m = pattern.matcher(uri);
if(m.find()) {
UrlMappingInfo urlInfo = createUrlMappingInfo(uri,m);
if(urlInfo!=null) {
return urlInfo;
}
}
}
return null;
}
/**
* @see org.codehaus.groovy.grails.web.mapping.UrlMapping
*/
public String createURL(Map parameterValues) {
if(parameterValues==null)parameterValues=Collections.EMPTY_MAP;
StringBuffer uri = new StringBuffer();
Set usedParams = new HashSet();
String[] tokens = urlData.getTokens();
int paramIndex = 0;
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i];
if(CAPTURED_WILDCARD.equals(token)) {
ConstrainedProperty prop = this.constraints[paramIndex++];
String propName = prop.getPropertyName();
Object value = parameterValues.get(propName);
usedParams.add(propName);
if(value == null && !prop.isNullable())
throw new UrlMappingException("Unable to create URL for mapping ["+this+"] and parameters ["+parameterValues+"]. Parameter ["+prop.getPropertyName()+"] is required, but was not specified!");
else if(value == null)
break;
uri.append(SLASH).append(value);
}
else {
uri.append(SLASH).append(token);
}
}
boolean addedParams = false;
+ usedParams.add( "controller" );
+ usedParams.add( "action" );
for (Iterator i = parameterValues.keySet().iterator(); i.hasNext();) {
String name = i.next().toString();
if(!usedParams.contains(name)) {
if(!addedParams) {
uri.append('?');
addedParams = true;
}
else {
uri.append('&');
}
uri.append(name).append('=').append(parameterValues.get(name));
}
}
if(LOG.isDebugEnabled()) {
LOG.debug("Created reverse URL mapping ["+uri.toString()+"] for parameters ["+parameterValues+"]");
}
return uri.toString();
}
public UrlMappingData getUrlData() {
return this.urlData;
}
private UrlMappingInfo createUrlMappingInfo(String uri, Matcher m) {
Map params = new HashMap();
Errors errors = new MapBindingResult(params, "urlMapping");
String lastGroup = null;
for (int i = 0; i < m.groupCount(); i++) {
lastGroup = m.group(i+1);
if(constraints.length > i) {
ConstrainedProperty cp = constraints[i];
cp.validate(this,lastGroup, errors);
if(errors.hasErrors()) return null;
else {
params.put(cp.getPropertyName(), lastGroup);
}
}
}
if(lastGroup!= null) {
String remainingUri = uri.substring(uri.lastIndexOf(lastGroup)+lastGroup.length());
if(remainingUri.length() > 0) {
if(remainingUri.startsWith(SLASH))remainingUri = remainingUri.substring(1);
String[] tokens = remainingUri.split(SLASH);
for (int i = 0; i < tokens.length; i=i+2) {
String token = tokens[i];
if((i+1) < tokens.length) {
params.put(token, tokens[i+1]);
}
}
}
}
if(controllerName == null) {
this.controllerName = createRuntimeConstraintEvaluator(GrailsControllerClass.CONTROLLER, this.constraints);
}
if(actionName == null) {
this.actionName = createRuntimeConstraintEvaluator(GrailsControllerClass.ACTION, this.constraints);
}
return new DefaultUrlMappingInfo(this.controllerName, this.actionName, params);
}
/**
* This method will look for a constraint for the given name and return a closure that when executed will
* attempt to evaluate its value from the bound request parameters at runtime.
*
* @param name The name of the constrained property
* @param constraints The array of current ConstrainedProperty instances
* @return Either a Closure or null
*/
private Object createRuntimeConstraintEvaluator(final String name, ConstrainedProperty[] constraints) {
if(constraints == null)return null;
for (int i = 0; i < constraints.length; i++) {
ConstrainedProperty constraint = constraints[i];
if(constraint.getPropertyName().equals(name)) {
return new Closure(this) {
public Object call(Object[] objects) {
GrailsWebRequest webRequest = (GrailsWebRequest)RequestContextHolder.currentRequestAttributes();
return webRequest.getParams().get(name);
}
};
}
}
return null;
}
public String[] getLogicalMappings() {
return this.urlData.getLogicalUrls();
}
/**
* Compares this UrlMapping instance with the specified UrlMapping instance and deals with URL mapping precedence rules.
*
* @param o An instance of the UrlMapping interface
* @return 1 if this UrlMapping should match before the specified UrlMapping. 0 if they are equal or -1 if this UrlMapping should match after the given UrlMapping
*/
public int compareTo(Object o) {
if(!(o instanceof UrlMapping)) throw new IllegalArgumentException("Cannot compare with Object ["+o+"]. It is not an instance of UrlMapping!");
UrlMapping other = (UrlMapping)o;
String[] otherTokens = other
.getUrlData()
.getTokens();
String[] tokens = getUrlData().getTokens();
if( isWildcard(this) && !isWildcard( other ) ) return -1;
if( !isWildcard(this) && isWildcard( other ) ) return 1;
if(tokens.length < otherTokens.length) {
return -1;
}
else if(tokens.length > otherTokens.length) {
return 1;
}
int result = 0;
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i];
if(otherTokens.length > i) {
String otherToken = otherTokens[i];
if(isWildcard(token) && !isWildcard(otherToken)) {
result = -1;
break;
}
else if(!isWildcard(token) && isWildcard(otherToken)) {
result = 1;
break;
}
}
else {
break;
}
}
return result;
}
private boolean isWildcard(UrlMapping mapping) {
String[] tokens = mapping.getUrlData().getTokens();
for( int i = 0; i < tokens.length; i++ ) {
if( isWildcard( tokens[i] )) return true;
}
return false;
}
private boolean isWildcard(String token) {
return WILDCARD.equals(token) || CAPTURED_WILDCARD.equals(token);
}
public String toString() {
return this.urlData.getUrlPattern();
}
}
| true | true | public String createURL(Map parameterValues) {
if(parameterValues==null)parameterValues=Collections.EMPTY_MAP;
StringBuffer uri = new StringBuffer();
Set usedParams = new HashSet();
String[] tokens = urlData.getTokens();
int paramIndex = 0;
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i];
if(CAPTURED_WILDCARD.equals(token)) {
ConstrainedProperty prop = this.constraints[paramIndex++];
String propName = prop.getPropertyName();
Object value = parameterValues.get(propName);
usedParams.add(propName);
if(value == null && !prop.isNullable())
throw new UrlMappingException("Unable to create URL for mapping ["+this+"] and parameters ["+parameterValues+"]. Parameter ["+prop.getPropertyName()+"] is required, but was not specified!");
else if(value == null)
break;
uri.append(SLASH).append(value);
}
else {
uri.append(SLASH).append(token);
}
}
boolean addedParams = false;
for (Iterator i = parameterValues.keySet().iterator(); i.hasNext();) {
String name = i.next().toString();
if(!usedParams.contains(name)) {
if(!addedParams) {
uri.append('?');
addedParams = true;
}
else {
uri.append('&');
}
uri.append(name).append('=').append(parameterValues.get(name));
}
}
if(LOG.isDebugEnabled()) {
LOG.debug("Created reverse URL mapping ["+uri.toString()+"] for parameters ["+parameterValues+"]");
}
return uri.toString();
}
| public String createURL(Map parameterValues) {
if(parameterValues==null)parameterValues=Collections.EMPTY_MAP;
StringBuffer uri = new StringBuffer();
Set usedParams = new HashSet();
String[] tokens = urlData.getTokens();
int paramIndex = 0;
for (int i = 0; i < tokens.length; i++) {
String token = tokens[i];
if(CAPTURED_WILDCARD.equals(token)) {
ConstrainedProperty prop = this.constraints[paramIndex++];
String propName = prop.getPropertyName();
Object value = parameterValues.get(propName);
usedParams.add(propName);
if(value == null && !prop.isNullable())
throw new UrlMappingException("Unable to create URL for mapping ["+this+"] and parameters ["+parameterValues+"]. Parameter ["+prop.getPropertyName()+"] is required, but was not specified!");
else if(value == null)
break;
uri.append(SLASH).append(value);
}
else {
uri.append(SLASH).append(token);
}
}
boolean addedParams = false;
usedParams.add( "controller" );
usedParams.add( "action" );
for (Iterator i = parameterValues.keySet().iterator(); i.hasNext();) {
String name = i.next().toString();
if(!usedParams.contains(name)) {
if(!addedParams) {
uri.append('?');
addedParams = true;
}
else {
uri.append('&');
}
uri.append(name).append('=').append(parameterValues.get(name));
}
}
if(LOG.isDebugEnabled()) {
LOG.debug("Created reverse URL mapping ["+uri.toString()+"] for parameters ["+parameterValues+"]");
}
return uri.toString();
}
|
diff --git a/src/com/reddit/worddit/ProfileActivity.java b/src/com/reddit/worddit/ProfileActivity.java
index 2089abf..e13d058 100755
--- a/src/com/reddit/worddit/ProfileActivity.java
+++ b/src/com/reddit/worddit/ProfileActivity.java
@@ -1,156 +1,160 @@
package com.reddit.worddit;
import com.reddit.worddit.api.APICall;
import com.reddit.worddit.api.APICallback;
import com.reddit.worddit.api.Session;
import com.reddit.worddit.api.response.Profile;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
public class ProfileActivity extends Activity {
protected Session mSession;
protected String mFriendStatus;
protected String mAvatarUrl;
protected boolean mInfoFetched = false;
protected boolean mAvatarFetched = false;
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
Intent i = getIntent();
mSession = (Session) i.getParcelableExtra(Constants.EXTRA_SESSION);
this.setContentView(R.layout.activity_profile);
setupListeners();
fetchInfo();
}
protected void onSaveInstanceState(Bundle icicle) {
saveToBundle(icicle);
}
protected void onRestoreInstanceState(Bundle icicle) {
restoreFromBundle(icicle);
}
protected void showFetching() {
findViewById(R.id.profile_bodyContainer).setVisibility(View.GONE);
findViewById(R.id.profile_messageContainer).setVisibility(View.VISIBLE);
findViewById(R.id.profile_progressBar).setVisibility(View.VISIBLE);
findViewById(R.id.profile_btnRetry).setVisibility(View.GONE);
TextView msg = (TextView) findViewById(R.id.profile_message);
msg.setText(R.string.label_loading);
}
protected void showMessage(int resId) {
findViewById(R.id.profile_bodyContainer).setVisibility(View.GONE);
findViewById(R.id.profile_messageContainer).setVisibility(View.VISIBLE);
findViewById(R.id.profile_progressBar).setVisibility(View.GONE);
findViewById(R.id.profile_btnRetry).setVisibility(View.VISIBLE);
TextView msg = (TextView) findViewById(R.id.profile_message);
msg.setText(resId);
}
protected void showProfile(Profile p) {
TextView title = (TextView) findViewById(R.id.profile_title);
TextView subtitle = (TextView) findViewById(R.id.profile_subtitle);
mAvatarUrl = p.avatar;
if(p.nickname != null && p.nickname.length() > 0 && p.email != null) {
title.setText(p.nickname);
subtitle.setText(p.email);
}
else if(p.email != null) {
title.setText(p.email);
subtitle.setVisibility(View.GONE);
}
+ else if(p.nickname != null && p.nickname.length() > 0) {
+ title.setText(p.nickname);
+ subtitle.setVisibility(View.GONE);
+ }
else {
title.setText(R.string.label_no_nickname);
subtitle.setVisibility(View.GONE);
}
findViewById(R.id.profile_bodyContainer).setVisibility(View.VISIBLE);
findViewById(R.id.profile_messageContainer).setVisibility(View.GONE);
// TODO: Friend status? Change the buttons?
}
protected void fetchInfo() {
if(mInfoFetched == true) return;
showFetching();
APICall task = new APICall(new APICallback() {
@Override
public void onCallComplete(boolean success, APICall task) {
mInfoFetched = success;
if(success) {
showProfile((Profile) task.getPayload());
}
else {
showMessage(task.getMessage());
}
}
}, mSession);
mInfoFetched = true;
Intent i = getIntent();
task.findUser( i.getStringExtra(Constants.EXTRA_FRIENDID) );
}
private void saveToBundle(Bundle b) {
if(b == null) return;
TextView title = (TextView) findViewById(R.id.profile_title);
TextView subtitle = (TextView) findViewById(R.id.profile_subtitle);
b.putString(TITLE, title.getText().toString());
b.putString(SUBTITLE, subtitle.getText().toString());
b.putInt(SUBTITLE_STATUS, subtitle.getVisibility());
b.putString(STATUS, mFriendStatus);
b.putString(AVATAR_URL, mAvatarUrl);
b.putBoolean(FETCHED_INFO, mInfoFetched);
b.putBoolean(FETCHED_AVATAR, mAvatarFetched);
}
private void restoreFromBundle(Bundle b) {
if(b == null) return;
TextView title = (TextView) findViewById(R.id.profile_title);
TextView subtitle = (TextView) findViewById(R.id.profile_subtitle);
title.setText(b.getString(TITLE));
subtitle.setText(b.getString(SUBTITLE));
subtitle.setVisibility(b.getInt(SUBTITLE_STATUS));
mFriendStatus = (b.containsKey(STATUS)) ? b.getString(STATUS) : mFriendStatus;
mAvatarUrl = (b.containsKey(AVATAR_URL)) ? b.getString(AVATAR_URL) : mAvatarUrl;
mInfoFetched = b.getBoolean(FETCHED_INFO);
mAvatarFetched = b.getBoolean(FETCHED_AVATAR);
}
private void setupListeners() {
findViewById(R.id.profile_btnRetry).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
ProfileActivity.this.fetchInfo();
}
});
}
public static final String
TITLE = "title",
SUBTITLE = "subtitle",
SUBTITLE_STATUS = "subtitle-status",
STATUS = "status",
AVATAR_URL = "avatar-url",
FETCHED_INFO = "fetched-info",
FETCHED_AVATAR = "fetched-avatar";
}
| true | true | protected void showProfile(Profile p) {
TextView title = (TextView) findViewById(R.id.profile_title);
TextView subtitle = (TextView) findViewById(R.id.profile_subtitle);
mAvatarUrl = p.avatar;
if(p.nickname != null && p.nickname.length() > 0 && p.email != null) {
title.setText(p.nickname);
subtitle.setText(p.email);
}
else if(p.email != null) {
title.setText(p.email);
subtitle.setVisibility(View.GONE);
}
else {
title.setText(R.string.label_no_nickname);
subtitle.setVisibility(View.GONE);
}
findViewById(R.id.profile_bodyContainer).setVisibility(View.VISIBLE);
findViewById(R.id.profile_messageContainer).setVisibility(View.GONE);
// TODO: Friend status? Change the buttons?
}
| protected void showProfile(Profile p) {
TextView title = (TextView) findViewById(R.id.profile_title);
TextView subtitle = (TextView) findViewById(R.id.profile_subtitle);
mAvatarUrl = p.avatar;
if(p.nickname != null && p.nickname.length() > 0 && p.email != null) {
title.setText(p.nickname);
subtitle.setText(p.email);
}
else if(p.email != null) {
title.setText(p.email);
subtitle.setVisibility(View.GONE);
}
else if(p.nickname != null && p.nickname.length() > 0) {
title.setText(p.nickname);
subtitle.setVisibility(View.GONE);
}
else {
title.setText(R.string.label_no_nickname);
subtitle.setVisibility(View.GONE);
}
findViewById(R.id.profile_bodyContainer).setVisibility(View.VISIBLE);
findViewById(R.id.profile_messageContainer).setVisibility(View.GONE);
// TODO: Friend status? Change the buttons?
}
|
diff --git a/plugins/org.eclipse.wst.common.frameworks.ui/wtp_ui/org/eclipse/wst/common/frameworks/internal/ui/UITesterImpl.java b/plugins/org.eclipse.wst.common.frameworks.ui/wtp_ui/org/eclipse/wst/common/frameworks/internal/ui/UITesterImpl.java
index 7d19f90e..695fdd38 100644
--- a/plugins/org.eclipse.wst.common.frameworks.ui/wtp_ui/org/eclipse/wst/common/frameworks/internal/ui/UITesterImpl.java
+++ b/plugins/org.eclipse.wst.common.frameworks.ui/wtp_ui/org/eclipse/wst/common/frameworks/internal/ui/UITesterImpl.java
@@ -1,53 +1,52 @@
/*******************************************************************************
* Copyright (c) 2003, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
/*
* Created on Oct 27, 2003
*
* To change the template for this generated file go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
package org.eclipse.wst.common.frameworks.internal.ui;
import org.eclipse.jem.util.UITester;
import org.eclipse.ui.PlatformUI;
/**
* @author schacher
*
* To change the template for this generated type comment go to
* Window>Preferences>Java>Code Generation>Code and Comments
*/
public class UITesterImpl implements UITester {
/**
*
*/
public UITesterImpl() {
super();
}
/*
* (non-Javadoc)
*
* @see org.eclipse.wst.common.frameworks.internal.UITester#isCurrentContextUI()
*/
public boolean isCurrentContextUI() {
- //TODO verify this is working properly now
try {
return PlatformUI.isWorkbenchRunning() || PlatformUI.getWorkbench().isClosing();
} catch (Exception e) {
//Ignore, workbench must not be running
return false;
}
}
}
| true | true | public boolean isCurrentContextUI() {
//TODO verify this is working properly now
try {
return PlatformUI.isWorkbenchRunning() || PlatformUI.getWorkbench().isClosing();
} catch (Exception e) {
//Ignore, workbench must not be running
return false;
}
}
| public boolean isCurrentContextUI() {
try {
return PlatformUI.isWorkbenchRunning() || PlatformUI.getWorkbench().isClosing();
} catch (Exception e) {
//Ignore, workbench must not be running
return false;
}
}
|
diff --git a/RavenEdit/src/raven/edit/editor/EditorController.java b/RavenEdit/src/raven/edit/editor/EditorController.java
index 3b5a040..6fa62b3 100644
--- a/RavenEdit/src/raven/edit/editor/EditorController.java
+++ b/RavenEdit/src/raven/edit/editor/EditorController.java
@@ -1,161 +1,160 @@
package raven.edit.editor;
import java.awt.Component;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import raven.game.RavenMap;
import raven.utils.MapSerializer;
public class EditorController implements EditorViewDelegate {
JFileChooser fileChooser;
EditorView view;
RavenMap currentLevel;
boolean isDirty;
private class LevelFilter extends FileFilter {
@Override
public boolean accept(File file) {
if (file.isDirectory()) {
return false;
}
return file.getName().endsWith(".raven");
}
@Override
public String getDescription() {
return "Raven levels (*.raven)";
}
}
public EditorController() {
fileChooser = new JFileChooser();
fileChooser.setFileFilter(new LevelFilter());
currentLevel = new RavenMap();
view = new EditorView(currentLevel);
view.setDelegate(this);
view.create();
isDirty = false;
}
@Override
public boolean doNewLevel() {
if (!doSaveIfDirty())
return false;
changeLevel(new RavenMap());
return true;
}
@Override
public boolean doOpen() {
// If there have been changes, ask about saving them.
if (!doSaveIfDirty())
return false;
int result = fileChooser.showOpenDialog((Component)view);
if (result == JFileChooser.APPROVE_OPTION) {
RavenMap level;
try {
- level = new RavenMap();
- level.loadMap(fileChooser.getSelectedFile().getPath());
+ level = MapSerializer.deserializeMapFromFile(fileChooser.getSelectedFile());
changeLevel(level);
view.updateStatus("Opened level " + level.getPath());
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(view,
"File " + fileChooser.getSelectedFile().getPath() + " was not found!",
"File not found",
JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(view,
"Unable to open " + fileChooser.getSelectedFile().getPath() + "\n" + e.getLocalizedMessage(),
"Unable to open file",
JOptionPane.ERROR_MESSAGE);
}
}
return true;
}
/**
* Returns true if the save was successful.
*/
public boolean doSaveIfDirty() {
if (isDirty) {
int confirm = JOptionPane.showConfirmDialog(view,
"Level has been modified. Would you like to save the changes?", "Confirm save...",
JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
if (confirm == JOptionPane.YES_OPTION) {
doSave();
} else if (confirm == JOptionPane.CANCEL_OPTION) {
return false;
} // else ignore changes
}
return true;
}
@Override
public boolean doSave() {
// Ask where to save the file if it doesn't have a filename yet
if (currentLevel.getPath() == null) {
fileChooser.setSelectedFile(new File(currentLevel.getName() + ".raven"));
int result = fileChooser.showSaveDialog((Component)view);
if (result == JFileChooser.APPROVE_OPTION) {
currentLevel.setPath(fileChooser.getSelectedFile().getPath());
} else {
return false;
}
}
isDirty = false;
// Write it
try {
MapSerializer.serializeMapToPath(currentLevel, currentLevel.getPath());
} catch (IOException e) {
JOptionPane.showMessageDialog(view,
"Unable to save " + fileChooser.getSelectedFile().getPath() + "\n" + e.getLocalizedMessage(),
"Unable to save file",
JOptionPane.ERROR_MESSAGE);
}
view.updateStatus("Level saved to " + currentLevel.getPath());
return true;
}
@Override
public void changeLevel(RavenMap level) {
isDirty = false;
currentLevel = level;
view.setLevel(currentLevel);
}
@Override
public EditorView getView() {
return view;
}
@Override
public void makeDirty() {
isDirty = true;
}
}
| true | true | public boolean doOpen() {
// If there have been changes, ask about saving them.
if (!doSaveIfDirty())
return false;
int result = fileChooser.showOpenDialog((Component)view);
if (result == JFileChooser.APPROVE_OPTION) {
RavenMap level;
try {
level = new RavenMap();
level.loadMap(fileChooser.getSelectedFile().getPath());
changeLevel(level);
view.updateStatus("Opened level " + level.getPath());
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(view,
"File " + fileChooser.getSelectedFile().getPath() + " was not found!",
"File not found",
JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(view,
"Unable to open " + fileChooser.getSelectedFile().getPath() + "\n" + e.getLocalizedMessage(),
"Unable to open file",
JOptionPane.ERROR_MESSAGE);
}
}
return true;
}
| public boolean doOpen() {
// If there have been changes, ask about saving them.
if (!doSaveIfDirty())
return false;
int result = fileChooser.showOpenDialog((Component)view);
if (result == JFileChooser.APPROVE_OPTION) {
RavenMap level;
try {
level = MapSerializer.deserializeMapFromFile(fileChooser.getSelectedFile());
changeLevel(level);
view.updateStatus("Opened level " + level.getPath());
} catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(view,
"File " + fileChooser.getSelectedFile().getPath() + " was not found!",
"File not found",
JOptionPane.ERROR_MESSAGE);
} catch (IOException e) {
JOptionPane.showMessageDialog(view,
"Unable to open " + fileChooser.getSelectedFile().getPath() + "\n" + e.getLocalizedMessage(),
"Unable to open file",
JOptionPane.ERROR_MESSAGE);
}
}
return true;
}
|
diff --git a/ContactsWidgetICS/src/com/gmail/yuyang226/contactswidget/pro/ContactAccessor.java b/ContactsWidgetICS/src/com/gmail/yuyang226/contactswidget/pro/ContactAccessor.java
index 41f18d7..a23579f 100644
--- a/ContactsWidgetICS/src/com/gmail/yuyang226/contactswidget/pro/ContactAccessor.java
+++ b/ContactsWidgetICS/src/com/gmail/yuyang226/contactswidget/pro/ContactAccessor.java
@@ -1,510 +1,511 @@
/**
*
*/
package com.gmail.yuyang226.contactswidget.pro;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.TreeSet;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.CursorLoader;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.net.Uri;
import android.provider.ContactsContract;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Directory;
import android.util.LruCache;
import com.gmail.yuyang226.contactswidget.pro.models.Contact;
import com.gmail.yuyang226.contactswidget.pro.models.ContactDirectory;
import com.gmail.yuyang226.contactswidget.pro.models.ContactGroup;
import com.gmail.yuyang226.contactswidget.pro.models.PhoneNumber;
import com.gmail.yuyang226.contactswidget.pro.ui.ContactsWidgetConfigurationActivity;
/**
* @author Toby Yu([email protected])
*
*/
public class ContactAccessor {
private static final String STARRED_CONTACTS_ENG = "Starred in Android"; //$NON-NLS-1$
private static final LruCache<String, Bitmap> IMAGES_CACHE;
private static final int CACHE_SIZE = 8 * 1024 * 1024; // 8MiB
private static final String[] CONTACT_PROJECTION = {
ContactsContract.Contacts._ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.Contacts.PHOTO_URI,
ContactsContract.Contacts.HAS_PHONE_NUMBER};
private static final String[] CONTACTS_BY_GROUP_PROJECTION = {
ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID,
ContactsContract.CommonDataKinds.GroupMembership.CONTACT_ID };
private static final String CONTACT_SELECTION = Contacts._ID + "=?"; //$NON-NLS-1$
private static final String[] PHONENUNBER_PROJECTION = {
ContactsContract.CommonDataKinds.Phone._ID,
ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.NUMBER,
ContactsContract.CommonDataKinds.Phone.IS_PRIMARY};
private static final String PHONENUMBER_SELECTION =
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ?"; //$NON-NLS-1$
private static final String PHONENUMBER_SORTSTRING = ContactsContract.CommonDataKinds.Phone.TIMES_CONTACTED + " DESC"; //$NON-NLS-1$
private static final Comparator<PhoneNumber> PHONENUMBER_COMPARATOR = new Comparator<PhoneNumber>() {
@Override
public int compare(PhoneNumber n1, PhoneNumber n2) {
if (n1.isPrimary()) {
return -1;
} else if (n2.isPrimary()) {
return 1;
} else if (ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE == n1.getType()) {
return -1;
} else if (ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE == n2.getType()) {
return 1;
} else if (ContactsContract.CommonDataKinds.Phone.TYPE_MAIN == n1.getType()) {
return -1;
} else if (ContactsContract.CommonDataKinds.Phone.TYPE_MAIN == n2.getType()) {
return 1;
}
return 0;
}
};
static {
IMAGES_CACHE = new LruCache<String, Bitmap>(CACHE_SIZE) {
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();
}
};
}
/**
*
*/
public ContactAccessor() {
super();
}
static void clearImageCache() {
IMAGES_CACHE.evictAll();
}
public List<ContactDirectory> getContactDirectories(Context context) {
final List<ContactDirectory> directories = new ArrayList<ContactDirectory>();
// Run query
Uri uri = ContactsContract.Directory.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Directory._ID,
ContactsContract.Directory.ACCOUNT_NAME,
ContactsContract.Directory.ACCOUNT_TYPE, };
String selection = null;
String[] selectionArgs = null;
String sortOrder = ContactsContract.Directory.DISPLAY_NAME
+ " COLLATE LOCALIZED ASC"; //$NON-NLS-1$
CursorLoader loader = new CursorLoader(context, uri, projection,
selection, selectionArgs, sortOrder);
Cursor cursor = null;
try {
loader.startLoading();
cursor = loader.loadInBackground();
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
long directoryId = cursor.getLong(0);
String accountName = cursor.getString(1);
if (accountName == null && directoryId == Directory.DEFAULT) {
accountName = "Local"; //$NON-NLS-1$
}
String accountType = cursor.getString(2);
ContactDirectory directory = new ContactDirectory(directoryId,
accountName, accountType);
directories.add(directory);
cursor.moveToNext();
}
} finally {
loader.stopLoading();
if (cursor != null) {
cursor.close();
}
}
return directories;
}
public Collection<ContactGroup> getContactGroups(Context context,
long directoryId) {
final String starredContacts = context.getString(R.string.starredContacts);
final String myContacts = context.getString(R.string.myContacts);
Comparator<ContactGroup> comparator = new Comparator<ContactGroup>() {
@Override
public int compare(ContactGroup g1, ContactGroup g2) {
if (myContacts.equalsIgnoreCase(g1.getTitle())) {
return -1;
} else if (myContacts.equalsIgnoreCase(g2.getTitle())) {
return 1;
} else if (starredContacts.equalsIgnoreCase(g1.getTitle())
|| STARRED_CONTACTS_ENG.equalsIgnoreCase(g1.getTitle())) {
return -1;
} else if (starredContacts.equalsIgnoreCase(g2.getTitle())
|| STARRED_CONTACTS_ENG.equalsIgnoreCase(g2.getTitle())) {
return 1;
}
return g1.getTitle().compareTo(g2.getTitle());
}
};
final Collection<ContactGroup> groups = new TreeSet<ContactGroup>(
comparator);
// Run query
Uri uri = ContactsContract.Groups.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Groups._ID,
ContactsContract.Groups.ACCOUNT_NAME,
ContactsContract.Groups.ACCOUNT_TYPE,
ContactsContract.Groups.TITLE, };
String selection = null;
String[] selectionArgs = null;
String sortOrder = ContactsContract.Groups.TITLE
+ " COLLATE LOCALIZED ASC"; //$NON-NLS-1$
CursorLoader loader = new CursorLoader(context, uri, projection,
selection, selectionArgs, sortOrder);
Cursor cursor = null;
boolean foundStarredGroup = false;
boolean foundMyContacts = false;
try {
loader.startLoading();
cursor = loader.loadInBackground();
if (cursor == null) {
return groups;
}
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
long groupId = cursor.getLong(0);
String accountName = cursor.getString(1);
String accountType = cursor.getString(2);
String title = cursor.getString(3);
if (title == null || title.equalsIgnoreCase(myContacts)) { //$NON-NLS-1$
// the title is null and we don't want to handle My Contacts
if (foundMyContacts) {
//two my contacts appear
cursor.moveToNext();
continue;
}
foundMyContacts = true;
groupId = ContactsWidgetConfigurationActivity.CONTACT_MY_CONTACTS_GROUP_ID;
+ title = myContacts;
} else if (title.equalsIgnoreCase(starredContacts)
|| STARRED_CONTACTS_ENG.equalsIgnoreCase(title)) {
foundStarredGroup = true;
groupId = ContactsWidgetConfigurationActivity.CONTACT_STARRED_GROUP_ID;
}
ContactGroup group = new ContactGroup(groupId, accountName,
accountType, title);
groups.add(group);
cursor.moveToNext();
}
} finally {
loader.stopLoading();
if (cursor != null) {
cursor.close();
}
}
if (!foundStarredGroup) {
//not containing the starredContacts
ContactGroup group = new ContactGroup(
ContactsWidgetConfigurationActivity.CONTACT_STARRED_GROUP_ID, starredContacts,
null, starredContacts);
groups.add(group);
}
if (!foundMyContacts) {
//not containing the my contacts group
ContactGroup group = new ContactGroup(
ContactsWidgetConfigurationActivity.CONTACT_MY_CONTACTS_GROUP_ID, myContacts,
null, myContacts);
groups.add(group);
}
return groups;
}
/**
* Obtains the contact list for the currently selected account.
*
* @return A cursor for for accessing the contact list.
*/
public List<Contact> getContacts(ContentResolver contentResolver,
Context context, int appWidgetId, Rect size) {
final List<Contact> contacts = new ArrayList<Contact>();
// Run query
Uri uri = ContactsContract.Contacts.CONTENT_URI;
String selection = null;
String groupId = ContactsWidgetConfigurationActivity
.loadSelectionString(context, appWidgetId);
String sortOrder = ContactsWidgetConfigurationActivity
.loadSortingString(context, appWidgetId);
int maxNumber = ContactsWidgetConfigurationActivity.loadMaxNumbers(context, appWidgetId);
if (ContactsWidgetConfigurationActivity.CONTACT_STARRED.equals(groupId)) {
selection = groupId;
} else if (groupId == "") { //$NON-NLS-1$
//all contacts;
selection = groupId;
} else {
return getContactsByGroup(contentResolver, context, appWidgetId,
groupId, sortOrder, size, maxNumber);
}
String[] selectionArgs = null;
boolean supportDirectDial = ContactsWidgetConfigurationActivity
.loadSupportDirectDial(context, appWidgetId);
boolean showHighRes = ContactsWidgetConfigurationActivity
.loadShowHighRes(context, appWidgetId);
CursorLoader loader = new CursorLoader(context, uri, CONTACT_PROJECTION,
selection, selectionArgs, sortOrder);
Cursor cursor = null;
try {
loader.startLoading();
cursor = loader.loadInBackground();
if (cursor == null) {
return contacts;
}
cursor.moveToFirst();
int count = 0;
while (cursor.isAfterLast() == false && count < maxNumber) {
long contactId = cursor.getLong(0);
String displayName = cursor.getString(1);
String photoUri = cursor.getString(2);
Contact contact = new Contact();
contact.setContactId(contactId);
contact.setDisplayName(displayName);
contact.setPhotoUri(photoUri);
contact.setContactUri(ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, contactId));
if (photoUri != null && photoUri.length() > 0) {
contact.setPhoto(loadContactPhoto(contentResolver,
contact.getContactUri(), showHighRes, size));
}
int hasPhoneNumber = cursor.getInt(3);
if (supportDirectDial && hasPhoneNumber > 0) {
contact.setPhoneNumbers(loadPhoneNumbers(
contentResolver, context, contactId));
}
if (!supportDirectDial || hasPhoneNumber > 0) {
//either not support direct dial, or has phone number
contacts.add(contact);
count++;
}
cursor.moveToNext();
}
} finally {
loader.stopLoading();
if (cursor != null) {
cursor.close();
}
}
return contacts;
}
private List<PhoneNumber> loadPhoneNumbers(ContentResolver contentResolver,
Context context, long contactId) {
Cursor pCur = null;
CursorLoader loader = new CursorLoader(context, ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
PHONENUNBER_PROJECTION,
PHONENUMBER_SELECTION, new String[] { String.valueOf(contactId) }, PHONENUMBER_SORTSTRING);
List<PhoneNumber> phoneNumbers = new ArrayList<PhoneNumber>();
try {
loader.startLoading();
pCur = loader.loadInBackground();
if (pCur == null) {
return phoneNumbers;
}
pCur.moveToFirst();
while (pCur.isAfterLast() == false) {
int type = pCur.getInt(1);
String phone = pCur.getString(2);
int primary = pCur.getInt(3);
if (primary > 0) {
//primary number will be used first
phoneNumbers.add(0, new PhoneNumber(type, phone, true));
} else {
phoneNumbers.add(new PhoneNumber(type, phone, false));
}
pCur.moveToNext();
}
} finally {
loader.stopLoading();
if (pCur != null) {
pCur.close();
}
}
Collections.sort(phoneNumbers, PHONENUMBER_COMPARATOR);
return phoneNumbers;
}
private List<Contact> getContactsByGroup(ContentResolver contentResolver,
Context context, int appWidgetId, String groupID, String sortOrder,
Rect size, int maxNumber) {
final List<Contact> contacts = new ArrayList<Contact>();
Uri uri = ContactsContract.Data.CONTENT_URI;
String selection = new StringBuffer(ContactsContract.CommonDataKinds.GroupMembership.GROUP_ROW_ID)
.append("=").append(groupID).toString(); //$NON-NLS-1$
boolean showHighRes = ContactsWidgetConfigurationActivity
.loadShowHighRes(context, appWidgetId);
boolean supportDirectDial = ContactsWidgetConfigurationActivity
.loadSupportDirectDial(context, appWidgetId);
String[] selectionArgs = null;
CursorLoader loader = new CursorLoader(context, uri, CONTACTS_BY_GROUP_PROJECTION,
selection, selectionArgs, sortOrder);
Cursor cursor = null;
try {
loader.startLoading();
cursor = loader.loadInBackground();
if (cursor == null) {
return contacts;
}
cursor.moveToFirst();
int count = 0;
while (cursor.isAfterLast() == false
&& count < maxNumber) {
// long groupRowId = cursor.getLong(0);
long contactId = cursor.getLong(1);
Contact contact = loadContactById(contentResolver, context,
contactId, sortOrder, showHighRes, supportDirectDial, size);
if (contact != null) {
contacts.add(contact);
count++;
}
cursor.moveToNext();
}
} finally {
loader.stopLoading();
if (cursor != null) {
cursor.close();
}
}
return contacts;
}
private Contact loadContactById(ContentResolver contentResolver,
Context context, long contactId, String sortOrder, boolean showHighRes,
boolean supportDirectDial, Rect size) {
Contact contact = new Contact();
contact.setContactId(contactId);
Uri contactUri = ContentUris.withAppendedId(
ContactsContract.Contacts.CONTENT_URI, contactId);
contact.setContactUri(contactUri);
Uri uri = ContactsContract.Contacts.CONTENT_URI;
CursorLoader loader = new CursorLoader(context, uri, CONTACT_PROJECTION,
CONTACT_SELECTION, new String[]{String.valueOf(contactId)}, sortOrder);
Cursor cursor = null;
try {
loader.startLoading();
cursor = loader.loadInBackground();
if (cursor == null) {
//did not find the contact
return null;
} else if (cursor.moveToFirst()) {
String displayName = cursor.getString(1);
String photoUri = cursor.getString(2);
contact.setContactId(contactId);
contact.setDisplayName(displayName);
contact.setPhotoUri(photoUri);
if (photoUri != null && photoUri.length() > 0) {
contact.setPhoto(loadContactPhoto(contentResolver,
contact.getContactUri(), showHighRes, size));
}
int hasPhoneNumber = cursor.getInt(3);
if (supportDirectDial) {
if (hasPhoneNumber > 0) {
contact.setPhoneNumbers(loadPhoneNumbers(
contentResolver, context, contactId));
} else {
//users want direct dial but this contact has no phone number
return null;
}
}
}
} finally {
loader.stopLoading();
if (cursor != null) {
cursor.close();
}
}
return contact;
}
public static int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
return inSampleSize;
}
private Bitmap loadContactPhoto(ContentResolver contentResolver, Uri uri, boolean showHighRes,
Rect size) {
final String imageKey = uri.toString() + showHighRes + size;
Bitmap pic = IMAGES_CACHE.get(imageKey);
if (pic == null) {
InputStream input = ContactsContract.Contacts
.openContactPhotoInputStream(contentResolver, uri, showHighRes);
if (input == null) {
return null;
}
if (showHighRes && size != null) {
//performance enhancement
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(input, null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, size.width(), size.height());
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
//opening another inputstream because the first one has been auto closed
input = ContactsContract.Contacts
.openContactPhotoInputStream(contentResolver, uri, showHighRes);
if (input == null) {
return null;
}
pic = BitmapFactory.decodeStream(input, null, options);
} else {
pic = BitmapFactory.decodeStream(input);
}
if (pic != null) {
IMAGES_CACHE.put(imageKey, pic);
}
}
return pic;
}
}
| true | true | public Collection<ContactGroup> getContactGroups(Context context,
long directoryId) {
final String starredContacts = context.getString(R.string.starredContacts);
final String myContacts = context.getString(R.string.myContacts);
Comparator<ContactGroup> comparator = new Comparator<ContactGroup>() {
@Override
public int compare(ContactGroup g1, ContactGroup g2) {
if (myContacts.equalsIgnoreCase(g1.getTitle())) {
return -1;
} else if (myContacts.equalsIgnoreCase(g2.getTitle())) {
return 1;
} else if (starredContacts.equalsIgnoreCase(g1.getTitle())
|| STARRED_CONTACTS_ENG.equalsIgnoreCase(g1.getTitle())) {
return -1;
} else if (starredContacts.equalsIgnoreCase(g2.getTitle())
|| STARRED_CONTACTS_ENG.equalsIgnoreCase(g2.getTitle())) {
return 1;
}
return g1.getTitle().compareTo(g2.getTitle());
}
};
final Collection<ContactGroup> groups = new TreeSet<ContactGroup>(
comparator);
// Run query
Uri uri = ContactsContract.Groups.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Groups._ID,
ContactsContract.Groups.ACCOUNT_NAME,
ContactsContract.Groups.ACCOUNT_TYPE,
ContactsContract.Groups.TITLE, };
String selection = null;
String[] selectionArgs = null;
String sortOrder = ContactsContract.Groups.TITLE
+ " COLLATE LOCALIZED ASC"; //$NON-NLS-1$
CursorLoader loader = new CursorLoader(context, uri, projection,
selection, selectionArgs, sortOrder);
Cursor cursor = null;
boolean foundStarredGroup = false;
boolean foundMyContacts = false;
try {
loader.startLoading();
cursor = loader.loadInBackground();
if (cursor == null) {
return groups;
}
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
long groupId = cursor.getLong(0);
String accountName = cursor.getString(1);
String accountType = cursor.getString(2);
String title = cursor.getString(3);
if (title == null || title.equalsIgnoreCase(myContacts)) { //$NON-NLS-1$
// the title is null and we don't want to handle My Contacts
if (foundMyContacts) {
//two my contacts appear
cursor.moveToNext();
continue;
}
foundMyContacts = true;
groupId = ContactsWidgetConfigurationActivity.CONTACT_MY_CONTACTS_GROUP_ID;
} else if (title.equalsIgnoreCase(starredContacts)
|| STARRED_CONTACTS_ENG.equalsIgnoreCase(title)) {
foundStarredGroup = true;
groupId = ContactsWidgetConfigurationActivity.CONTACT_STARRED_GROUP_ID;
}
ContactGroup group = new ContactGroup(groupId, accountName,
accountType, title);
groups.add(group);
cursor.moveToNext();
}
} finally {
loader.stopLoading();
if (cursor != null) {
cursor.close();
}
}
if (!foundStarredGroup) {
//not containing the starredContacts
ContactGroup group = new ContactGroup(
ContactsWidgetConfigurationActivity.CONTACT_STARRED_GROUP_ID, starredContacts,
null, starredContacts);
groups.add(group);
}
if (!foundMyContacts) {
//not containing the my contacts group
ContactGroup group = new ContactGroup(
ContactsWidgetConfigurationActivity.CONTACT_MY_CONTACTS_GROUP_ID, myContacts,
null, myContacts);
groups.add(group);
}
return groups;
}
| public Collection<ContactGroup> getContactGroups(Context context,
long directoryId) {
final String starredContacts = context.getString(R.string.starredContacts);
final String myContacts = context.getString(R.string.myContacts);
Comparator<ContactGroup> comparator = new Comparator<ContactGroup>() {
@Override
public int compare(ContactGroup g1, ContactGroup g2) {
if (myContacts.equalsIgnoreCase(g1.getTitle())) {
return -1;
} else if (myContacts.equalsIgnoreCase(g2.getTitle())) {
return 1;
} else if (starredContacts.equalsIgnoreCase(g1.getTitle())
|| STARRED_CONTACTS_ENG.equalsIgnoreCase(g1.getTitle())) {
return -1;
} else if (starredContacts.equalsIgnoreCase(g2.getTitle())
|| STARRED_CONTACTS_ENG.equalsIgnoreCase(g2.getTitle())) {
return 1;
}
return g1.getTitle().compareTo(g2.getTitle());
}
};
final Collection<ContactGroup> groups = new TreeSet<ContactGroup>(
comparator);
// Run query
Uri uri = ContactsContract.Groups.CONTENT_URI;
String[] projection = new String[] { ContactsContract.Groups._ID,
ContactsContract.Groups.ACCOUNT_NAME,
ContactsContract.Groups.ACCOUNT_TYPE,
ContactsContract.Groups.TITLE, };
String selection = null;
String[] selectionArgs = null;
String sortOrder = ContactsContract.Groups.TITLE
+ " COLLATE LOCALIZED ASC"; //$NON-NLS-1$
CursorLoader loader = new CursorLoader(context, uri, projection,
selection, selectionArgs, sortOrder);
Cursor cursor = null;
boolean foundStarredGroup = false;
boolean foundMyContacts = false;
try {
loader.startLoading();
cursor = loader.loadInBackground();
if (cursor == null) {
return groups;
}
cursor.moveToFirst();
while (cursor.isAfterLast() == false) {
long groupId = cursor.getLong(0);
String accountName = cursor.getString(1);
String accountType = cursor.getString(2);
String title = cursor.getString(3);
if (title == null || title.equalsIgnoreCase(myContacts)) { //$NON-NLS-1$
// the title is null and we don't want to handle My Contacts
if (foundMyContacts) {
//two my contacts appear
cursor.moveToNext();
continue;
}
foundMyContacts = true;
groupId = ContactsWidgetConfigurationActivity.CONTACT_MY_CONTACTS_GROUP_ID;
title = myContacts;
} else if (title.equalsIgnoreCase(starredContacts)
|| STARRED_CONTACTS_ENG.equalsIgnoreCase(title)) {
foundStarredGroup = true;
groupId = ContactsWidgetConfigurationActivity.CONTACT_STARRED_GROUP_ID;
}
ContactGroup group = new ContactGroup(groupId, accountName,
accountType, title);
groups.add(group);
cursor.moveToNext();
}
} finally {
loader.stopLoading();
if (cursor != null) {
cursor.close();
}
}
if (!foundStarredGroup) {
//not containing the starredContacts
ContactGroup group = new ContactGroup(
ContactsWidgetConfigurationActivity.CONTACT_STARRED_GROUP_ID, starredContacts,
null, starredContacts);
groups.add(group);
}
if (!foundMyContacts) {
//not containing the my contacts group
ContactGroup group = new ContactGroup(
ContactsWidgetConfigurationActivity.CONTACT_MY_CONTACTS_GROUP_ID, myContacts,
null, myContacts);
groups.add(group);
}
return groups;
}
|
diff --git a/src/pokemon/util/WildPokemonGenerator.java b/src/pokemon/util/WildPokemonGenerator.java
index 1fae7bb..5a34130 100644
--- a/src/pokemon/util/WildPokemonGenerator.java
+++ b/src/pokemon/util/WildPokemonGenerator.java
@@ -1,24 +1,19 @@
package pokemon.util;
import pokemon.core.Pokemon;
import pokemon.core.Species;
/**
* Created with IntelliJ IDEA.
* User: Nolan
* Date: 5/14/13
* Time: 9:43 AM
* To change this template use File | Settings | File Templates.
*/
public class WildPokemonGenerator {
//TODO - make enums for each route and what pokemon can appear where along with the level range
- public static Pokemon generatePokemon() {
- int rand = (int) (Math.random() * Species.values().length);
- for(final Species s : Species.values()) {
- if(Integer.parseInt(s.getDexNumber()) == rand) {
- return new Pokemon(s);
- }
- }
- return null;
+ public static Pokemon generatePokemon()
+ {
+ return new Pokemon(Species.values()[(int) (Math.random() * Species.values().length)]);
}
}
| true | true | public static Pokemon generatePokemon() {
int rand = (int) (Math.random() * Species.values().length);
for(final Species s : Species.values()) {
if(Integer.parseInt(s.getDexNumber()) == rand) {
return new Pokemon(s);
}
}
return null;
}
| public static Pokemon generatePokemon()
{
return new Pokemon(Species.values()[(int) (Math.random() * Species.values().length)]);
}
|
diff --git a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterCompareNode.java b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterCompareNode.java
index 7e42d49ab..a89bb077b 100644
--- a/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterCompareNode.java
+++ b/lttng/org.eclipse.linuxtools.tmf.core/src/org/eclipse/linuxtools/tmf/core/filter/model/TmfFilterCompareNode.java
@@ -1,175 +1,178 @@
/*******************************************************************************
* Copyright (c) 2010 Ericsson
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Patrick Tasse - Initial API and implementation
*******************************************************************************/
package org.eclipse.linuxtools.tmf.core.filter.model;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.linuxtools.tmf.core.event.ITmfEvent;
import org.eclipse.linuxtools.tmf.core.event.TmfTimestamp;
public class TmfFilterCompareNode extends TmfFilterTreeNode {
public static final String NODE_NAME = "COMPARE"; //$NON-NLS-1$
public static final String NOT_ATTR = "not"; //$NON-NLS-1$
public static final String FIELD_ATTR = "field"; //$NON-NLS-1$
public static final String RESULT_ATTR = "result"; //$NON-NLS-1$
public static final String TYPE_ATTR = "type"; //$NON-NLS-1$
public static final String VALUE_ATTR = "value"; //$NON-NLS-1$
public static enum Type {
NUM,
ALPHA,
TIMESTAMP
}
private boolean fNot = false;
private String fField;
private int fResult;
private Type fType = Type.NUM;
private String fValue;
private Number fValueNumber;
private TmfTimestamp fValueTimestamp;
public TmfFilterCompareNode(ITmfFilterTreeNode parent) {
super(parent);
}
public boolean isNot() {
return fNot;
}
public void setNot(boolean not) {
this.fNot = not;
}
public String getField() {
return fField;
}
public void setField(String field) {
this.fField = field;
}
public int getResult() {
return fResult;
}
public void setResult(int result) {
this.fResult = result;
}
public Type getType() {
return fType;
}
public void setType(Type type) {
this.fType = type;
setValue(fValue);
}
public String getValue() {
return fValue;
}
public void setValue(String value) {
this.fValue = value;
fValueNumber = null;
fValueTimestamp = null;
if (value == null) {
return;
}
if (fType == Type.NUM) {
try {
fValueNumber = NumberFormat.getInstance().parse(value).doubleValue();
} catch (ParseException e) {
}
} else if (fType == Type.TIMESTAMP) {
try {
fValueTimestamp = new TmfTimestamp((long) (1E9 * NumberFormat.getInstance().parse(value.toString()).doubleValue()));
} catch (ParseException e) {
}
}
}
@Override
public String getNodeName() {
return NODE_NAME;
}
@Override
public boolean matches(ITmfEvent event) {
Object value = getFieldValue(event, fField);
if (value == null) {
return false ^ fNot;
}
if (fType == Type.NUM) {
if (fValueNumber != null) {
if (value instanceof Number) {
Double valueDouble = ((Number) value).doubleValue();
return (valueDouble.compareTo(fValueNumber.doubleValue()) == fResult) ^ fNot;
} else {
try {
Double valueDouble = NumberFormat.getInstance().parse(value.toString())
.doubleValue();
return (valueDouble.compareTo(fValueNumber.doubleValue()) == fResult)
^ fNot;
} catch (ParseException e) {
}
}
}
} else if (fType == Type.ALPHA) {
String valueString = value.toString();
- return (valueString.compareTo(fValue.toString()) == fResult) ^ fNot;
+ int comp = valueString.compareTo(fValue.toString());
+ if (comp < -1) comp = -1;
+ else if (comp > 1) comp = 1;
+ return (comp == fResult) ^ fNot;
} else if (fType == Type.TIMESTAMP) {
if (fValueTimestamp != null) {
if (value instanceof TmfTimestamp) {
TmfTimestamp valueTimestamp = (TmfTimestamp) value;
return (valueTimestamp.compareTo(fValueTimestamp, false) == fResult) ^ fNot;
} else {
try {
TmfTimestamp valueTimestamp = new TmfTimestamp((long) (1E9 * NumberFormat
.getInstance().parse(value.toString()).doubleValue()));
return (valueTimestamp.compareTo(fValueTimestamp, false) == fResult) ^ fNot;
} catch (ParseException e) {
}
}
}
}
return false ^ fNot;
}
@Override
public List<String> getValidChildren() {
return new ArrayList<String>(0);
}
@Override
public String toString() {
String result = (fResult == 0 ? "= " : fResult < 0 ? "< " : "> "); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
String open = (fType == Type.NUM ? "" : fType == Type.ALPHA ? "\"" : "["); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
String close = (fType == Type.NUM ? "" : fType == Type.ALPHA ? "\"" : "]"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return fField + (fNot ? " not " : " ") + result + open + fValue + close; //$NON-NLS-1$ //$NON-NLS-2$
}
@Override
public ITmfFilterTreeNode clone() {
TmfFilterCompareNode clone = (TmfFilterCompareNode) super.clone();
clone.fField = fField;
clone.setValue(fValue);
return clone;
}
}
| true | true | public boolean matches(ITmfEvent event) {
Object value = getFieldValue(event, fField);
if (value == null) {
return false ^ fNot;
}
if (fType == Type.NUM) {
if (fValueNumber != null) {
if (value instanceof Number) {
Double valueDouble = ((Number) value).doubleValue();
return (valueDouble.compareTo(fValueNumber.doubleValue()) == fResult) ^ fNot;
} else {
try {
Double valueDouble = NumberFormat.getInstance().parse(value.toString())
.doubleValue();
return (valueDouble.compareTo(fValueNumber.doubleValue()) == fResult)
^ fNot;
} catch (ParseException e) {
}
}
}
} else if (fType == Type.ALPHA) {
String valueString = value.toString();
return (valueString.compareTo(fValue.toString()) == fResult) ^ fNot;
} else if (fType == Type.TIMESTAMP) {
if (fValueTimestamp != null) {
if (value instanceof TmfTimestamp) {
TmfTimestamp valueTimestamp = (TmfTimestamp) value;
return (valueTimestamp.compareTo(fValueTimestamp, false) == fResult) ^ fNot;
} else {
try {
TmfTimestamp valueTimestamp = new TmfTimestamp((long) (1E9 * NumberFormat
.getInstance().parse(value.toString()).doubleValue()));
return (valueTimestamp.compareTo(fValueTimestamp, false) == fResult) ^ fNot;
} catch (ParseException e) {
}
}
}
}
return false ^ fNot;
}
| public boolean matches(ITmfEvent event) {
Object value = getFieldValue(event, fField);
if (value == null) {
return false ^ fNot;
}
if (fType == Type.NUM) {
if (fValueNumber != null) {
if (value instanceof Number) {
Double valueDouble = ((Number) value).doubleValue();
return (valueDouble.compareTo(fValueNumber.doubleValue()) == fResult) ^ fNot;
} else {
try {
Double valueDouble = NumberFormat.getInstance().parse(value.toString())
.doubleValue();
return (valueDouble.compareTo(fValueNumber.doubleValue()) == fResult)
^ fNot;
} catch (ParseException e) {
}
}
}
} else if (fType == Type.ALPHA) {
String valueString = value.toString();
int comp = valueString.compareTo(fValue.toString());
if (comp < -1) comp = -1;
else if (comp > 1) comp = 1;
return (comp == fResult) ^ fNot;
} else if (fType == Type.TIMESTAMP) {
if (fValueTimestamp != null) {
if (value instanceof TmfTimestamp) {
TmfTimestamp valueTimestamp = (TmfTimestamp) value;
return (valueTimestamp.compareTo(fValueTimestamp, false) == fResult) ^ fNot;
} else {
try {
TmfTimestamp valueTimestamp = new TmfTimestamp((long) (1E9 * NumberFormat
.getInstance().parse(value.toString()).doubleValue()));
return (valueTimestamp.compareTo(fValueTimestamp, false) == fResult) ^ fNot;
} catch (ParseException e) {
}
}
}
}
return false ^ fNot;
}
|
diff --git a/test/integrationTest/issue3402853/HeaderColumnNameMappingStrategyUserTest.java b/test/integrationTest/issue3402853/HeaderColumnNameMappingStrategyUserTest.java
index 1452401..3ca02c9 100644
--- a/test/integrationTest/issue3402853/HeaderColumnNameMappingStrategyUserTest.java
+++ b/test/integrationTest/issue3402853/HeaderColumnNameMappingStrategyUserTest.java
@@ -1,56 +1,56 @@
package integrationTest.issue3402853;
/**
Copyright 2007 Kyle Miller.
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 au.com.bytecode.opencsv.CSVReader;
import au.com.bytecode.opencsv.bean.CsvToBean;
import au.com.bytecode.opencsv.bean.HeaderColumnNameMappingStrategy;
import org.junit.Test;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.List;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
public class HeaderColumnNameMappingStrategyUserTest {
private static final String USER_FILE = "test/integrationTest/issue3402853/user.csv";
private List<MockUserBean> createTestParseResult() throws FileNotFoundException {
CSVReader reader = new CSVReader(new FileReader(USER_FILE));
HeaderColumnNameMappingStrategy<MockUserBean> strat = new HeaderColumnNameMappingStrategy<MockUserBean>();
strat.setType(MockUserBean.class);
CsvToBean<MockUserBean> csv = new CsvToBean<MockUserBean>();
return csv.parse(strat, reader);
}
@Test
public void testParse() throws FileNotFoundException {
List<MockUserBean> list = createTestParseResult();
assertNotNull(list);
assertEquals(2, list.size());
MockUserBean bean = list.get(0);
assertEquals("[email protected]", bean.getEmail());
- assertEquals("\"\"CHia Sia Ta", bean.getFirst_Name());
+ assertEquals("\\\"CHia Sia Ta", bean.getFirst_Name());
assertEquals("", bean.getLast_Name());
assertEquals("bc1er1163", bean.getProfile_Id());
}
}
| true | true | public void testParse() throws FileNotFoundException {
List<MockUserBean> list = createTestParseResult();
assertNotNull(list);
assertEquals(2, list.size());
MockUserBean bean = list.get(0);
assertEquals("[email protected]", bean.getEmail());
assertEquals("\"\"CHia Sia Ta", bean.getFirst_Name());
assertEquals("", bean.getLast_Name());
assertEquals("bc1er1163", bean.getProfile_Id());
}
| public void testParse() throws FileNotFoundException {
List<MockUserBean> list = createTestParseResult();
assertNotNull(list);
assertEquals(2, list.size());
MockUserBean bean = list.get(0);
assertEquals("[email protected]", bean.getEmail());
assertEquals("\\\"CHia Sia Ta", bean.getFirst_Name());
assertEquals("", bean.getLast_Name());
assertEquals("bc1er1163", bean.getProfile_Id());
}
|
diff --git a/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapRealm.java b/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapRealm.java
index 900f8caa0..a8965eefc 100644
--- a/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapRealm.java
+++ b/gerrit-server/src/main/java/com/google/gerrit/server/auth/ldap/LdapRealm.java
@@ -1,587 +1,590 @@
// Copyright (C) 2009 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.server.auth.ldap;
import com.google.gerrit.reviewdb.Account;
import com.google.gerrit.reviewdb.AccountExternalId;
import com.google.gerrit.reviewdb.AccountGroup;
import com.google.gerrit.reviewdb.AuthType;
import com.google.gerrit.reviewdb.ReviewDb;
import com.google.gerrit.common.data.ParamertizedString;
import com.google.gerrit.server.account.AccountException;
import com.google.gerrit.server.account.AccountState;
import com.google.gerrit.server.account.AuthRequest;
import com.google.gerrit.server.account.EmailExpander;
import com.google.gerrit.server.account.GroupCache;
import com.google.gerrit.server.account.Realm;
import com.google.gerrit.server.cache.Cache;
import com.google.gerrit.server.cache.SelfPopulatingCache;
import com.google.gerrit.server.config.AuthConfig;
import com.google.gerrit.server.config.ConfigUtil;
import com.google.gerrit.server.config.GerritServerConfig;
import com.google.gerrit.util.ssl.BlindSSLSocketFactory;
import com.google.gwtorm.client.OrmException;
import com.google.gwtorm.client.SchemaFactory;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.google.inject.name.Named;
import org.eclipse.jgit.lib.Config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Arrays;
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.Properties;
import java.util.Set;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.net.ssl.SSLSocketFactory;
@Singleton
class LdapRealm implements Realm {
private static final Logger log = LoggerFactory.getLogger(LdapRealm.class);
private static final String LDAP = "com.sun.jndi.ldap.LdapCtxFactory";
private static final String USERNAME = "username";
private static final String GROUPNAME = "groupname";
private final String server;
private final String username;
private final String password;
private final LdapType type;
private final boolean sslVerify;
private final AuthConfig authConfig;
private final SchemaFactory<ReviewDb> schema;
private final EmailExpander emailExpander;
private final ParamertizedString accountFullName;
private final ParamertizedString accountEmailAddress;
private final ParamertizedString accountSshUserName;
private final String accountMemberField;
private final List<LdapQuery> accountQueryList;
private final SelfPopulatingCache<String, Account.Id> usernameCache;
private final GroupCache groupCache;
private boolean groupNeedsAccount;
private final List<String> groupBases;
private final SearchScope groupScope;
private final ParamertizedString groupPattern;
private final List<LdapQuery> groupMemberQueryList;
private final SelfPopulatingCache<String, Set<AccountGroup.Id>> membershipCache;
@Inject
LdapRealm(
final AuthConfig authConfig,
final GroupCache groupCache,
final EmailExpander emailExpander,
final SchemaFactory<ReviewDb> schema,
@Named(LdapModule.GROUP_CACHE) final Cache<String, Set<AccountGroup.Id>> rawGroup,
@Named(LdapModule.USERNAME_CACHE) final Cache<String, Account.Id> rawUsername,
@GerritServerConfig final Config config) {
this.authConfig = authConfig;
this.groupCache = groupCache;
this.emailExpander = emailExpander;
this.schema = schema;
this.server = required(config, "server");
this.username = optional(config, "username");
this.password = optional(config, "password");
this.sslVerify = config.getBoolean("ldap", "sslverify", true);
this.type = discoverLdapType();
groupMemberQueryList = new ArrayList<LdapQuery>();
accountQueryList = new ArrayList<LdapQuery>();
final Set<String> accountAtts = new HashSet<String>();
// Group query
//
groupBases = optionalList(config, "groupBase");
groupScope = scope(config, "groupScope");
- groupPattern =
- paramString(config, "groupPattern", type.groupPattern());
+ groupPattern = paramString(config, "groupPattern", type.groupPattern());
final String groupMemberPattern =
optdef(config, "groupMemberPattern", type.groupMemberPattern());
for (String groupBase : groupBases) {
if (groupMemberPattern != null) {
final LdapQuery groupMemberQuery =
new LdapQuery(groupBase, groupScope, new ParamertizedString(
groupMemberPattern), Collections.<String> emptySet());
if (groupMemberQuery.getParameters().isEmpty()) {
throw new IllegalArgumentException(
"No variables in ldap.groupMemberPattern");
}
for (final String name : groupMemberQuery.getParameters()) {
if (!USERNAME.equals(name)) {
groupNeedsAccount = true;
accountAtts.add(name);
}
}
groupMemberQueryList.add(groupMemberQuery);
}
}
membershipCache =
new SelfPopulatingCache<String, Set<AccountGroup.Id>>(rawGroup) {
@Override
public Set<AccountGroup.Id> createEntry(final String username)
throws Exception {
return queryForGroups(username);
}
@Override
protected Set<AccountGroup.Id> missing(final String key) {
return Collections.emptySet();
}
};
// Account query
//
- accountFullName = paramString(config, "accountFullName", type.accountFullName());
+ accountFullName =
+ paramString(config, "accountFullName", type.accountFullName());
if (accountFullName != null) {
accountAtts.addAll(accountFullName.getParameterNames());
}
- accountEmailAddress = paramString(config, "accountEmailAddress", type.accountEmailAddress());
+ accountEmailAddress =
+ paramString(config, "accountEmailAddress", type.accountEmailAddress());
if (accountEmailAddress != null) {
accountAtts.addAll(accountEmailAddress.getParameterNames());
}
- accountSshUserName = paramString(config, "accountSshUserName", type.accountSshUserName());
+ accountSshUserName =
+ paramString(config, "accountSshUserName", type.accountSshUserName());
if (accountSshUserName != null) {
accountAtts.addAll(accountSshUserName.getParameterNames());
}
- accountMemberField = optdef(config, "accountMemberField", type.accountMemberField());
+ accountMemberField =
+ optdef(config, "accountMemberField", type.accountMemberField());
if (accountMemberField != null) {
accountAtts.add(accountMemberField);
}
final SearchScope accountScope = scope(config, "accountScope");
final String accountPattern =
reqdef(config, "accountPattern", type.accountPattern());
for (String accountBase : requiredList(config, "accountBase")) {
final LdapQuery accountQuery =
new LdapQuery(accountBase, accountScope, new ParamertizedString(
accountPattern), accountAtts);
if (accountQuery.getParameters().isEmpty()) {
throw new IllegalArgumentException(
"No variables in ldap.accountPattern");
}
accountQueryList.add(accountQuery);
}
usernameCache = new SelfPopulatingCache<String, Account.Id>(rawUsername) {
@Override
public Account.Id createEntry(final String username) throws Exception {
return queryForUsername(username);
}
};
}
private static SearchScope scope(final Config c, final String setting) {
return ConfigUtil.getEnum(c, "ldap", null, setting, SearchScope.SUBTREE);
}
private static String optional(final Config config, final String name) {
return config.getString("ldap", null, name);
}
private static String required(final Config config, final String name) {
final String v = optional(config, name);
if (v == null || "".equals(v)) {
throw new IllegalArgumentException("No ldap." + name + " configured");
}
return v;
}
private static List<String> optionalList(final Config config,
final String name) {
String s[] = config.getStringList("ldap", null, name);
return Arrays.asList(s);
}
private static List<String> requiredList(final Config config,
final String name) {
List<String> vlist = optionalList(config, name);
if (vlist.isEmpty()) {
throw new IllegalArgumentException("No ldap " + name + " configured");
}
return vlist;
}
private static String optdef(final Config c, final String n, final String d) {
final String[] v = c.getStringList("ldap", null, n);
if (v == null || v.length == 0) {
return d;
} else if (v[0] == null || "".equals(v[0])) {
return null;
} else {
return v[0];
}
}
private static String reqdef(final Config c, final String n, final String d) {
final String v = optdef(c, n, d);
if (v == null) {
throw new IllegalArgumentException("No ldap." + n + " configured");
}
return v;
}
private static ParamertizedString paramString(Config c, String n, String d) {
String expression = optdef(c, n, d);
if (expression == null) {
return null;
} else if (expression.contains("${")) {
return new ParamertizedString(expression);
} else {
return new ParamertizedString("${" + expression + "}");
}
}
@Override
public boolean allowsEdit(final Account.FieldName field) {
switch (field) {
case FULL_NAME:
return accountFullName == null; // only if not obtained from LDAP
case SSH_USER_NAME:
return accountSshUserName == null; // only if not obtained from LDAP
default:
return true;
}
}
private static String apply(ParamertizedString p, LdapQuery.Result m)
throws NamingException {
if (p == null) {
return null;
}
final Map<String, String> values = new HashMap<String, String>();
for (final String name : m.attributes()) {
values.put(name, m.get(name));
}
String r = p.replace(values);
return r.isEmpty() ? null : r;
}
public AuthRequest authenticate(final AuthRequest who)
throws AccountException {
final String username = who.getLocalUser();
try {
final DirContext ctx = open();
try {
final LdapQuery.Result m = findAccount(ctx, username);
if (authConfig.getAuthType() == AuthType.LDAP) {
// We found the user account, but we need to verify
// the password matches it before we can continue.
//
authenticate(m.getDN(), who.getPassword());
}
who.setDisplayName(apply(accountFullName, m));
who.setSshUserName(apply(accountSshUserName, m));
if (accountEmailAddress != null) {
who.setEmailAddress(apply(accountEmailAddress, m));
} else if (emailExpander.canExpand(username)) {
// If LDAP cannot give us a valid email address for this user
// try expanding it through the older email expander code which
// assumes a user name within a domain.
//
who.setEmailAddress(emailExpander.expand(username));
}
// Fill the cache with the user's current groups. We've already
// spent the cost to open the LDAP connection, we might as well
// do one more call to get their group membership. Since we are
// in the middle of authenticating the user, its likely we will
// need to know what access rights they have soon.
//
membershipCache.put(username, queryForGroups(ctx, username, m));
return who;
} finally {
try {
ctx.close();
} catch (NamingException e) {
log.warn("Cannot close LDAP query handle", e);
}
}
} catch (NamingException e) {
log.error("Cannot query LDAP to autenticate user", e);
throw new AccountException("Cannot query LDAP for account", e);
}
}
@Override
public void onCreateAccount(final AuthRequest who, final Account account) {
usernameCache.put(who.getLocalUser(), account.getId());
}
@Override
public Set<AccountGroup.Id> groups(final AccountState who) {
final HashSet<AccountGroup.Id> r = new HashSet<AccountGroup.Id>();
r.addAll(membershipCache.get(findId(who.getExternalIds())));
r.addAll(who.getInternalGroups());
return r;
}
private Set<AccountGroup.Id> queryForGroups(final String username)
throws NamingException, AccountException {
final DirContext ctx = open();
try {
return queryForGroups(ctx, username, null);
} finally {
try {
ctx.close();
} catch (NamingException e) {
log.warn("Cannot close LDAP query handle", e);
}
}
}
private Set<AccountGroup.Id> queryForGroups(final DirContext ctx,
final String username, LdapQuery.Result account) throws NamingException,
AccountException {
final Set<String> groupDNs = new HashSet<String>();
if (!groupMemberQueryList.isEmpty()) {
final HashMap<String, String> params = new HashMap<String, String>();
if (groupNeedsAccount) {
if (account == null) {
account = findAccount(ctx, username);
}
for (final String name : groupMemberQueryList.get(0).getParameters()) {
params.put(name, account.get(name));
}
}
params.put(USERNAME, username);
for (LdapQuery groupMemberQuery : groupMemberQueryList) {
for (LdapQuery.Result r : groupMemberQuery.query(ctx, params)) {
groupDNs.add(r.getDN());
}
}
}
if (accountMemberField != null) {
if (account == null) {
account = findAccount(ctx, username);
}
final Attribute groupAtt = account.getAll(accountMemberField);
if (groupAtt != null) {
final NamingEnumeration<?> groups = groupAtt.getAll();
while (groups.hasMore()) {
recursivelyExpandGroups(groupDNs, ctx, (String) groups.next());
}
}
}
final Set<AccountGroup.Id> actual = new HashSet<AccountGroup.Id>();
for (String dn : groupDNs) {
final AccountGroup group;
group = groupCache.get(new AccountGroup.ExternalNameKey(dn));
if (group != null && group.getType() == AccountGroup.Type.LDAP) {
actual.add(group.getId());
}
}
if (actual.isEmpty()) {
return Collections.emptySet();
} else {
return Collections.unmodifiableSet(actual);
}
}
private void recursivelyExpandGroups(final Set<String> groupDNs,
final DirContext ctx, final String groupDN) {
if (groupDNs.add(groupDN)) {
// Recursively identify the groups it is a member of.
//
try {
final Attribute in = ctx.getAttributes(groupDN).get(accountMemberField);
if (in != null) {
final NamingEnumeration<?> groups = in.getAll();
while (groups.hasMore()) {
recursivelyExpandGroups(groupDNs, ctx, (String) groups.next());
}
}
} catch (NamingException e) {
log.warn("Could not find group " + groupDN, e);
}
}
}
private static String findId(final Collection<AccountExternalId> ids) {
for (final AccountExternalId i : ids) {
if (i.isScheme(AccountExternalId.SCHEME_GERRIT)) {
return i.getSchemeRest(AccountExternalId.SCHEME_GERRIT);
}
}
return null;
}
@Override
public Account.Id lookup(final String accountName) {
return usernameCache.get(accountName);
}
@Override
public Set<AccountGroup.ExternalNameKey> lookupGroups(String name) {
final Set<AccountGroup.ExternalNameKey> out;
final ParamertizedString filter =
ParamertizedString.asis(groupPattern.replace(GROUPNAME, name)
.toString());
final Map<String, String> params = Collections.<String, String> emptyMap();
out = new HashSet<AccountGroup.ExternalNameKey>();
try {
final DirContext ctx = open();
try {
for (String groupBase : groupBases) {
final LdapQuery query =
new LdapQuery(groupBase, groupScope, filter, Collections
.<String> emptySet());
for (LdapQuery.Result res : query.query(ctx, params)) {
out.add(new AccountGroup.ExternalNameKey(res.getDN()));
}
}
} finally {
try {
ctx.close();
} catch (NamingException e) {
log.warn("Cannot close LDAP query handle", e);
}
}
} catch (NamingException e) {
log.warn("Cannot query LDAP for groups matching requested name", e);
}
return out;
}
private Account.Id queryForUsername(final String username) {
try {
final ReviewDb db = schema.open();
try {
final String id = AccountExternalId.SCHEME_GERRIT + username;
final AccountExternalId extId =
db.accountExternalIds().get(new AccountExternalId.Key(id));
return extId != null ? extId.getAccountId() : null;
} finally {
db.close();
}
} catch (OrmException e) {
log.warn("Cannot query for username in database", e);
return null;
}
}
private Properties createContextProperties() {
final Properties env = new Properties();
env.put(Context.INITIAL_CONTEXT_FACTORY, LDAP);
env.put(Context.PROVIDER_URL, server);
if (server.startsWith("ldaps:") && !sslVerify) {
Class<? extends SSLSocketFactory> factory = BlindSSLSocketFactory.class;
env.put("java.naming.ldap.factory.socket", factory.getName());
}
return env;
}
private DirContext open() throws NamingException {
final Properties env = createContextProperties();
if (username != null) {
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, username);
env.put(Context.SECURITY_CREDENTIALS, password != null ? password : "");
}
return new InitialDirContext(env);
}
private void authenticate(String dn, String password) throws AccountException {
final Properties env = createContextProperties();
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, dn);
env.put(Context.SECURITY_CREDENTIALS, password != null ? password : "");
try {
new InitialDirContext(env).close();
} catch (NamingException e) {
throw new AccountException("Incorrect username or password", e);
}
}
private LdapType discoverLdapType() {
try {
final DirContext ctx = open();
try {
return LdapType.guessType(ctx);
} finally {
ctx.close();
}
} catch (NamingException e) {
log.warn("Cannot discover type of LDAP server at " + server
+ ", assuming the server is RFC 2307 compliant.", e);
return LdapType.RFC_2307;
}
}
private LdapQuery.Result findAccount(final DirContext ctx,
final String username) throws NamingException, AccountException {
final HashMap<String, String> params = new HashMap<String, String>();
params.put(USERNAME, username);
final List<LdapQuery.Result> res = new ArrayList<LdapQuery.Result>();
for (LdapQuery accountQuery : accountQueryList) {
res.addAll(accountQuery.query(ctx, params));
}
switch (res.size()) {
case 0:
throw new AccountException("No such user:" + username);
case 1:
return res.get(0);
default:
throw new AccountException("Duplicate users: " + username);
}
}
}
| false | true | LdapRealm(
final AuthConfig authConfig,
final GroupCache groupCache,
final EmailExpander emailExpander,
final SchemaFactory<ReviewDb> schema,
@Named(LdapModule.GROUP_CACHE) final Cache<String, Set<AccountGroup.Id>> rawGroup,
@Named(LdapModule.USERNAME_CACHE) final Cache<String, Account.Id> rawUsername,
@GerritServerConfig final Config config) {
this.authConfig = authConfig;
this.groupCache = groupCache;
this.emailExpander = emailExpander;
this.schema = schema;
this.server = required(config, "server");
this.username = optional(config, "username");
this.password = optional(config, "password");
this.sslVerify = config.getBoolean("ldap", "sslverify", true);
this.type = discoverLdapType();
groupMemberQueryList = new ArrayList<LdapQuery>();
accountQueryList = new ArrayList<LdapQuery>();
final Set<String> accountAtts = new HashSet<String>();
// Group query
//
groupBases = optionalList(config, "groupBase");
groupScope = scope(config, "groupScope");
groupPattern =
paramString(config, "groupPattern", type.groupPattern());
final String groupMemberPattern =
optdef(config, "groupMemberPattern", type.groupMemberPattern());
for (String groupBase : groupBases) {
if (groupMemberPattern != null) {
final LdapQuery groupMemberQuery =
new LdapQuery(groupBase, groupScope, new ParamertizedString(
groupMemberPattern), Collections.<String> emptySet());
if (groupMemberQuery.getParameters().isEmpty()) {
throw new IllegalArgumentException(
"No variables in ldap.groupMemberPattern");
}
for (final String name : groupMemberQuery.getParameters()) {
if (!USERNAME.equals(name)) {
groupNeedsAccount = true;
accountAtts.add(name);
}
}
groupMemberQueryList.add(groupMemberQuery);
}
}
membershipCache =
new SelfPopulatingCache<String, Set<AccountGroup.Id>>(rawGroup) {
@Override
public Set<AccountGroup.Id> createEntry(final String username)
throws Exception {
return queryForGroups(username);
}
@Override
protected Set<AccountGroup.Id> missing(final String key) {
return Collections.emptySet();
}
};
// Account query
//
accountFullName = paramString(config, "accountFullName", type.accountFullName());
if (accountFullName != null) {
accountAtts.addAll(accountFullName.getParameterNames());
}
accountEmailAddress = paramString(config, "accountEmailAddress", type.accountEmailAddress());
if (accountEmailAddress != null) {
accountAtts.addAll(accountEmailAddress.getParameterNames());
}
accountSshUserName = paramString(config, "accountSshUserName", type.accountSshUserName());
if (accountSshUserName != null) {
accountAtts.addAll(accountSshUserName.getParameterNames());
}
accountMemberField = optdef(config, "accountMemberField", type.accountMemberField());
if (accountMemberField != null) {
accountAtts.add(accountMemberField);
}
final SearchScope accountScope = scope(config, "accountScope");
final String accountPattern =
reqdef(config, "accountPattern", type.accountPattern());
for (String accountBase : requiredList(config, "accountBase")) {
final LdapQuery accountQuery =
new LdapQuery(accountBase, accountScope, new ParamertizedString(
accountPattern), accountAtts);
if (accountQuery.getParameters().isEmpty()) {
throw new IllegalArgumentException(
"No variables in ldap.accountPattern");
}
accountQueryList.add(accountQuery);
}
usernameCache = new SelfPopulatingCache<String, Account.Id>(rawUsername) {
@Override
public Account.Id createEntry(final String username) throws Exception {
return queryForUsername(username);
}
};
}
| LdapRealm(
final AuthConfig authConfig,
final GroupCache groupCache,
final EmailExpander emailExpander,
final SchemaFactory<ReviewDb> schema,
@Named(LdapModule.GROUP_CACHE) final Cache<String, Set<AccountGroup.Id>> rawGroup,
@Named(LdapModule.USERNAME_CACHE) final Cache<String, Account.Id> rawUsername,
@GerritServerConfig final Config config) {
this.authConfig = authConfig;
this.groupCache = groupCache;
this.emailExpander = emailExpander;
this.schema = schema;
this.server = required(config, "server");
this.username = optional(config, "username");
this.password = optional(config, "password");
this.sslVerify = config.getBoolean("ldap", "sslverify", true);
this.type = discoverLdapType();
groupMemberQueryList = new ArrayList<LdapQuery>();
accountQueryList = new ArrayList<LdapQuery>();
final Set<String> accountAtts = new HashSet<String>();
// Group query
//
groupBases = optionalList(config, "groupBase");
groupScope = scope(config, "groupScope");
groupPattern = paramString(config, "groupPattern", type.groupPattern());
final String groupMemberPattern =
optdef(config, "groupMemberPattern", type.groupMemberPattern());
for (String groupBase : groupBases) {
if (groupMemberPattern != null) {
final LdapQuery groupMemberQuery =
new LdapQuery(groupBase, groupScope, new ParamertizedString(
groupMemberPattern), Collections.<String> emptySet());
if (groupMemberQuery.getParameters().isEmpty()) {
throw new IllegalArgumentException(
"No variables in ldap.groupMemberPattern");
}
for (final String name : groupMemberQuery.getParameters()) {
if (!USERNAME.equals(name)) {
groupNeedsAccount = true;
accountAtts.add(name);
}
}
groupMemberQueryList.add(groupMemberQuery);
}
}
membershipCache =
new SelfPopulatingCache<String, Set<AccountGroup.Id>>(rawGroup) {
@Override
public Set<AccountGroup.Id> createEntry(final String username)
throws Exception {
return queryForGroups(username);
}
@Override
protected Set<AccountGroup.Id> missing(final String key) {
return Collections.emptySet();
}
};
// Account query
//
accountFullName =
paramString(config, "accountFullName", type.accountFullName());
if (accountFullName != null) {
accountAtts.addAll(accountFullName.getParameterNames());
}
accountEmailAddress =
paramString(config, "accountEmailAddress", type.accountEmailAddress());
if (accountEmailAddress != null) {
accountAtts.addAll(accountEmailAddress.getParameterNames());
}
accountSshUserName =
paramString(config, "accountSshUserName", type.accountSshUserName());
if (accountSshUserName != null) {
accountAtts.addAll(accountSshUserName.getParameterNames());
}
accountMemberField =
optdef(config, "accountMemberField", type.accountMemberField());
if (accountMemberField != null) {
accountAtts.add(accountMemberField);
}
final SearchScope accountScope = scope(config, "accountScope");
final String accountPattern =
reqdef(config, "accountPattern", type.accountPattern());
for (String accountBase : requiredList(config, "accountBase")) {
final LdapQuery accountQuery =
new LdapQuery(accountBase, accountScope, new ParamertizedString(
accountPattern), accountAtts);
if (accountQuery.getParameters().isEmpty()) {
throw new IllegalArgumentException(
"No variables in ldap.accountPattern");
}
accountQueryList.add(accountQuery);
}
usernameCache = new SelfPopulatingCache<String, Account.Id>(rawUsername) {
@Override
public Account.Id createEntry(final String username) throws Exception {
return queryForUsername(username);
}
};
}
|
diff --git a/otherblocks/src/com/sargant/bukkit/otherblocks/OtherBlocks.java b/otherblocks/src/com/sargant/bukkit/otherblocks/OtherBlocks.java
index 373176c..f4a6c9c 100644
--- a/otherblocks/src/com/sargant/bukkit/otherblocks/OtherBlocks.java
+++ b/otherblocks/src/com/sargant/bukkit/otherblocks/OtherBlocks.java
@@ -1,152 +1,155 @@
package com.sargant.bukkit.otherblocks;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.logging.Logger;
import org.bukkit.DyeColor;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Priority;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginLoader;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.PluginManager;
public class OtherBlocks extends JavaPlugin
{
protected List<OtherBlocksContainer> transformList = new ArrayList<OtherBlocksContainer>();
protected Random rng = new Random();
private final OtherBlocksBlockListener blockListener = new OtherBlocksBlockListener(this);
private final Logger log = Logger.getLogger("Minecraft");
//These are fixes for the broken getMaxDurability and getMaxStackSize in Bukkit
public short getFixedMaxDurability(Material m) {
// If the maxstacksize is -1, then the values are the wrong way round
return (short) ((m.getMaxStackSize() < 1) ? m.getMaxStackSize() : m.getMaxDurability());
}
public int getFixedMaxStackSize(Material m) {
return (int) ((m.getMaxStackSize() < 1) ? m.getMaxDurability() : m.getMaxStackSize());
}
public OtherBlocks(PluginLoader pluginLoader, Server instance, PluginDescriptionFile desc, File folder, File plugin, ClassLoader cLoader)
{
super(pluginLoader, instance, desc, folder, plugin, cLoader);
// Initialize and read in the YAML file
folder.mkdirs();
File yml = new File(getDataFolder(), "config.yml");
if (!yml.exists())
{
try {
yml.createNewFile();
log.info("Created an empty file " + getDataFolder() +"/config.yml, please edit it!");
getConfiguration().setProperty("otherblocks", null);
getConfiguration().save();
} catch (IOException ex){
log.warning(getDescription().getName() + ": could not generate config.yml. Are the file permissions OK?");
}
}
// Load in the values from the configuration file
List <String> keys;
try {
keys = getConfiguration().getKeys(null);
} catch(NullPointerException ex) {
log.warning(getDescription().getName() + ": no parent key not found");
return;
}
if(!keys.contains("otherblocks"))
{
log.warning(getDescription().getName() + ": no 'otherblocks' key found");
return;
}
keys.clear();
keys = getConfiguration().getKeys("otherblocks");
if(null == keys)
{
log.info(getDescription().getName() + ": no values found in config file!");
return;
}
for(String s : keys) {
List<Object> original_children = getConfiguration().getList("otherblocks."+s);
if(original_children == null) {
log.warning("Block \""+s+"\" has no children. Have you included the dash?");
continue;
}
for(Object o : original_children) {
if(o instanceof HashMap<?,?>) {
OtherBlocksContainer bt = new OtherBlocksContainer();
try {
@SuppressWarnings("unchecked")
HashMap<String, Object> m = (HashMap<String, Object>) o;
bt.original = Material.valueOf(s);
String toolString = String.class.cast(m.get("tool"));
if(toolString.equalsIgnoreCase("DYE")) { toolString = "INK_SACK"; }
bt.tool = (toolString.equalsIgnoreCase("ALL") ? null : Material.valueOf(toolString));
bt.dropped = Material.valueOf(String.class.cast(m.get("drop")));
Integer dropQuantity = Integer.class.cast(m.get("quantity"));
bt.quantity = (dropQuantity == null || dropQuantity <= 0) ? 1 : dropQuantity;
Integer toolDamage = Integer.class.cast(m.get("damage"));
bt.damage = (toolDamage == null || toolDamage < 0) ? 1 : toolDamage;
Integer dropChance = Integer.class.cast(m.get("chance"));
bt.chance = (dropChance == null || dropChance < 0 || dropChance > 100) ? 100 : dropChance;
- DyeColor dropColor = DyeColor.valueOf(String.class.cast(m.get("color")));
- bt.color = ((dropColor == null) ? null : dropColor.getData());
+ String dropColor = String.class.cast(m.get("color"));
+ bt.color = ((dropColor == null) ? 0 : DyeColor.valueOf(dropColor).getData());
} catch(IllegalArgumentException ex) {
log.warning("Error while processing block: " + s);
continue;
+ } catch(NullPointerException ex) {
+ log.warning("Error while processing block: " + s);
+ continue;
}
transformList.add(bt);
log.info(getDescription().getName() + ": " +
(bt.tool == null ? "ALL TOOLS" : bt.tool.toString()) + " + " +
bt.original.toString() + " now drops " +
bt.quantity.toString() + "x " +
bt.dropped.toString() + " with " +
bt.chance.toString() + "% chance");
}
}
}
}
public void onDisable()
{
log.info(getDescription().getName() + " " + getDescription().getVersion() + " unloaded.");
}
public void onEnable()
{
PluginManager pm = getServer().getPluginManager();
pm.registerEvent(Event.Type.BLOCK_BREAK, blockListener, Priority.Lowest, this);
log.info(getDescription().getName() + " " + getDescription().getVersion() + " loaded.");
}
}
| false | true | public OtherBlocks(PluginLoader pluginLoader, Server instance, PluginDescriptionFile desc, File folder, File plugin, ClassLoader cLoader)
{
super(pluginLoader, instance, desc, folder, plugin, cLoader);
// Initialize and read in the YAML file
folder.mkdirs();
File yml = new File(getDataFolder(), "config.yml");
if (!yml.exists())
{
try {
yml.createNewFile();
log.info("Created an empty file " + getDataFolder() +"/config.yml, please edit it!");
getConfiguration().setProperty("otherblocks", null);
getConfiguration().save();
} catch (IOException ex){
log.warning(getDescription().getName() + ": could not generate config.yml. Are the file permissions OK?");
}
}
// Load in the values from the configuration file
List <String> keys;
try {
keys = getConfiguration().getKeys(null);
} catch(NullPointerException ex) {
log.warning(getDescription().getName() + ": no parent key not found");
return;
}
if(!keys.contains("otherblocks"))
{
log.warning(getDescription().getName() + ": no 'otherblocks' key found");
return;
}
keys.clear();
keys = getConfiguration().getKeys("otherblocks");
if(null == keys)
{
log.info(getDescription().getName() + ": no values found in config file!");
return;
}
for(String s : keys) {
List<Object> original_children = getConfiguration().getList("otherblocks."+s);
if(original_children == null) {
log.warning("Block \""+s+"\" has no children. Have you included the dash?");
continue;
}
for(Object o : original_children) {
if(o instanceof HashMap<?,?>) {
OtherBlocksContainer bt = new OtherBlocksContainer();
try {
@SuppressWarnings("unchecked")
HashMap<String, Object> m = (HashMap<String, Object>) o;
bt.original = Material.valueOf(s);
String toolString = String.class.cast(m.get("tool"));
if(toolString.equalsIgnoreCase("DYE")) { toolString = "INK_SACK"; }
bt.tool = (toolString.equalsIgnoreCase("ALL") ? null : Material.valueOf(toolString));
bt.dropped = Material.valueOf(String.class.cast(m.get("drop")));
Integer dropQuantity = Integer.class.cast(m.get("quantity"));
bt.quantity = (dropQuantity == null || dropQuantity <= 0) ? 1 : dropQuantity;
Integer toolDamage = Integer.class.cast(m.get("damage"));
bt.damage = (toolDamage == null || toolDamage < 0) ? 1 : toolDamage;
Integer dropChance = Integer.class.cast(m.get("chance"));
bt.chance = (dropChance == null || dropChance < 0 || dropChance > 100) ? 100 : dropChance;
DyeColor dropColor = DyeColor.valueOf(String.class.cast(m.get("color")));
bt.color = ((dropColor == null) ? null : dropColor.getData());
} catch(IllegalArgumentException ex) {
log.warning("Error while processing block: " + s);
continue;
}
transformList.add(bt);
log.info(getDescription().getName() + ": " +
(bt.tool == null ? "ALL TOOLS" : bt.tool.toString()) + " + " +
bt.original.toString() + " now drops " +
bt.quantity.toString() + "x " +
bt.dropped.toString() + " with " +
bt.chance.toString() + "% chance");
}
}
}
| public OtherBlocks(PluginLoader pluginLoader, Server instance, PluginDescriptionFile desc, File folder, File plugin, ClassLoader cLoader)
{
super(pluginLoader, instance, desc, folder, plugin, cLoader);
// Initialize and read in the YAML file
folder.mkdirs();
File yml = new File(getDataFolder(), "config.yml");
if (!yml.exists())
{
try {
yml.createNewFile();
log.info("Created an empty file " + getDataFolder() +"/config.yml, please edit it!");
getConfiguration().setProperty("otherblocks", null);
getConfiguration().save();
} catch (IOException ex){
log.warning(getDescription().getName() + ": could not generate config.yml. Are the file permissions OK?");
}
}
// Load in the values from the configuration file
List <String> keys;
try {
keys = getConfiguration().getKeys(null);
} catch(NullPointerException ex) {
log.warning(getDescription().getName() + ": no parent key not found");
return;
}
if(!keys.contains("otherblocks"))
{
log.warning(getDescription().getName() + ": no 'otherblocks' key found");
return;
}
keys.clear();
keys = getConfiguration().getKeys("otherblocks");
if(null == keys)
{
log.info(getDescription().getName() + ": no values found in config file!");
return;
}
for(String s : keys) {
List<Object> original_children = getConfiguration().getList("otherblocks."+s);
if(original_children == null) {
log.warning("Block \""+s+"\" has no children. Have you included the dash?");
continue;
}
for(Object o : original_children) {
if(o instanceof HashMap<?,?>) {
OtherBlocksContainer bt = new OtherBlocksContainer();
try {
@SuppressWarnings("unchecked")
HashMap<String, Object> m = (HashMap<String, Object>) o;
bt.original = Material.valueOf(s);
String toolString = String.class.cast(m.get("tool"));
if(toolString.equalsIgnoreCase("DYE")) { toolString = "INK_SACK"; }
bt.tool = (toolString.equalsIgnoreCase("ALL") ? null : Material.valueOf(toolString));
bt.dropped = Material.valueOf(String.class.cast(m.get("drop")));
Integer dropQuantity = Integer.class.cast(m.get("quantity"));
bt.quantity = (dropQuantity == null || dropQuantity <= 0) ? 1 : dropQuantity;
Integer toolDamage = Integer.class.cast(m.get("damage"));
bt.damage = (toolDamage == null || toolDamage < 0) ? 1 : toolDamage;
Integer dropChance = Integer.class.cast(m.get("chance"));
bt.chance = (dropChance == null || dropChance < 0 || dropChance > 100) ? 100 : dropChance;
String dropColor = String.class.cast(m.get("color"));
bt.color = ((dropColor == null) ? 0 : DyeColor.valueOf(dropColor).getData());
} catch(IllegalArgumentException ex) {
log.warning("Error while processing block: " + s);
continue;
} catch(NullPointerException ex) {
log.warning("Error while processing block: " + s);
continue;
}
transformList.add(bt);
log.info(getDescription().getName() + ": " +
(bt.tool == null ? "ALL TOOLS" : bt.tool.toString()) + " + " +
bt.original.toString() + " now drops " +
bt.quantity.toString() + "x " +
bt.dropped.toString() + " with " +
bt.chance.toString() + "% chance");
}
}
}
|
diff --git a/component/src/java/org/sakaiproject/tool/assessment/qti/helper/ExtractionHelper.java b/component/src/java/org/sakaiproject/tool/assessment/qti/helper/ExtractionHelper.java
index b39fee3ff..04d86d253 100755
--- a/component/src/java/org/sakaiproject/tool/assessment/qti/helper/ExtractionHelper.java
+++ b/component/src/java/org/sakaiproject/tool/assessment/qti/helper/ExtractionHelper.java
@@ -1,1715 +1,1724 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003-2005 The Regents of the University of Michigan, Trustees of Indiana University,
* Board of Trustees of the Leland Stanford, Jr., University, and The MIT Corporation
*
* Licensed under the Educational Community License Version 1.0 (the "License");
* By obtaining, using and/or copying this Original Work, you agree that you have read,
* understand, and will comply with the terms and conditions of the Educational Community License.
* You may obtain a copy of the License at:
*
* http://cvs.sakaiproject.org/licenses/license_1_0.html
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**********************************************************************************/
package org.sakaiproject.tool.assessment.qti.helper;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.faces.context.FacesContext;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.xml.sax.SAXException;
import org.sakaiproject.tool.assessment.data.dao.assessment.Answer;
import org.sakaiproject.tool.assessment.data.dao.assessment.AnswerFeedback;
import org.sakaiproject.tool.assessment.data.dao.assessment.AssessmentAccessControl;
import org.sakaiproject.tool.assessment.data.dao.assessment.AssessmentFeedback;
import org.sakaiproject.tool.assessment.data.dao.assessment.EvaluationModel;
import org.sakaiproject.tool.assessment.data.dao.assessment.ItemText;
import org.sakaiproject.tool.assessment.data.dao.assessment.SecuredIPAddress;
import org.sakaiproject.tool.assessment.data.ifc.assessment.AnswerFeedbackIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.AssessmentAccessControlIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemDataIfc;
import org.sakaiproject.tool.assessment.data.ifc.shared.TypeIfc;
import org.sakaiproject.tool.assessment.facade.AssessmentFacade;
import org.sakaiproject.tool.assessment.facade.ItemFacade;
import org.sakaiproject.tool.assessment.facade.SectionFacade;
import org.sakaiproject.tool.assessment.qti.asi.ASIBaseClass;
import org.sakaiproject.tool.assessment.qti.asi.Assessment;
import org.sakaiproject.tool.assessment.qti.asi.Item;
import org.sakaiproject.tool.assessment.qti.asi.Section;
import org.sakaiproject.tool.assessment.qti.constants.AuthoringConstantStrings;
import org.sakaiproject.tool.assessment.qti.constants.QTIVersion;
import org.sakaiproject.tool.assessment.qti.exception.Iso8601FormatException;
import org.sakaiproject.tool.assessment.qti.helper.item.ItemTypeExtractionStrategy;
import org.sakaiproject.tool.assessment.qti.util.Iso8601DateFormat;
import org.sakaiproject.tool.assessment.qti.util.Iso8601TimeInterval;
import org.sakaiproject.tool.assessment.qti.util.XmlMapper;
import org.sakaiproject.tool.assessment.qti.util.XmlUtil;
import org.sakaiproject.tool.assessment.data.ifc.assessment.AssessmentBaseIfc;
import org.sakaiproject.tool.assessment.services.assessment.AssessmentService;
/**
* <p>Has helper methods for data extraction (import) from QTI</p>
* <p> </p>
* <p>Copyright: Copyright (c) 2005 Sakai</p>
* @author Ed Smiley [email protected]
* @version $Id$
*/
public class ExtractionHelper
{
private static final String QTI_VERSION_1_2_PATH = "v1p2";
private static final String QTI_VERSION_2_0_PATH = "v2p0";
private static final String TRANSFORM_PATH =
"/xml/xsl/dataTransform/import";
private static final String ASSESSMENT_TRANSFORM =
"extractAssessment.xsl";
private static final String SECTION_TRANSFORM = "extractSection.xsl";
private static final String ITEM_TRANSFORM = "extractItem.xsl";
private static Log log = LogFactory.getLog(ExtractionHelper.class);
private int qtiVersion = QTIVersion.VERSION_1_2;
private String overridePath = null; // override defaults and settings
private String FIB_BLANK_INDICATOR = " {} ";
// versioning title string that it will look for/use, followed by a number
private static final String VERSION_START = " - ";
/**
* @deprecated
*/
public ExtractionHelper()
{
this.setQtiVersion(QTIVersion.VERSION_1_2);
}
/**
* Get ExtractionHelper for QTIVersion.VERSION_1_2
* or QTIVersion.VERSION_2_0
* @param qtiVersion
*/
public ExtractionHelper(int qtiVersion)
{
this.setQtiVersion(qtiVersion);
}
/**
* Path to XSL transform code.
* @return context-relative path to XSL transform code.
*/
public String getTransformPath()
{
// first check to see if normal computed path has been overridden
if (overridePath != null)
{
return overridePath;
}
return TRANSFORM_PATH + "/" + getQtiPath();
}
private String getQtiPath()
{
return qtiVersion == QTIVersion.VERSION_1_2 ? QTI_VERSION_1_2_PATH :
QTI_VERSION_2_0_PATH;
}
/**
* Get QTI version flag.
* Either QTIVersion.VERSION_1_2 or QTIVersion.VERSION_2_0;
* @return QTI version flag
*/
public int getQtiVersion()
{
return qtiVersion;
}
/**
* Set QTI version flag.
* Either QTIVersion.VERSION_1_2 or QTIVersion.VERSION_2_0;
* @param qtiVersion
*/
public void setQtiVersion(int qtiVersion)
{
if (!QTIVersion.isValid(qtiVersion))
{
throw new IllegalArgumentException("NOT Legal Qti Version.");
}
this.qtiVersion = qtiVersion;
}
/**
* Get an XML document for the transform
* @param template
* @return
*/
public Document getTransformDocument(String template)
{
Document document = null;
if (!isOKtransform(template))
{
throw new IllegalArgumentException("NOT valid template.");
}
String templateContextPath = this.getTransformPath() + "/" + template;
FacesContext context = FacesContext.getCurrentInstance();
if (context == null)
{
return XmlUtil.readDocument(templateContextPath);
}
document = XmlUtil.readDocument(context, templateContextPath);
return document;
}
/**
* Get map of data to set from assessment XML
* @param assessmentXml
* @return a Map
*/
public Map mapAssessment(Assessment assessmentXml)
{
log.debug("inside: mapAssessment");
return map(ASSESSMENT_TRANSFORM, assessmentXml);
}
/**
* Get map of data to set from section XML
* @param sectionXml
* @return a Map
*/
public Map mapSection(Section sectionXml)
{
return map(SECTION_TRANSFORM, sectionXml);
}
/**
* Get map of data to set from item XML
* @param itemXml
* @return a Map
*/
public Map mapItem(Item itemXml)
{
return map(ITEM_TRANSFORM, itemXml);
}
/**
* Helper method
* @param transformType ASSESSMENT_TRANSFORM, SECTION_TRANSFORM, ITEM_TRANSFORM
* @param asi ASIBaseClass: Assessment, Section, or Item XML
* @return
*/
private Map map(String transformType, ASIBaseClass asi)
{
if (!isOKasi(asi))
{
throw new IllegalArgumentException("Incorrect ASI subclass.");
}
if (!isOKtransform(transformType))
{
throw new IllegalArgumentException("Incorrect transform: " +
transformType + ".");
}
Map map = null;
try
{
Document transform = getTransformDocument(transformType);
Document xml = asi.getDocument();
Document model = XmlUtil.transformDocument(xml, transform);
map = XmlMapper.map(model);
}
catch (IOException ex)
{
log.error(ex);
ex.printStackTrace(System.out);
}
catch (SAXException ex)
{
log.error(ex);
ex.printStackTrace(System.out);
}
catch (ParserConfigurationException ex)
{
log.error(ex);
ex.printStackTrace(System.out);
}
return map;
}
/**
* Look up a List of Section XML from Assessment Xml
* @return a List of Section XML objects
*/
public List getSectionXmlList(Assessment assessmentXml)
{
List nodeList = assessmentXml.selectNodes("//section");
List sectionXmlList = new ArrayList();
// now convert our list of Nodes to a list of section xml
for (int i = 0; i < nodeList.size(); i++)
{
try
{
Node node = (Node) nodeList.get(i);
// create a document for a section xml object
Document sectionDoc = XmlUtil.createDocument();
// Make a copy for inserting into the new document
Node importNode = sectionDoc.importNode(node, true);
// Insert the copy into sectionDoc
sectionDoc.appendChild(importNode);
Section sectionXml = new Section(sectionDoc,
this.getQtiVersion());
// add the new section xml object to the list
sectionXmlList.add(sectionXml);
}
catch (DOMException ex)
{
log.error(ex);
ex.printStackTrace(System.out);
}
}
return sectionXmlList;
}
/**
* Look up a List of Item XML from Section Xml
* @param Section sectionXml
* @return a List of Item XML objects
*/
public List getItemXmlList(Section sectionXml)
{
String itemElementName =
qtiVersion == QTIVersion.VERSION_1_2 ? "//item" : "//assessmentItem";
// now convert our list of Nodes to a list of section xml
List nodeList = sectionXml.selectNodes(itemElementName);
List itemXmlList = new ArrayList();
for (int i = 0; i < nodeList.size(); i++)
{
try
{
Node node = (Node) nodeList.get(i);
// create a document for a item xml object
Document itemDoc = XmlUtil.createDocument();
// Make a copy for inserting into the new document
Node importNode = itemDoc.importNode(node, true);
// Insert the copy into itemDoc
itemDoc.appendChild(importNode);
Item itemXml = new Item(itemDoc,
this.getQtiVersion());
// add the new section xml object to the list
itemXmlList.add(itemXml);
}
catch (DOMException ex)
{
log.error(ex);
ex.printStackTrace(System.out);
}
}
return itemXmlList;
}
/**
* Used internally.
* @param transform
* @return true if OK
*/
private boolean isOKtransform(String transform)
{
return (transform == this.ASSESSMENT_TRANSFORM ||
transform == this.SECTION_TRANSFORM ||
transform == this.ITEM_TRANSFORM) ? true : false;
}
/**
* Used internally.
* @param asi
* @return true if OK
*/
private boolean isOKasi(ASIBaseClass asi)
{
return (asi instanceof Assessment ||
asi instanceof Section ||
asi instanceof Item) ? true : false;
}
// /**
// * Create assessment from the extracted properties.
// * @param assessmentMap the extracted properties
// * @return an assessment, which has been persisted
// */
// public AssessmentFacade createAssessment(Map assessmentMap)
// {
// String description = (String) assessmentMap.get("description");
// String title = (String) assessmentMap.get("title");
// AssessmentService assessmentService = new AssessmentService();
// AssessmentFacade assessment = assessmentService.createAssessment(
// title, description, null, null);
// return assessment;
// }
/**
* Update assessment from the extracted properties.
* Note: you need to do a save when you are done.
* @param assessment the assessment, which will be persisted
* @param assessmentMap the extracted properties
*/
public void updateAssessment(AssessmentFacade assessment,
Map assessmentMap)
{
String title;
String displayName;
String description;
String comments;
String instructorNotification;
String testeeNotification;
String multipartAllowed;
String createdBy;
String createdDate;
title = (String) assessmentMap.get("title");
displayName = (String) assessmentMap.get("title");
comments = (String) assessmentMap.get("comments");
log.debug("ASSESSMENT updating metadata information");
// set meta data
List metalist = (List) assessmentMap.get("metadata");
MetaDataList metadataList = new MetaDataList(metalist);
metadataList.setDefaults(assessment);
metadataList.addTo(assessment);
createdBy = assessment.getAssessmentMetaDataByLabel("CREATOR");
log.debug("ASSESSMENT updating basic information");
// set basic properties
assessment.setCreatedBy(createdBy);
assessment.setComments(comments);
assessment.setCreatedDate(new Date());
assessment.setLastModifiedBy("Sakai Import");
assessment.setLastModifiedDate(new Date());
// additional information
// restricted IP address
log.debug("ASSESSMENT updating access control, evaluation model, feedback");
// access control
String duration = (String) assessmentMap.get("duration");
log.debug("duration: " + duration);
makeAccessControl(assessment, duration);
// evaluation model control
makeEvaluationModel(assessment);
// assessment feedback control
makeAssessmentFeedback(assessment);
}
/**
* Put feedback settings into assessment (bi-directional)
* @param assessment
*/
private void makeAssessmentFeedback(AssessmentFacade assessment)
{
AssessmentFeedback feedback =
(AssessmentFeedback) assessment.getAssessmentFeedback();
if (feedback == null){
feedback = new AssessmentFeedback();
// Need to fix AssessmentFeedback so it can take AssessmentFacade later
feedback.setAssessmentBase(assessment.getData());
}
if ("TRUE".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"FEEDBACK_SHOW_QUESTION")))
{
feedback.setShowQuestionText(Boolean.TRUE);
}
else
{
feedback.setShowQuestionText(Boolean.FALSE);
}
if ("TRUE".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"FEEDBACK_SHOW_RESPONSE")))
{
feedback.setShowStudentResponse(Boolean.TRUE);
}
else
{
feedback.setShowStudentResponse(Boolean.FALSE);
}
if ("TRUE".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"FEEDBACK_SHOW_CORRECT_RESPONSE")))
{
feedback.setShowCorrectResponse(Boolean.TRUE);
}
else
{
feedback.setShowCorrectResponse(Boolean.FALSE);
}
if ("TRUE".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"FEEDBACK_SHOW_STUDENT_SCORE")))
{
feedback.setShowStudentScore(Boolean.TRUE);
}
else
{
feedback.setShowStudentScore(Boolean.FALSE);
}
if ("TRUE".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"FEEDBACK_SHOW_STUDENT_QUESTIONSCORE")))
{
feedback.setShowStudentQuestionScore(Boolean.TRUE);
}
else
{
feedback.setShowStudentQuestionScore(Boolean.FALSE);
}
if ("TRUE".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"FEEDBACK_SHOW_ITEM_LEVEL")))
{
feedback.setShowQuestionLevelFeedback(Boolean.TRUE);
}
else
{
feedback.setShowQuestionLevelFeedback(Boolean.FALSE);
}
if ("TRUE".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"FEEDBACK_SHOW_SELECTION_LEVEL")))
{
feedback.setShowSelectionLevelFeedback(Boolean.TRUE);
}
else
{
feedback.setShowSelectionLevelFeedback(Boolean.FALSE);
}
if ("TRUE".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"FEEDBACK_SHOW_GRADER_COMMENT")))
{
feedback.setShowGraderComments(Boolean.TRUE);
}
else
{
feedback.setShowGraderComments(Boolean.FALSE);
}
if ("TRUE".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"FEEDBACK_SHOW_STATS")))
{
feedback.setShowStatistics(Boolean.TRUE);
}
else
{
feedback.setShowStatistics(Boolean.FALSE);
}
if (
this.notNullOrEmpty(assessment.getAssessmentMetaDataByLabel(
"FEEDBACK_DELIVERY_DATE") ) ||
"DATED".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"FEEDBACK_DELIVERY")))
{
feedback.setFeedbackDelivery(feedback.FEEDBACK_BY_DATE);
}
else if ("IMMEDIATE".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"FEEDBACK_DELIVERY")))
{
feedback.setFeedbackDelivery(feedback.IMMEDIATE_FEEDBACK);
}
else
{
feedback.setFeedbackDelivery(feedback.NO_FEEDBACK);
}
if (
"QUESTION".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"FEEDBACK_AUTHORING")))
{
feedback.setFeedbackAuthoring(feedback.QUESTIONLEVEL_FEEDBACK);
}
else if ("SECTION".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"FEEDBACK_AUTHORING")))
{
feedback.setFeedbackAuthoring(feedback.SECTIONLEVEL_FEEDBACK);
}
else
{
feedback.setFeedbackAuthoring(feedback.BOTH_FEEDBACK);
}
assessment.setAssessmentFeedback(feedback);
}
/**
* Put evaluation settings into assessment (bi-directional)
* @param assessment
*/
private void makeEvaluationModel(AssessmentFacade assessment)
{
EvaluationModel evaluationModel =
(EvaluationModel) assessment.getEvaluationModel();
if (evaluationModel == null){
evaluationModel = new EvaluationModel();
// Need to fix EvaluationModel so it can take AssessmentFacade later
evaluationModel.setAssessmentBase(assessment.getData());
}
// anonymous
if ("TRUE".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"ANONYMOUS_GRADING")))
{
evaluationModel.setAnonymousGrading(EvaluationModel.ANONYMOUS_GRADING);
}
else
{
evaluationModel.setAnonymousGrading(EvaluationModel.NON_ANONYMOUS_GRADING);
}
// gradebook options, don't know how this is supposed to work, leave alone for now
if ("DEFAULT".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"GRADEBOOK_OPTIONS")))
{
evaluationModel.setToGradeBook(EvaluationModel.TO_DEFAULT_GRADEBOOK.toString());
}
else if ("SELECTED".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"GRADEBOOK_OPTIONS")))
{
evaluationModel.setToGradeBook(EvaluationModel.TO_SELECTED_GRADEBOOK.toString());
}
// highest or last
if ("HIGHEST".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"GRADE_SCORE")))
{
evaluationModel.setScoringType(EvaluationModel.HIGHEST_SCORE);
}
/*
// not implementing average for now
else if ("AVERAGE".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"GRADE_SCORE")))
{
evaluationModel.setScoringType(EvaluationModel.AVERAGE_SCORE);
}
*/
else if ("LAST".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"GRADE_SCORE")))
{
evaluationModel.setScoringType(EvaluationModel.LAST_SCORE);
}
assessment.setEvaluationModel(evaluationModel);
}
/**
* Put access control settings into assessment (bi-directional)
* @param assessment
* @param duration Time interval for timed assessment (Iso8601 format)
*/
private void makeAccessControl(AssessmentFacade assessment, String duration)
{
AssessmentAccessControl control =
(AssessmentAccessControl)assessment.getAssessmentAccessControl();
if (control == null){
control = new AssessmentAccessControl();
// need to fix accessControl so it can take AssessmentFacade later
control.setAssessmentBase(assessment.getData());
}
// Control dates
Iso8601DateFormat iso = new Iso8601DateFormat();
String startDate = assessment.getAssessmentMetaDataByLabel("START_DATE");
String dueDate = assessment.getAssessmentMetaDataByLabel("END_DATE");
String retractDate = assessment.getAssessmentMetaDataByLabel("RETRACT_DATE");
String feedbackDate = assessment.getAssessmentMetaDataByLabel(
"FEEDBACK_DELIVERY_DATE");
try
{
control.setStartDate(iso.parse(startDate).getTime());
assessment.getData().addAssessmentMetaData("hasAvailableDate", "true");
}
catch (Iso8601FormatException ex)
{
log.debug("Cannot set startDate.");
}
try
{
control.setDueDate(iso.parse(dueDate).getTime());
// assessment.getData().addAssessmentMetaData("hasDueDate", "true");
assessment.getData().addAssessmentMetaData("dueDate", "true");
}
catch (Iso8601FormatException ex)
{
log.debug("Cannot set dueDate.");
}
try
{
control.setRetractDate(iso.parse(retractDate).getTime());
assessment.getData().addAssessmentMetaData("hasRetractDate", "true");
}
catch (Iso8601FormatException ex)
{
log.debug("Cannot set retractDate.");
}
try
{
control.setFeedbackDate(iso.parse(feedbackDate).getTime());
assessment.getData().addAssessmentMetaData("FEEDBACK_DELIVERY","DATED");
}
catch (Iso8601FormatException ex)
{
log.debug("Cannot set feedbackDate.");
}
// don't know what site you will have in a new environment
// but registered as a BUG in SAM-271 so turning it on.
String releasedTo = assessment.getAssessmentMetaDataByLabel(
"ASSESSMENT_RELEASED_TO");
// for backwards compatibility with version 1.5 exports.
if (releasedTo != null && releasedTo.indexOf("Authenticated Users") > -1)
{
log.debug(
"Fixing obsolete reference to 'Authenticated Users', setting released to 'Anonymous Users'.");
releasedTo = "Anonymous Users";
}
// for backwards compatibility with version 1.5 exports.
if (releasedTo != null && releasedTo.indexOf("Authenticated Users") > -1)
{
log.debug(
"Fixing obsolete reference to 'Authenticated Users', setting released to 'Anonymous Users'.");
releasedTo = "Anonymous Users";
}
log.debug("control.setReleaseTo(releasedTo)='"+releasedTo+"'.");
control.setReleaseTo(releasedTo);
// Timed Assessment
if (duration != null)
{
try
{
Iso8601TimeInterval tiso = new Iso8601TimeInterval(duration);
log.debug("tiso.getDuration(): " + tiso.getDuration());
if(tiso==null)
{
throw new Iso8601FormatException("Assessment duration could not be resolved.");
}
long millisecondsDuration = tiso.getDuration();
int seconds = (int) millisecondsDuration /1000;
control.setTimeLimit(new Integer(seconds));
- control.setTimedAssessment(AssessmentAccessControl.TIMED_ASSESSMENT);
- assessment.getData().addAssessmentMetaData("hasTimeAssessment", "true");
+ if (seconds !=0)
+ {
+ control.setTimedAssessment(AssessmentAccessControl.TIMED_ASSESSMENT);
+ assessment.getData().addAssessmentMetaData("hasTimeAssessment", "true");
+ }
+ else
+ {
+ control.setTimeLimit(new Integer(0));
+ control.setTimedAssessment(AssessmentAccessControl.
+ DO_NOT_TIMED_ASSESSMENT);
+ }
}
catch (Iso8601FormatException ex)
{
log.warn("Can't format assessment duration. " + ex);
control.setTimeLimit(new Integer(0));
control.setTimedAssessment(AssessmentAccessControl.
DO_NOT_TIMED_ASSESSMENT);
}
}
else
{
control.setTimeLimit(new Integer(0));
control.setTimedAssessment(AssessmentAccessControl.
DO_NOT_TIMED_ASSESSMENT);
}
log.debug("assessment.getAssessmentMetaDataByLabel(AUTO_SUBMIT): " +
assessment.getAssessmentMetaDataByLabel("AUTO_SUBMIT"));
if ("TRUE".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"AUTO_SUBMIT")))
{
log.debug("AUTO SUBMIT IS TRUE");
control.setAutoSubmit(AssessmentAccessControl.AUTO_SUBMIT);
assessment.getData().addAssessmentMetaData("hasAutoSubmit", "true");
}
else
{
control.setAutoSubmit(AssessmentAccessControl.DO_NOT_AUTO_SUBMIT);
}
// Assessment Organization
// navigation
if ("LINEAR".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"NAVIGATION")))
{
control.setItemNavigation(control.LINEAR_ACCESS);
}
else
{
control.setItemNavigation(control.RANDOM_ACCESS);
}
// numbering
if ("CONTINUOUS".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"QUESTION_NUMBERING")))
{
control.setItemNumbering(control.CONTINUOUS_NUMBERING);
}
else if ("RESTART".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"QUESTION_NUMBERING")))
{
control.setItemNumbering(control.RESTART_NUMBERING_BY_PART);
}
//question layout
if ("I".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"QUESTION_LAYOUT")))
{
control.setAssessmentFormat(control.BY_QUESTION);
}
else if ("S".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"QUESTION_LAYOUT")))
{
control.setAssessmentFormat(control.BY_PART);
}
else
{
control.setAssessmentFormat(control.BY_ASSESSMENT);
}
//Submissions
// submissions allowed
String maxAttempts =
"" + assessment.getAssessmentMetaDataByLabel("MAX_ATTEMPTS");
String unlimited = AuthoringConstantStrings.UNLIMITED_SUBMISSIONS;
log.debug("maxAttempts: '" + maxAttempts + "'");
log.debug("unlimited: '" + unlimited + "'");
if (
unlimited.equals(maxAttempts.trim()))
{
log.debug("unlimited.equals(maxAttempts.trim()");
control.setUnlimitedSubmissions(Boolean.TRUE);
control.setSubmissionsAllowed(AssessmentAccessControlIfc.
UNLIMITED_SUBMISSIONS);
}
else
{
control.setUnlimitedSubmissions(Boolean.FALSE);
try
{
control.setSubmissionsAllowed(new Integer(maxAttempts));
}
catch (NumberFormatException ex1)
{
control.setSubmissionsAllowed(new Integer("1"));
}
}
log.debug("Set: control.getSubmissionsAllowed()="+control.getSubmissionsAllowed());
log.debug("Set: control.getUnlimitedSubmissions()="+control.getUnlimitedSubmissions());
// late submissions
// I am puzzled as to why there is no ACCEPT_LATE_SUBMISSION, assuming it =T
if ("FALSE".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"LATE_HANDLING")))
{
control.setLateHandling(control.NOT_ACCEPT_LATE_SUBMISSION);
}
else
{
control.setLateHandling(new Integer(1));
}
// auto save
if ("TRUE".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"AUTO_SAVE")))
{
control.setAutoSubmit(control.AUTO_SAVE);
}
// Submission Message
String submissionMessage = assessment.getAssessmentMetaDataByLabel(
"SUBMISSION_MESSAGE");
if (submissionMessage != null)
{
control.setSubmissionMessage(submissionMessage);
}
// Username, password, finalPageUrl
// String considerUserId = assessment.getAssessmentMetaDataByLabel(
// "CONSIDER_USERID"); //
String userId = assessment.getAssessmentMetaDataByLabel("USERID");
String password = assessment.getAssessmentMetaDataByLabel("PASSWORD");
String finalPageUrl = assessment.getAssessmentMetaDataByLabel("FINISH_URL");
if (//"TRUE".equalsIgnoreCase(considerUserId) &&
notNullOrEmpty(userId) && notNullOrEmpty(password))
{
control.setUsername(userId);
control.setPassword(password);
assessment.getData().addAssessmentMetaData("hasUsernamePassword", "true");
}
control.setFinalPageUrl(finalPageUrl);
assessment.setAssessmentAccessControl(control);
}
/**
* the ip address is in a newline delimited string
* @param assessment
*/
public void makeSecuredIPAddressSet(AssessmentFacade assessment, String ipList)
{
Set securedIPAddressSet = (Set) assessment.getSecuredIPAddressSet();
AssessmentBaseIfc data = assessment.getData();
if (securedIPAddressSet == null)
{
securedIPAddressSet = new HashSet();
}
log.info("Getting securedIPAddressSet=" + securedIPAddressSet);
log.info("ipList: " + ipList);
if (ipList == null)
ipList = "";
String[] ip = ipList.split("\\n");
for (int j = 0; j < ip.length; j++)
{
log.info("ip # " + j + ": " + ip[j]);
if (ip[j] != null)
{
SecuredIPAddress sip = new SecuredIPAddress(data, null, ip[j]);
//sip.setAssessment(data);
securedIPAddressSet.add(sip);
}
}
log.info("securedIPAddressSet.size()=" + securedIPAddressSet.size());
if (securedIPAddressSet.size()>0)
{
log.info("Setting securedIPAddressSet;addAssessmentMetaData(hasIpAddress, true)");
AssessmentService assessmentService = new AssessmentService();
// assessment.getData().setSecuredIPAddressSet(securedIPAddressSet);
// assessment.getData().addAssessmentMetaData("hasIpAddress", "true");
// assessment.getData().addAssessmentMetaData("hasSpecificIP", "true");
// data.setSecuredIPAddressSet(securedIPAddressSet);
data.addAssessmentMetaData("hasIpAddress", "true");
data.addAssessmentMetaData("hasSpecificIP", "true");
assessment.updateData(data);
assessment.setSecuredIPAddressSet(securedIPAddressSet);
}
}
/**
* Update section from the extracted properties.
* Note: you need to do a save when you are done.
* @param section the section, which will be persisted
* @param sectionMap the extracted properties
*/
public void updateSection(SectionFacade section, Map sectionMap)
{
section.setTitle( (String) sectionMap.get("title"));
section.setDescription( (String) sectionMap.get("description"));
section.setLastModifiedBy("Sakai Import");
section.setLastModifiedDate(new Date());
}
/**
* Update item from the extracted properties.
* Note: you need to do a save when you are done.
* @param item the item, which will be persisted
* @param itemMap the extracted properties
*/
public void updateItem(ItemFacade item, Map itemMap)
{
// type and title
String title = (String) itemMap.get("title");
item.setDescription(title);
// set meta data
List metalist = (List) itemMap.get("metadata");
MetaDataList metadataList = new MetaDataList(metalist);
metadataList.addTo(item);
// type
log.debug("itemMap="+itemMap);
String qmd = item.getItemMetaDataByLabel("qmd_itemtype");
String itemIntrospect = (String) itemMap.get("itemIntrospect");
log.debug("Calling ItemTypeExtractionStrategy.calculate(");
log.debug(" title="+title);
log.debug(" , itemIntrospect="+itemIntrospect);
log.debug(" , qmd="+qmd);
log.debug(");");
Long typeId = ItemTypeExtractionStrategy.calculate(title, itemIntrospect, qmd);
item.setTypeId(typeId);
// basic properties
addItemProperties(item, itemMap);
// feedback
// correct, incorrect, general
addFeedback(item, itemMap, typeId);
// item text and answers
if (TypeIfc.FILL_IN_BLANK.longValue() == typeId.longValue())
{
addFibTextAndAnswers(item, itemMap);
}
else if (TypeIfc.MATCHING.longValue() == typeId.longValue())
{
addMatchTextAndAnswers(item, itemMap);
}
else
{
addTextAndAnswers(item, itemMap);
}
}
/**
*
* @param item
* @param itemMap
*/
private void addItemProperties(ItemFacade item, Map itemMap)
{
String duration = (String) itemMap.get("duration");
String triesAllowed = (String) itemMap.get("triesAllowed");
String score = (String) itemMap.get("score");
String hasRationale = item.getItemMetaDataByLabel("hasRationale");//rshastri :SAK-1824
String status = (String) itemMap.get("status");
String createdBy = (String) itemMap.get("createdBy");
// not being set yet
String instruction = (String) itemMap.get("instruction");
String hint = (String) itemMap.get("hint");
// created by is not nullable
if (createdBy == null)
{
createdBy = "Imported by Sakai";
}
String createdDate = (String) itemMap.get("createdDate");
if (notNullOrEmpty(duration))
{
item.setDuration(new Integer(duration));
}
if (notNullOrEmpty(triesAllowed))
{
item.setTriesAllowed(new Integer(triesAllowed));
}
item.setInstruction( (String) itemMap.get("instruction"));
if (notNullOrEmpty(score))
{
item.setScore(new Float(score));
}
item.setHint( (String) itemMap.get("hint"));
if (notNullOrEmpty(hasRationale))
{
item.setHasRationale(new Boolean(hasRationale));
}
if (notNullOrEmpty(status))
{
item.setStatus(new Integer(status));
}
item.setCreatedBy(createdBy);
try
{
Iso8601DateFormat iso = new Iso8601DateFormat();
Calendar cal = iso.parse(createdDate);
item.setCreatedDate(cal.getTime());
}
catch (Exception ex)
{
item.setCreatedDate(new Date());
}
item.setLastModifiedBy("Sakai Import");
item.setLastModifiedDate(new Date());
}
/**
* add feedback
* @param item
* @param itemMap
* @param typeId
*/
private void addFeedback(ItemFacade item, Map itemMap, Long typeId)
{
// write the map out
Iterator iter = itemMap.keySet().iterator();
while (iter.hasNext())
{
String key = (String) iter.next();
Object o = itemMap.get(key);
log.debug("itemMap: " + key + "=" + itemMap.get(key));
}
String correctItemFeedback = (String) itemMap.get("correctItemFeedback");
String incorrectItemFeedback = (String) itemMap.get("incorrectItemFeedback");
String generalItemFeedback = (String) itemMap.get("generalItemFeedback");
if (generalItemFeedback==null) generalItemFeedback = "";
// NOTE:
// in early Samigo (aka Navigo) general feedback exported as "InCorrect"!
// now if this is an Audio, File Upload or Short Answer question additional
// feedback will append feedback to general, this should be OK, since
// QTI with general feedback for these types will leave them empty
if (TypeIfc.AUDIO_RECORDING.longValue() == typeId.longValue() ||
TypeIfc.FILE_UPLOAD.longValue() == typeId.longValue() ||
TypeIfc.ESSAY_QUESTION.longValue() == typeId.longValue())
{
if (notNullOrEmpty(incorrectItemFeedback))
{
generalItemFeedback += " " + incorrectItemFeedback;
}
if (notNullOrEmpty(correctItemFeedback))
{
generalItemFeedback += " " + correctItemFeedback;
}
}
if (notNullOrEmpty(correctItemFeedback))
{
item.setCorrectItemFeedback(correctItemFeedback);
}
if (notNullOrEmpty(incorrectItemFeedback))
{
item.setInCorrectItemFeedback(incorrectItemFeedback);
}
if (notNullOrEmpty(generalItemFeedback))
{
item.setGeneralItemFeedback(generalItemFeedback);
}
}
/**
* create the answer feedback set for an answer
* @param item
* @param itemMap
*/
private void addAnswerFeedback(Answer answer, String value)
{
HashSet answerFeedbackSet = new HashSet();
answerFeedbackSet.add(new AnswerFeedback(answer,
AnswerFeedbackIfc.ANSWER_FEEDBACK,
value));
answer.setAnswerFeedbackSet(answerFeedbackSet);
}
/**
* @param item
* @param itemMap
*/
private void addTextAndAnswers(ItemFacade item, Map itemMap)
{
List itemTextList = (List) itemMap.get("itemText");
HashSet itemTextSet = new HashSet();
for (int i = 0; i < itemTextList.size(); i++)
{
ItemText itemText = new ItemText();
String text = (String) itemTextList.get(i);
// should be allow this or, continue??
// for now, empty string OK, setting to empty string if null
if (text == null)
{
text = "";
}
text=text.replaceAll("\\?\\?"," ");//SAK-2298
log.debug("text: " + text);
itemText.setText(text);
itemText.setItem(item.getData());
itemText.setSequence(new Long(i + 1));
List answerList = new ArrayList();
List aList = (List) itemMap.get("itemAnswer");
answerList = aList == null ? answerList : aList;
HashSet answerSet = new HashSet();
char answerLabel = 'A';
List answerFeedbackList = (List) itemMap.get("itemAnswerFeedback");
ArrayList correctLabels;
correctLabels = (ArrayList) itemMap.get("itemAnswerCorrectLabel");
if (correctLabels == null)
{
correctLabels = new ArrayList();
}
for (int a = 0; a < answerList.size(); a++)
{
Answer answer = new Answer();
String answerText = (String) answerList.get(a);
// these are not supposed to be empty
if (notNullOrEmpty(answerText))
{
answerText=answerText.replaceAll("\\?\\?"," ");//SAK-2298
log.debug("answerText: " + answerText);
// normalize all true/false questions
if (answerList.size()==2)
{
if (answerText.equalsIgnoreCase("true")) answerText = "true";
if (answerText.equalsIgnoreCase("false")) answerText = "false";
}
String label = "" + answerLabel++;
answer.setLabel(label); // up to 26, is this a problem?
// correct answer and score
float score = 0;
// if label matches correct answer it is correct
if (isCorrectLabel(label, correctLabels))
{
answer.setIsCorrect(Boolean.TRUE);
// manual authoring disregards correctness
// commented out: what we'd have if we looked at correctness
// score = getCorrectScore(item, 1);
}
else
{
answer.setIsCorrect(Boolean.FALSE);
}
// manual authoring disregards correctness
// so we will do the same.
score = getCorrectScore(item, 1);
log.debug("setting answer" + label + " score to:" + score);
answer.setScore(new Float(score));
answer.setText(answerText);
answer.setItemText(itemText);
answer.setItem(item.getData());
int sequence = a + 1;
answer.setSequence(new Long(sequence));
// prepare answer feedback - daisyf added this on 2/21/05
// need to check if this works for question type other than
// MC
HashSet set = new HashSet();
if (answerFeedbackList != null)
{
AnswerFeedback answerFeedback = new AnswerFeedback();
answerFeedback.setAnswer(answer);
answerFeedback.setTypeId(AnswerFeedbackIfc.GENERAL_FEEDBACK);
if (answerFeedbackList.get(sequence - 1) != null)
{
answerFeedback.setText( (String) answerFeedbackList.get(sequence -
1));
set.add(answerFeedback);
answer.setAnswerFeedbackSet(set);
}
}
answerSet.add(answer);
}
}
itemText.setAnswerSet(answerSet);
itemTextSet.add(itemText);
}
item.setItemTextSet(itemTextSet);
}
private float getCorrectScore(ItemDataIfc item, int answerSize)
{
float score =0;
if (answerSize>0 && item!=null && item.getScore()!=null)
{
score = item.getScore().floatValue()/answerSize;
}
return score;
}
/**
* Check to find out it response label is in the list of correct responses
* @param testLabel response label
* @param labels the list of correct responses
* @return
*/
private boolean isCorrectLabel(String testLabel, ArrayList labels)
{
if (testLabel == null || labels == null
|| labels.indexOf(testLabel) == -1)
{
return false;
}
return true;
}
/**
* FIB questions ONLY
* @param item
* @param itemMap
*/
private void addFibTextAndAnswers(ItemFacade item, Map itemMap)
{
List itemTextList = new ArrayList();
List iList = (List) itemMap.get("itemFibText");
itemTextList = iList == null ? itemTextList : iList;
List itemTList = new ArrayList();
List tList = (List) itemMap.get("itemText");
itemTList = iList == null ? itemTList : tList;
HashSet itemTextSet = new HashSet();
ItemText itemText = new ItemText();
String itemTextString = "";
List answerFeedbackList = (List) itemMap.get("itemFeedback");
List answerList = new ArrayList();
List aList = (List) itemMap.get("itemFibAnswer");
answerList = aList == null ? answerList : aList;
// handle FIB with instructional text
// sneak it into first text
if ( !itemTList.isEmpty()
&& !itemTextList.isEmpty()
&& !(itemTextList.size()>1))
{
try
{
String firstFib = (String) itemTextList.get(0);
String firstText = (String) itemTList.get(0);
if (firstFib.equals(firstText))
{
log.debug("Setting FIB instructional text.");
// itemTextList.remove(0);
String newFirstFib
= firstFib + "<br />" + itemTextList.get(0);
itemTextList.set(0, newFirstFib);
}
}
catch (Exception ex)
{
log.warn("Thought we found an instructional text but couldn't put it in."
+ " " + ex);
}
}
// loop through all our extracted FIB texts interposing FIB_BLANK_INDICATOR
for (int i = 0; i < itemTextList.size(); i++)
{
String text = (String) itemTextList.get(i);
// we are assuming non-empty text/answer/non-empty text/answer etc.
if (text == null || text=="")
{
continue;
}
itemTextString += text;
if (i < answerList.size())
{
itemTextString += FIB_BLANK_INDICATOR;
}
}
itemTextString=itemTextString.replaceAll("\\?\\?"," ");//SAK-2298
log.debug("itemTextString="+itemTextString);
itemText.setText(itemTextString);
itemText.setItem(item.getData());
itemText.setSequence(new Long(0));
HashSet answerSet = new HashSet();
char answerLabel = 'A';
for (int a = 0; a < answerList.size(); a++)
{
Answer answer = new Answer();
String answerText = (String) answerList.get(a);
// these are not supposed to be empty
if (notNullOrEmpty(answerText))
{
answerText=answerText.replaceAll("\\?\\?"," ");//SAK-2298
log.debug("answerText="+answerText);
String label = "" + answerLabel++;
answer.setLabel(label); // up to 26, is this a problem?
answer.setText(answerText);
answer.setItemText(itemText);
// correct answer and score
answer.setIsCorrect(Boolean.TRUE);
// manual authoring disregards the number of partial answers
// so we will do the same.
float score = getCorrectScore(item, 1);
// float score = getCorrectScore(item, answerList.size());
log.debug("setting answer " + label + " score to:" + score);
answer.setScore(new Float(score));
answer.setItem(item.getData());
int sequence = a + 1;
answer.setSequence(new Long(sequence));
HashSet set = new HashSet();
if (answerFeedbackList != null)
{
AnswerFeedback answerFeedback = new AnswerFeedback();
answerFeedback.setAnswer(answer);
answerFeedback.setTypeId(AnswerFeedbackIfc.GENERAL_FEEDBACK);
if (answerFeedbackList.get(sequence - 1) != null)
{
answerFeedback.setText( (String) answerFeedbackList.get(
sequence - 1));
set.add(answerFeedback);
answer.setAnswerFeedbackSet(set);
}
}
answerSet.add(answer);
}
}
itemText.setAnswerSet(answerSet);
itemTextSet.add(itemText);
item.setItemTextSet(itemTextSet);
}
/**
* MATCHING questions ONLY
* @param item
* @param itemMap
*/
private void addMatchTextAndAnswers(ItemFacade item, Map itemMap)
{
List sourceList = (List) itemMap.get("itemMatchSourceText");
List targetList = (List) itemMap.get("itemMatchTargetText");
List indexList = (List) itemMap.get("itemMatchIndex");
List answerFeedbackList = (List) itemMap.get("itemFeedback");
List correctMatchFeedbackList = (List) itemMap.get(
"itemMatchCorrectFeedback");
List incorrectMatchFeedbackList = (List) itemMap.get(
"itemMatchIncorrectFeedback");
List itemTextList = (List) itemMap.get("itemText");
sourceList = sourceList == null ? new ArrayList() : sourceList;
targetList = targetList == null ? new ArrayList() : targetList;
indexList = indexList == null ? new ArrayList() : indexList;
answerFeedbackList =
answerFeedbackList == null ? new ArrayList() : answerFeedbackList;
correctMatchFeedbackList =
correctMatchFeedbackList ==
null ? new ArrayList() : correctMatchFeedbackList;
incorrectMatchFeedbackList =
incorrectMatchFeedbackList ==
null ? new ArrayList() : incorrectMatchFeedbackList;
log.debug("*** original order");
for (int i = 0; i < correctMatchFeedbackList.size(); i++) {
log.debug("incorrectMatchFeedbackList.get(" + i + ")="+
incorrectMatchFeedbackList.get(i));
}
int maxNumCorrectFeedback = sourceList.size();
int numIncorrectFeedback = incorrectMatchFeedbackList.size();
if (maxNumCorrectFeedback>0 && numIncorrectFeedback>0)
{
incorrectMatchFeedbackList =
reassembleIncorrectMatches(
incorrectMatchFeedbackList, maxNumCorrectFeedback);
}
log.debug("*** NEW order");
for (int i = 0; i < correctMatchFeedbackList.size(); i++) {
log.debug("incorrectMatchFeedbackList.get(" + i + ")="+
incorrectMatchFeedbackList.get(i));
}
itemTextList =
itemTextList == null ? new ArrayList() : itemTextList;
if (targetList.size() <indexList.size())
{
log.debug("targetList.size(): " + targetList.size());
log.debug("indexList.size(): " + indexList.size());
}
String itemTextString = "";
if (itemTextList.size()>0)
{
itemTextString = (String) itemTextList.get(0);
}
HashSet itemTextSet = new HashSet();
// first, add the question text
if (itemTextString==null) itemTextString = "";
itemTextString=itemTextString.replaceAll("\\?\\?"," ");//SAK-2298
log.debug("item.setInstruction itemTextString: " + itemTextString);
item.setInstruction(itemTextString);
// loop through source texts indicating answers (targets)
for (int i = 0; i < sourceList.size(); i++)
{
// create the entry for the matching item (source)
String sourceText = (String) sourceList.get(i);
if (sourceText == null) sourceText="";
sourceText=sourceText.replaceAll("\\?\\?"," ");//SAK-2298
log.debug("sourceText: " + sourceText);
ItemText sourceItemText = new ItemText();
sourceItemText.setText(sourceText);
sourceItemText.setItem(item.getData());
sourceItemText.setSequence(new Long(i + 1));
// find the matching answer (target)
HashSet targetSet = new HashSet();
String targetString;
int targetIndex = 999;// obviously not matching value
try
{
targetIndex = Integer.parseInt( (String) indexList.get(i));
}
catch (NumberFormatException ex)
{
log.warn("No match for " + sourceText + "."); // default to no match
}
catch (IndexOutOfBoundsException ex)
{
log.error("Corrupt index list. Cannot assign match for: " +sourceText + ".");
}
// loop through all possible targets (matching answers)
char answerLabel = 'A';
for (int a = 0; a < targetList.size(); a++)
{
targetString = (String) targetList.get(a);
if (targetString == null)
{
targetString = "";
}
targetString=targetString.replaceAll("\\?\\?"," ");//SAK-2298
log.debug("targetString: " + targetString);
Answer target = new Answer();
//feedback
HashSet answerFeedbackSet = new HashSet();
if (correctMatchFeedbackList.size() > i)
{
String fb = (String) correctMatchFeedbackList.get(i);
answerFeedbackSet.add( new AnswerFeedback(
target, AnswerFeedbackIfc.CORRECT_FEEDBACK, fb));
}
if (incorrectMatchFeedbackList.size() > i)
{
String fb = (String) incorrectMatchFeedbackList.get(i);
log.debug("setting incorrect fb="+fb);
answerFeedbackSet.add( new AnswerFeedback(
target, AnswerFeedbackIfc.INCORRECT_FEEDBACK, fb));
}
target.setAnswerFeedbackSet(answerFeedbackSet);
String label = "" + answerLabel++;
target.setLabel(label); // up to 26, is this a problem?
target.setText(targetString);
target.setItemText(sourceItemText);
target.setItem(item.getData());
target.setSequence(new Long(a + 1));
// correct answer and score
// manual authoring disregards the number of partial answers
// or whether the answer is correct so we will do the same.
// float score = 0;
float score = getCorrectScore(item, 1);
// if this answer is the indexed one, flag as correct
if (a + 1 == targetIndex)
{
target.setIsCorrect(Boolean.TRUE);
// score = getCorrectScore(item, targetList.size());
log.debug("source: " + sourceText + " matches target: " + targetString);
}
else
{
target.setIsCorrect(Boolean.FALSE);
}
log.debug("setting answer " + a + " score to:" + score);
target.setScore(new Float(score));
if (answerFeedbackList != null)
{
Set targetFeedbackSet = new HashSet();
AnswerFeedback tAnswerFeedback = new AnswerFeedback();
tAnswerFeedback.setAnswer(target);
tAnswerFeedback.setTypeId(AnswerFeedbackIfc.GENERAL_FEEDBACK);
String targetFeedback = "";
if (answerFeedbackList.size()>0)
{
targetFeedback = (String) answerFeedbackList.get(targetIndex);
}
if (targetFeedback.length()>0)
{
tAnswerFeedback.setText( targetFeedback);
targetFeedbackSet.add(tAnswerFeedback);
target.setAnswerFeedbackSet(targetFeedbackSet);
}
}
targetSet.add(target);
}
sourceItemText.setAnswerSet(targetSet);
itemTextSet.add(sourceItemText);
}
item.setItemTextSet(itemTextSet);
}
/**
* Helper method rotates the first n.
* This will work with Samigo matching where
* incorrect matches (n) = the square of the correct matches (n**2)
* and the 0th displayfeedback is correct and the next n are incorrect
* feedback. In export Samigo uses the incorrect feedback redundantly.
*
* For example, if there are 5 matches, there are 25 matches and mismatched,
* 5 of which are correct and 20 of which are not, so there is redundancy in
* Samigo.
*
* In non-Samigo matching, there may be more than one incorrect
* feedback for a failed matching.
*
* @param list the list
* @return a reassembled list of size n
*/
private List reassembleIncorrectMatches(List list, int n)
{
// make sure we have a reasonable value
if (n<0) n = -n;
if (n==0) return list;
// pad input list if too small or null
if (list == null)
list = new ArrayList();
for (int i = 0; i < n && list.size()<n +1; i++)
{
list.add("");
}
// our output value
List newList = new ArrayList();
// move the last of the n entries (0-index) up to the front
newList.add(list.get(n-1));
// add the 2nd entry and so forth
for (int i = 0; i < n-1 ; i++)
{
String s = (String) list.get(i);
newList.add(s);
}
return newList;
}
/**
* helper method
* @param s
* @return
*/
private boolean notNullOrEmpty(String s)
{
return s != null && s.trim().length() > 0 ?
true : false;
}
/**
* Append " - 2", " - 3", etc. incrementing as you go.
* @param title the original
* @return the title with versioning appended
*/
public String renameDuplicate(String title)
{
if (title==null) title = "";
String rename = "";
int index = title.lastIndexOf(VERSION_START);
if (index>-1)//if is versioned
{
String mainPart = "";
String versionPart = title.substring(index);
if (index > 0)
{
mainPart = title.substring(0, index);
}
int nindex = index + VERSION_START.length();
String version = title.substring(nindex);
int versionNumber = 0;
try
{
versionNumber = Integer.parseInt(version);
if (versionNumber < 2) versionNumber = 2;
versionPart = VERSION_START + (versionNumber + 1);
rename = mainPart + versionPart;
}
catch (NumberFormatException ex)
{
rename = title + VERSION_START + "2";
}
}
else
{
rename = title + VERSION_START + "2";
}
return rename;
}
/**
* Primarily for testing purposes.
* @return an overridden path if not null
*/
public String getOverridePath()
{
return overridePath;
}
/**
* Primarily for testing purposes.
* @param overridePath an overriding path
*/
public void setOverridePath(String overridePath)
{
this.overridePath = overridePath;
}
}
| true | true | private void makeAccessControl(AssessmentFacade assessment, String duration)
{
AssessmentAccessControl control =
(AssessmentAccessControl)assessment.getAssessmentAccessControl();
if (control == null){
control = new AssessmentAccessControl();
// need to fix accessControl so it can take AssessmentFacade later
control.setAssessmentBase(assessment.getData());
}
// Control dates
Iso8601DateFormat iso = new Iso8601DateFormat();
String startDate = assessment.getAssessmentMetaDataByLabel("START_DATE");
String dueDate = assessment.getAssessmentMetaDataByLabel("END_DATE");
String retractDate = assessment.getAssessmentMetaDataByLabel("RETRACT_DATE");
String feedbackDate = assessment.getAssessmentMetaDataByLabel(
"FEEDBACK_DELIVERY_DATE");
try
{
control.setStartDate(iso.parse(startDate).getTime());
assessment.getData().addAssessmentMetaData("hasAvailableDate", "true");
}
catch (Iso8601FormatException ex)
{
log.debug("Cannot set startDate.");
}
try
{
control.setDueDate(iso.parse(dueDate).getTime());
// assessment.getData().addAssessmentMetaData("hasDueDate", "true");
assessment.getData().addAssessmentMetaData("dueDate", "true");
}
catch (Iso8601FormatException ex)
{
log.debug("Cannot set dueDate.");
}
try
{
control.setRetractDate(iso.parse(retractDate).getTime());
assessment.getData().addAssessmentMetaData("hasRetractDate", "true");
}
catch (Iso8601FormatException ex)
{
log.debug("Cannot set retractDate.");
}
try
{
control.setFeedbackDate(iso.parse(feedbackDate).getTime());
assessment.getData().addAssessmentMetaData("FEEDBACK_DELIVERY","DATED");
}
catch (Iso8601FormatException ex)
{
log.debug("Cannot set feedbackDate.");
}
// don't know what site you will have in a new environment
// but registered as a BUG in SAM-271 so turning it on.
String releasedTo = assessment.getAssessmentMetaDataByLabel(
"ASSESSMENT_RELEASED_TO");
// for backwards compatibility with version 1.5 exports.
if (releasedTo != null && releasedTo.indexOf("Authenticated Users") > -1)
{
log.debug(
"Fixing obsolete reference to 'Authenticated Users', setting released to 'Anonymous Users'.");
releasedTo = "Anonymous Users";
}
// for backwards compatibility with version 1.5 exports.
if (releasedTo != null && releasedTo.indexOf("Authenticated Users") > -1)
{
log.debug(
"Fixing obsolete reference to 'Authenticated Users', setting released to 'Anonymous Users'.");
releasedTo = "Anonymous Users";
}
log.debug("control.setReleaseTo(releasedTo)='"+releasedTo+"'.");
control.setReleaseTo(releasedTo);
// Timed Assessment
if (duration != null)
{
try
{
Iso8601TimeInterval tiso = new Iso8601TimeInterval(duration);
log.debug("tiso.getDuration(): " + tiso.getDuration());
if(tiso==null)
{
throw new Iso8601FormatException("Assessment duration could not be resolved.");
}
long millisecondsDuration = tiso.getDuration();
int seconds = (int) millisecondsDuration /1000;
control.setTimeLimit(new Integer(seconds));
control.setTimedAssessment(AssessmentAccessControl.TIMED_ASSESSMENT);
assessment.getData().addAssessmentMetaData("hasTimeAssessment", "true");
}
catch (Iso8601FormatException ex)
{
log.warn("Can't format assessment duration. " + ex);
control.setTimeLimit(new Integer(0));
control.setTimedAssessment(AssessmentAccessControl.
DO_NOT_TIMED_ASSESSMENT);
}
}
else
{
control.setTimeLimit(new Integer(0));
control.setTimedAssessment(AssessmentAccessControl.
DO_NOT_TIMED_ASSESSMENT);
}
log.debug("assessment.getAssessmentMetaDataByLabel(AUTO_SUBMIT): " +
assessment.getAssessmentMetaDataByLabel("AUTO_SUBMIT"));
if ("TRUE".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"AUTO_SUBMIT")))
{
log.debug("AUTO SUBMIT IS TRUE");
control.setAutoSubmit(AssessmentAccessControl.AUTO_SUBMIT);
assessment.getData().addAssessmentMetaData("hasAutoSubmit", "true");
}
else
{
control.setAutoSubmit(AssessmentAccessControl.DO_NOT_AUTO_SUBMIT);
}
// Assessment Organization
// navigation
if ("LINEAR".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"NAVIGATION")))
{
control.setItemNavigation(control.LINEAR_ACCESS);
}
else
{
control.setItemNavigation(control.RANDOM_ACCESS);
}
// numbering
if ("CONTINUOUS".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"QUESTION_NUMBERING")))
{
control.setItemNumbering(control.CONTINUOUS_NUMBERING);
}
else if ("RESTART".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"QUESTION_NUMBERING")))
{
control.setItemNumbering(control.RESTART_NUMBERING_BY_PART);
}
//question layout
if ("I".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"QUESTION_LAYOUT")))
{
control.setAssessmentFormat(control.BY_QUESTION);
}
else if ("S".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"QUESTION_LAYOUT")))
{
control.setAssessmentFormat(control.BY_PART);
}
else
{
control.setAssessmentFormat(control.BY_ASSESSMENT);
}
//Submissions
// submissions allowed
String maxAttempts =
"" + assessment.getAssessmentMetaDataByLabel("MAX_ATTEMPTS");
String unlimited = AuthoringConstantStrings.UNLIMITED_SUBMISSIONS;
log.debug("maxAttempts: '" + maxAttempts + "'");
log.debug("unlimited: '" + unlimited + "'");
if (
unlimited.equals(maxAttempts.trim()))
{
log.debug("unlimited.equals(maxAttempts.trim()");
control.setUnlimitedSubmissions(Boolean.TRUE);
control.setSubmissionsAllowed(AssessmentAccessControlIfc.
UNLIMITED_SUBMISSIONS);
}
else
{
control.setUnlimitedSubmissions(Boolean.FALSE);
try
{
control.setSubmissionsAllowed(new Integer(maxAttempts));
}
catch (NumberFormatException ex1)
{
control.setSubmissionsAllowed(new Integer("1"));
}
}
log.debug("Set: control.getSubmissionsAllowed()="+control.getSubmissionsAllowed());
log.debug("Set: control.getUnlimitedSubmissions()="+control.getUnlimitedSubmissions());
// late submissions
// I am puzzled as to why there is no ACCEPT_LATE_SUBMISSION, assuming it =T
if ("FALSE".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"LATE_HANDLING")))
{
control.setLateHandling(control.NOT_ACCEPT_LATE_SUBMISSION);
}
else
{
control.setLateHandling(new Integer(1));
}
// auto save
if ("TRUE".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"AUTO_SAVE")))
{
control.setAutoSubmit(control.AUTO_SAVE);
}
// Submission Message
String submissionMessage = assessment.getAssessmentMetaDataByLabel(
"SUBMISSION_MESSAGE");
if (submissionMessage != null)
{
control.setSubmissionMessage(submissionMessage);
}
// Username, password, finalPageUrl
// String considerUserId = assessment.getAssessmentMetaDataByLabel(
// "CONSIDER_USERID"); //
String userId = assessment.getAssessmentMetaDataByLabel("USERID");
String password = assessment.getAssessmentMetaDataByLabel("PASSWORD");
String finalPageUrl = assessment.getAssessmentMetaDataByLabel("FINISH_URL");
if (//"TRUE".equalsIgnoreCase(considerUserId) &&
notNullOrEmpty(userId) && notNullOrEmpty(password))
{
control.setUsername(userId);
control.setPassword(password);
assessment.getData().addAssessmentMetaData("hasUsernamePassword", "true");
}
control.setFinalPageUrl(finalPageUrl);
assessment.setAssessmentAccessControl(control);
}
| private void makeAccessControl(AssessmentFacade assessment, String duration)
{
AssessmentAccessControl control =
(AssessmentAccessControl)assessment.getAssessmentAccessControl();
if (control == null){
control = new AssessmentAccessControl();
// need to fix accessControl so it can take AssessmentFacade later
control.setAssessmentBase(assessment.getData());
}
// Control dates
Iso8601DateFormat iso = new Iso8601DateFormat();
String startDate = assessment.getAssessmentMetaDataByLabel("START_DATE");
String dueDate = assessment.getAssessmentMetaDataByLabel("END_DATE");
String retractDate = assessment.getAssessmentMetaDataByLabel("RETRACT_DATE");
String feedbackDate = assessment.getAssessmentMetaDataByLabel(
"FEEDBACK_DELIVERY_DATE");
try
{
control.setStartDate(iso.parse(startDate).getTime());
assessment.getData().addAssessmentMetaData("hasAvailableDate", "true");
}
catch (Iso8601FormatException ex)
{
log.debug("Cannot set startDate.");
}
try
{
control.setDueDate(iso.parse(dueDate).getTime());
// assessment.getData().addAssessmentMetaData("hasDueDate", "true");
assessment.getData().addAssessmentMetaData("dueDate", "true");
}
catch (Iso8601FormatException ex)
{
log.debug("Cannot set dueDate.");
}
try
{
control.setRetractDate(iso.parse(retractDate).getTime());
assessment.getData().addAssessmentMetaData("hasRetractDate", "true");
}
catch (Iso8601FormatException ex)
{
log.debug("Cannot set retractDate.");
}
try
{
control.setFeedbackDate(iso.parse(feedbackDate).getTime());
assessment.getData().addAssessmentMetaData("FEEDBACK_DELIVERY","DATED");
}
catch (Iso8601FormatException ex)
{
log.debug("Cannot set feedbackDate.");
}
// don't know what site you will have in a new environment
// but registered as a BUG in SAM-271 so turning it on.
String releasedTo = assessment.getAssessmentMetaDataByLabel(
"ASSESSMENT_RELEASED_TO");
// for backwards compatibility with version 1.5 exports.
if (releasedTo != null && releasedTo.indexOf("Authenticated Users") > -1)
{
log.debug(
"Fixing obsolete reference to 'Authenticated Users', setting released to 'Anonymous Users'.");
releasedTo = "Anonymous Users";
}
// for backwards compatibility with version 1.5 exports.
if (releasedTo != null && releasedTo.indexOf("Authenticated Users") > -1)
{
log.debug(
"Fixing obsolete reference to 'Authenticated Users', setting released to 'Anonymous Users'.");
releasedTo = "Anonymous Users";
}
log.debug("control.setReleaseTo(releasedTo)='"+releasedTo+"'.");
control.setReleaseTo(releasedTo);
// Timed Assessment
if (duration != null)
{
try
{
Iso8601TimeInterval tiso = new Iso8601TimeInterval(duration);
log.debug("tiso.getDuration(): " + tiso.getDuration());
if(tiso==null)
{
throw new Iso8601FormatException("Assessment duration could not be resolved.");
}
long millisecondsDuration = tiso.getDuration();
int seconds = (int) millisecondsDuration /1000;
control.setTimeLimit(new Integer(seconds));
if (seconds !=0)
{
control.setTimedAssessment(AssessmentAccessControl.TIMED_ASSESSMENT);
assessment.getData().addAssessmentMetaData("hasTimeAssessment", "true");
}
else
{
control.setTimeLimit(new Integer(0));
control.setTimedAssessment(AssessmentAccessControl.
DO_NOT_TIMED_ASSESSMENT);
}
}
catch (Iso8601FormatException ex)
{
log.warn("Can't format assessment duration. " + ex);
control.setTimeLimit(new Integer(0));
control.setTimedAssessment(AssessmentAccessControl.
DO_NOT_TIMED_ASSESSMENT);
}
}
else
{
control.setTimeLimit(new Integer(0));
control.setTimedAssessment(AssessmentAccessControl.
DO_NOT_TIMED_ASSESSMENT);
}
log.debug("assessment.getAssessmentMetaDataByLabel(AUTO_SUBMIT): " +
assessment.getAssessmentMetaDataByLabel("AUTO_SUBMIT"));
if ("TRUE".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"AUTO_SUBMIT")))
{
log.debug("AUTO SUBMIT IS TRUE");
control.setAutoSubmit(AssessmentAccessControl.AUTO_SUBMIT);
assessment.getData().addAssessmentMetaData("hasAutoSubmit", "true");
}
else
{
control.setAutoSubmit(AssessmentAccessControl.DO_NOT_AUTO_SUBMIT);
}
// Assessment Organization
// navigation
if ("LINEAR".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"NAVIGATION")))
{
control.setItemNavigation(control.LINEAR_ACCESS);
}
else
{
control.setItemNavigation(control.RANDOM_ACCESS);
}
// numbering
if ("CONTINUOUS".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"QUESTION_NUMBERING")))
{
control.setItemNumbering(control.CONTINUOUS_NUMBERING);
}
else if ("RESTART".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"QUESTION_NUMBERING")))
{
control.setItemNumbering(control.RESTART_NUMBERING_BY_PART);
}
//question layout
if ("I".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"QUESTION_LAYOUT")))
{
control.setAssessmentFormat(control.BY_QUESTION);
}
else if ("S".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"QUESTION_LAYOUT")))
{
control.setAssessmentFormat(control.BY_PART);
}
else
{
control.setAssessmentFormat(control.BY_ASSESSMENT);
}
//Submissions
// submissions allowed
String maxAttempts =
"" + assessment.getAssessmentMetaDataByLabel("MAX_ATTEMPTS");
String unlimited = AuthoringConstantStrings.UNLIMITED_SUBMISSIONS;
log.debug("maxAttempts: '" + maxAttempts + "'");
log.debug("unlimited: '" + unlimited + "'");
if (
unlimited.equals(maxAttempts.trim()))
{
log.debug("unlimited.equals(maxAttempts.trim()");
control.setUnlimitedSubmissions(Boolean.TRUE);
control.setSubmissionsAllowed(AssessmentAccessControlIfc.
UNLIMITED_SUBMISSIONS);
}
else
{
control.setUnlimitedSubmissions(Boolean.FALSE);
try
{
control.setSubmissionsAllowed(new Integer(maxAttempts));
}
catch (NumberFormatException ex1)
{
control.setSubmissionsAllowed(new Integer("1"));
}
}
log.debug("Set: control.getSubmissionsAllowed()="+control.getSubmissionsAllowed());
log.debug("Set: control.getUnlimitedSubmissions()="+control.getUnlimitedSubmissions());
// late submissions
// I am puzzled as to why there is no ACCEPT_LATE_SUBMISSION, assuming it =T
if ("FALSE".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"LATE_HANDLING")))
{
control.setLateHandling(control.NOT_ACCEPT_LATE_SUBMISSION);
}
else
{
control.setLateHandling(new Integer(1));
}
// auto save
if ("TRUE".equalsIgnoreCase(assessment.getAssessmentMetaDataByLabel(
"AUTO_SAVE")))
{
control.setAutoSubmit(control.AUTO_SAVE);
}
// Submission Message
String submissionMessage = assessment.getAssessmentMetaDataByLabel(
"SUBMISSION_MESSAGE");
if (submissionMessage != null)
{
control.setSubmissionMessage(submissionMessage);
}
// Username, password, finalPageUrl
// String considerUserId = assessment.getAssessmentMetaDataByLabel(
// "CONSIDER_USERID"); //
String userId = assessment.getAssessmentMetaDataByLabel("USERID");
String password = assessment.getAssessmentMetaDataByLabel("PASSWORD");
String finalPageUrl = assessment.getAssessmentMetaDataByLabel("FINISH_URL");
if (//"TRUE".equalsIgnoreCase(considerUserId) &&
notNullOrEmpty(userId) && notNullOrEmpty(password))
{
control.setUsername(userId);
control.setPassword(password);
assessment.getData().addAssessmentMetaData("hasUsernamePassword", "true");
}
control.setFinalPageUrl(finalPageUrl);
assessment.setAssessmentAccessControl(control);
}
|
diff --git a/src/com/indivisible/tortidy/TestMenu.java b/src/com/indivisible/tortidy/TestMenu.java
index b0a2d21..6804d9a 100644
--- a/src/com/indivisible/tortidy/TestMenu.java
+++ b/src/com/indivisible/tortidy/TestMenu.java
@@ -1,45 +1,45 @@
package com.indivisible.tortidy;
import android.os.Bundle;
import android.app.ListActivity;
import android.content.Intent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class TestMenu extends ListActivity {
// file names of the activities to offer (remember to add to AndroidManifest!)
String[] tests = {
"MainActivity",
"test.TestTorHandler"
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(
TestMenu.this, android.R.layout.simple_list_item_1, tests));
Log.i("onCreate()", "Starting app...");
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Class<?> ourClass = null;
try {
String nextClass = tests[position];
- ourClass = Class.forName("com.indivisible.mightyv." + nextClass);
+ ourClass = Class.forName("com.indivisible.tortidy." + nextClass);
Intent ourIntent = new Intent(TestMenu.this, ourClass);
startActivity(ourIntent);
} catch (ClassNotFoundException e) {
Toast toast = Toast.makeText(TestMenu.this, "Not a suitable class", Toast.LENGTH_SHORT);
toast.show();
e.printStackTrace();
}
}
}
| true | true | protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Class<?> ourClass = null;
try {
String nextClass = tests[position];
ourClass = Class.forName("com.indivisible.mightyv." + nextClass);
Intent ourIntent = new Intent(TestMenu.this, ourClass);
startActivity(ourIntent);
} catch (ClassNotFoundException e) {
Toast toast = Toast.makeText(TestMenu.this, "Not a suitable class", Toast.LENGTH_SHORT);
toast.show();
e.printStackTrace();
}
}
| protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Class<?> ourClass = null;
try {
String nextClass = tests[position];
ourClass = Class.forName("com.indivisible.tortidy." + nextClass);
Intent ourIntent = new Intent(TestMenu.this, ourClass);
startActivity(ourIntent);
} catch (ClassNotFoundException e) {
Toast toast = Toast.makeText(TestMenu.this, "Not a suitable class", Toast.LENGTH_SHORT);
toast.show();
e.printStackTrace();
}
}
|
diff --git a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/PerfTestService.java b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/PerfTestService.java
index 05c57a1d..75e22481 100644
--- a/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/PerfTestService.java
+++ b/ngrinder-controller/src/main/java/org/ngrinder/perftest/service/PerfTestService.java
@@ -1,1554 +1,1555 @@
/*
* 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.ngrinder.perftest.service;
import static org.ngrinder.common.util.Preconditions.checkNotEmpty;
import static org.ngrinder.common.util.Preconditions.checkNotNull;
import static org.ngrinder.model.Status.getProcessingOrTestingTestStatus;
import static org.ngrinder.perftest.repository.PerfTestSpecification.createdBy;
import static org.ngrinder.perftest.repository.PerfTestSpecification.hasTag;
import static org.ngrinder.perftest.repository.PerfTestSpecification.idEmptyPredicate;
import static org.ngrinder.perftest.repository.PerfTestSpecification.idEqual;
import static org.ngrinder.perftest.repository.PerfTestSpecification.idRegionEqual;
import static org.ngrinder.perftest.repository.PerfTestSpecification.idSetEqual;
import static org.ngrinder.perftest.repository.PerfTestSpecification.likeTestNameOrDescription;
import static org.ngrinder.perftest.repository.PerfTestSpecification.scheduledTimeNotEmptyPredicate;
import static org.ngrinder.perftest.repository.PerfTestSpecification.statusSetEqual;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedSet;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import net.grinder.SingleConsole;
import net.grinder.StopReason;
import net.grinder.common.GrinderProperties;
import net.grinder.console.communication.AgentProcessControlImplementation.AgentStatus;
import net.grinder.console.model.ConsoleProperties;
import net.grinder.util.ConsolePropertiesFactory;
import net.grinder.util.Directory;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.collections.Predicate;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.hibernate.Hibernate;
import org.ngrinder.common.constant.NGrinderConstants;
import org.ngrinder.common.exception.NGrinderRuntimeException;
import org.ngrinder.infra.config.Config;
import org.ngrinder.infra.logger.CoreLogger;
import org.ngrinder.model.PerfTest;
import org.ngrinder.model.Permission;
import org.ngrinder.model.Role;
import org.ngrinder.model.Status;
import org.ngrinder.model.Tag;
import org.ngrinder.model.User;
import org.ngrinder.monitor.controller.model.SystemDataModel;
import org.ngrinder.perftest.model.PerfTestStatistics;
import org.ngrinder.perftest.model.ProcessAndThread;
import org.ngrinder.perftest.repository.PerfTestRepository;
import org.ngrinder.script.model.FileEntry;
import org.ngrinder.script.model.FileType;
import org.ngrinder.script.service.FileEntryService;
import org.ngrinder.service.IPerfTestService;
import org.python.google.common.collect.Lists;
import org.python.google.common.collect.Maps;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specifications;
import org.springframework.transaction.annotation.Transactional;
import com.google.gson.Gson;
/**
* {@link PerfTest} Service Class.
*
* This class contains various method which mainly get the {@link PerfTest} matching specific
* conditions from DB.
*
* @author JunHo Yoon
* @author Mavlarn
* @since 3.0
*/
public class PerfTestService implements NGrinderConstants, IPerfTestService {
private static final int MAX_POINT_COUNT = 100;
private static final Logger LOGGER = LoggerFactory.getLogger(PerfTestService.class);
private static final String DATA_FILE_EXTENSION = ".data";
@Autowired
private PerfTestRepository perfTestRepository;
@Autowired
private ConsoleManager consoleManager;
@Autowired
private AgentManager agentManager;
@Autowired
private Config config;
@Autowired
private FileEntryService fileEntryService;
@Autowired
private TagService tagSerivce;
/**
* Get {@link PerfTest} list on the user.
*
* @param user
* user
* @param query
* query string on test name or description
* @param tag
* seach tag.
* @param queryFilter
* "S" for querying scheduled test, "F" for querying finished test
* @param pageable
* paging info
* @return found {@link PerfTest} list
*/
public Page<PerfTest> getPerfTestList(User user, String query, String tag, String queryFilter, Pageable pageable) {
Specifications<PerfTest> spec = Specifications.where(idEmptyPredicate());
// User can see only his own test
if (user.getRole().equals(Role.USER)) {
spec = spec.and(createdBy(user));
}
if (StringUtils.isNotBlank(tag)) {
spec = spec.and(hasTag(tag));
}
if ("F".equals(queryFilter)) {
spec = spec.and(statusSetEqual(Status.FINISHED));
} else if ("S".equals(queryFilter)) {
spec = spec.and(statusSetEqual(Status.READY));
spec = spec.and(scheduledTimeNotEmptyPredicate());
}
if (StringUtils.isNotBlank(query)) {
spec = spec.and(likeTestNameOrDescription(query));
}
return perfTestRepository.findAll(spec, pageable);
}
/**
* Get {@link PerfTest} list on the user.
*
* @param user
* user
* @return found {@link PerfTest} list
*/
List<PerfTest> getPerfTestList(User user) {
Specifications<PerfTest> spec = Specifications.where(createdBy(user));
return perfTestRepository.findAll(spec);
}
/*
* (non-Javadoc)
*
* @see org.ngrinder.perftest.service.IPerfTestService#getPerfTest(org.ngrinder .model.User,
* java.lang.Integer)
*/
@Override
public PerfTest getPerfTest(User user, Long id) {
Specifications<PerfTest> spec = Specifications.where(idEmptyPredicate());
// User can see only his own test
if (user.getRole().equals(Role.USER)) {
spec = spec.and(createdBy(user));
}
spec = spec.and(idEqual(id));
return perfTestRepository.findOne(spec);
}
/*
* (non-Javadoc)
*
* @see org.ngrinder.perftest.service.IPerfTestService#getPerfTest(org.ngrinder .model.User,
* java.lang.Integer[])
*/
@Override
public List<PerfTest> getPerfTest(User user, Long[] ids) {
Specifications<PerfTest> spec = Specifications.where(idEmptyPredicate());
// User can see only his own test
if (user.getRole().equals(Role.USER)) {
spec = spec.and(createdBy(user));
}
spec = spec.and(idSetEqual(ids));
return perfTestRepository.findAll(spec);
}
/*
* (non-Javadoc)
*
* @see org.ngrinder.perftest.service.IPerfTestService#getPerfTestCount(org.ngrinder
* .model.User, org.ngrinder.perftest.model.Status)
*/
@Override
public long getPerfTestCount(User user, Status... statuses) {
Specifications<PerfTest> spec = Specifications.where(idEmptyPredicate());
// User can see only his own test
if (user != null) {
spec = spec.and(createdBy(user));
}
if (statuses.length != 0) {
spec = spec.and(statusSetEqual(statuses));
}
return perfTestRepository.count(spec);
}
/*
* (non-Javadoc)
*
* @see org.ngrinder.perftest.service.IPerfTestService#getPerfTest(org.ngrinder .model.User,
* org.ngrinder.perftest.model.Status)
*/
@Override
public List<PerfTest> getPerfTest(User user, Status... statuses) {
Specifications<PerfTest> spec = Specifications.where(idEmptyPredicate());
// User can see only his own test
if (user != null) {
spec = spec.and(createdBy(user));
}
if (statuses.length != 0) {
spec = spec.and(statusSetEqual(statuses));
}
return perfTestRepository.findAll(spec);
}
private List<PerfTest> getPerfTest(User user, String region, Status... statuses) {
Specifications<PerfTest> spec = Specifications.where(idEmptyPredicate());
// User can see only his own test
if (user != null) {
spec = spec.and(createdBy(user));
}
spec = spec.and(idRegionEqual(region));
if (statuses.length != 0) {
spec = spec.and(statusSetEqual(statuses));
}
return perfTestRepository.findAll(spec);
}
/*
* (non-Javadoc)
*
* @see org.ngrinder.perftest.service.IPerfTestService#savePerfTest(org.ngrinder .model.User,
* org.ngrinder.perftest.model.PerfTest)
*/
@Override
@Transactional
public PerfTest savePerfTest(User user, PerfTest perfTest) {
if (perfTest.getStatus() == Status.READY) {
FileEntry scriptEntry = fileEntryService.getFileEntry(user, perfTest.getScriptName());
long revision = scriptEntry != null ? scriptEntry.getRevision() : -1;
perfTest.setScriptRevision(revision);
}
SortedSet<Tag> tags = tagSerivce.addTags(user,
StringUtils.split(StringUtils.trimToEmpty(perfTest.getTagString()), ","));
perfTest.setTags(tags);
perfTest.setTagString(buildTagString(tags));
return savePerfTest(perfTest);
}
private String buildTagString(Set<Tag> tags) {
List<String> tagStringResult = new ArrayList<String>();
for (Tag each : tags) {
tagStringResult.add(each.getTagValue());
}
return StringUtils.join(tagStringResult, ",");
}
/*
* (non-Javadoc)
*
* @see org.ngrinder.perftest.service.IPerfTestService#savePerfTest(org.ngrinder
* .perftest.model.PerfTest )
*/
@Override
@Transactional
public PerfTest savePerfTest(PerfTest perfTest) {
checkNotNull(perfTest);
// Merge if necessary
if (perfTest.exist()) {
PerfTest existingPerfTest = perfTestRepository.findOne(perfTest.getId());
perfTest = existingPerfTest.merge(perfTest);
} else {
perfTest.clearMessages();
}
return perfTestRepository.save(perfTest);
}
/**
* Mark test error on {@link PerfTest} instance.
*
* @param perfTest
* {@link PerfTest}
* @param reason
* stop reason
* @return perftest with updated data
*/
@Transactional
public PerfTest markAbromalTermination(PerfTest perfTest, StopReason reason) {
return markAbromalTermination(perfTest, reason.name());
}
/**
* Mark test error on {@link PerfTest} instance.
*
* @param perfTest
* {@link PerfTest}
* @param reason
* stop reason
* @return perftest with updated data
*/
@Transactional
public PerfTest markAbromalTermination(PerfTest perfTest, String reason) {
// Leave last status as test error cause
perfTest.setTestErrorCause(perfTest.getStatus());
return markStatusAndProgress(perfTest, Status.ABNORMAL_TESTING, reason);
}
/*
* (non-Javadoc)
*
* @see org.ngrinder.service.IPerfTestService#markStatusAndProgress(org.ngrinder.model.PerfTest,
* org.ngrinder.model.Status, java.lang.String)
*/
@Transactional
@Override
public PerfTest markStatusAndProgress(PerfTest perfTest, Status status, String message) {
perfTest.setStatus(checkNotNull(status, "status should not be null"));
return markProgress(perfTest, message);
}
/**
* Add a progress message on the given perfTest.
*
* @param perfTest
* perf test
* @param message
* message to be recored.
* @return saved {@link PerfTest}
*/
@Transactional
public PerfTest markProgress(PerfTest perfTest, String message) {
checkNotNull(perfTest);
checkNotNull(perfTest.getId(), "perfTest should save Id");
perfTest.setLastProgressMessage(message);
LOGGER.debug("Progress : Test - {} : {}", perfTest.getId(), message);
return perfTestRepository.saveAndFlush(perfTest);
}
/**
* Add a progress message on the given perfTest and change the status.
*
* @param perfTest
* perf test
* @param status
* status to be recorded.
* @param message
* message to be recored.
* @return perftest with latest status and data
*/
@Transactional
public PerfTest markProgressAndStatus(PerfTest perfTest, Status status, String message) {
perfTest.setStatus(status);
return markProgress(perfTest, message);
}
/**
* Add a progress message on the given perfTest and change the status. In addition, the finish
* time and various test statistic are recorded as well.
*
* @param perfTest
* perf test
* @param status
* status to be recorded.
* @param message
* message to be recored.
* @return perftest with latest status and data
*/
@Transactional
public PerfTest markProgressAndStatusAndFinishTimeAndStatistics(PerfTest perfTest, Status status, String message) {
perfTest.setFinishTime(new Date());
updatePerfTestAfterTestFinish(perfTest);
return markProgressAndStatus(perfTest, status, message);
}
/**
* mark the perftest as {@link Status.START_CONSOLE_FINISHED} .
*
* @param perfTest
* perftest to mark
* @param consolePort
* port of the console, on which the test is running
*
* @return saved perftest
*/
@Transactional
public PerfTest markPerfTestConsoleStart(PerfTest perfTest, int consolePort) {
perfTest.setPort(consolePort);
return markProgressAndStatus(perfTest, Status.START_CONSOLE_FINISHED, "Console is started on port "
+ consolePort);
}
/*
* (non-Javadoc)
*
* @see org.ngrinder.perftest.service.IPerfTestService#getPerfTest(long)
*/
@Transactional
@Override
public PerfTest getPerfTestWithTag(Long testId) {
PerfTest findOne = perfTestRepository.findOne(testId);
if (findOne != null) {
Hibernate.initialize(findOne.getTags());
}
return findOne;
}
/*
* (non-Javadoc)
*
* @see org.ngrinder.perftest.service.IPerfTestService#getPerfTest(long)
*/
@Override
public PerfTest getPerfTest(Long testId) {
return perfTestRepository.findOne(testId);
}
/**
* Get next runnable PerfTest list.
*
* @return found {@link PerfTest} which is ready to run, null otherwise
*/
@Transactional
public PerfTest getPerfTestCandiate() {
List<PerfTest> readyPerfTests = perfTestRepository.findAllByStatusOrderByScheduledTimeAsc(Status.READY);
List<PerfTest> usersFirstPerfTests = filterCurrentlyRunningTestUsersTest(readyPerfTests);
return usersFirstPerfTests.isEmpty() ? null : readyPerfTests.get(0);
}
/**
* Get currently running {@link PerfTest} list.
*
* @return running test list
*/
public List<PerfTest> getCurrentlyRunningTest() {
return getPerfTest(null, Status.getProcessingOrTestingTestStatus());
}
/**
* Filter out {@link PerfTest} whose owner is running another test now..
*
* @param perfTestLists
* perf test
* @return filtered perf test
*/
protected List<PerfTest> filterCurrentlyRunningTestUsersTest(List<PerfTest> perfTestLists) {
List<PerfTest> currentlyRunningTests = getCurrentlyRunningTest();
final Set<User> currentlyRunningTestOwners = new HashSet<User>();
for (PerfTest each : currentlyRunningTests) {
currentlyRunningTestOwners.add(each.getCreatedUser());
}
CollectionUtils.filter(perfTestLists, new Predicate() {
@Override
public boolean evaluate(Object object) {
PerfTest perfTest = (PerfTest) object;
return !currentlyRunningTestOwners.contains(perfTest.getCreatedUser());
}
});
return perfTestLists;
}
/*
* (non-Javadoc)
*
* @see org.ngrinder.perftest.service.IPerfTestService#getTestingPerfTest()
*/
@Override
public List<PerfTest> getTestingPerfTest() {
return getPerfTest(null, config.getRegion(), Status.getTestingTestStates());
}
/**
* Get abnormally testing PerfTest.
*
* @return found {@link PerfTest} list
*/
public List<PerfTest> getAbnoramlTestingPerfTest() {
return getPerfTest(null, config.getRegion(), Status.ABNORMAL_TESTING);
}
/**
* Delete PerfTest by id.
*
* Never use this method in runtime. This method is used only for testing.
*
* @param user
* user
* @param id
* {@link PerfTest} id
*/
@Transactional
public void deletePerfTest(User user, long id) {
PerfTest perfTest = getPerfTest(id);
// If it's not requested by user who started job. It's wrong request.
if (!hasPermission(perfTest, user, Permission.DELETE_TEST_OFOTHER)) {
return;
}
SortedSet<Tag> tags = perfTest.getTags();
if (tags != null) {
tags.clear();
}
perfTestRepository.save(perfTest);
perfTestRepository.delete(perfTest);
deletePerfTestDirectory(perfTest);
}
/**
* Delete {@link PerfTest} directory.
*
* @param perfTest
* perfTest
*/
private void deletePerfTestDirectory(PerfTest perfTest) {
FileUtils.deleteQuietly(getPerfTestDirectory(perfTest));
}
/*
* (non-Javadoc)
*
* @see org.ngrinder.perftest.service.IPerfTestService#getPerfTestFilePath(org
* .ngrinder.perftest. model.PerfTest)
*/
@Override
public File getPerfTestStatisticPath(PerfTest perfTest) {
File perfTestStatisticPath = config.getHome().getPerfTestStatisticPath(perfTest);
if (!perfTestStatisticPath.exists()) {
perfTestStatisticPath.mkdirs();
}
return perfTestStatisticPath;
}
/*
* (non-Javadoc)
*
* @see org.ngrinder.perftest.service.IPerfTestService#getPerfTestFilePath(org
* .ngrinder.perftest. model.PerfTest)
*/
@Override
public File getPerfTestDistributionPath(PerfTest perfTest) {
return config.getHome().getPerfTestDistDirectory(perfTest);
}
/**
* Build custom class path on the given {@link PerfTest}.
*
* @param perfTest
* perftest
* @return custom class path.
*/
public String getCustomClassPath(PerfTest perfTest) {
File perfTestDirectory = getPerfTestDistributionPath(perfTest);
File libFolder = new File(perfTestDirectory, "lib");
final StringBuffer customClassPath = new StringBuffer();
customClassPath.append(".");
if (libFolder.exists()) {
customClassPath.append(File.pathSeparator).append("lib");
libFolder.list(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
if (name.endsWith(".jar")) {
customClassPath.append(File.pathSeparator).append("lib/").append(name);
}
return true;
}
});
}
return customClassPath.toString();
}
/**
* Create {@link GrinderProperties} based on the passed {@link PerfTest}.
*
* @param perfTest
* base data
* @return created {@link GrinderProperties} instance
*/
public GrinderProperties getGrinderProperties(PerfTest perfTest) {
FileWriter fileWriter = null;
try {
// Copy grinder properties
File userGrinderPropertiesPath = new File(getPerfTestDistributionPath(perfTest),
DEFAULT_GRINDER_PROPERTIES_PATH);
// FileUtils.copyFile(config.getHome().getDefaultGrinderProperties(),
// userGrinderPropertiesPath);
GrinderProperties grinderProperties = new GrinderProperties(config.getHome().getDefaultGrinderProperties());
User user = perfTest.getCreatedUser();
// Get all files in the script path
FileEntry userDefinedGrinderProperties = fileEntryService.getFileEntry(user, FilenameUtils.concat(
FilenameUtils.getPath(perfTest.getScriptName()), DEFAULT_GRINDER_PROPERTIES_PATH), perfTest
.getScriptRevision());
if (!config.isSecurityEnabled() && userDefinedGrinderProperties != null) {
// Make the property overridden by user property.
GrinderProperties userProperties = new GrinderProperties();
userProperties.load(new StringReader(userDefinedGrinderProperties.getContent()));
grinderProperties.putAll(userProperties);
}
grinderProperties.setAssociatedFile(new File(userGrinderPropertiesPath.getName()));
grinderProperties.setProperty(GrinderProperties.SCRIPT,
FilenameUtils.getName(checkNotEmpty(perfTest.getScriptName())));
grinderProperties.setProperty(GRINDER_PROP_TEST_ID, "test_" + perfTest.getId());
grinderProperties.setInt(GRINDER_PROP_THREAD, perfTest.getThreads());
grinderProperties.setInt(GRINDER_PROP_PROCESSES, perfTest.getProcesses());
if (perfTest.isThreshholdDuration()) {
grinderProperties.setLong(GRINDER_PROP_DURATION, perfTest.getDuration());
grinderProperties.setInt(GRINDER_PROP_RUNS, 0);
} else {
grinderProperties.setInt(GRINDER_PROP_RUNS, perfTest.getRunCount());
if (grinderProperties.containsKey(GRINDER_PROP_DURATION)) {
grinderProperties.remove(GRINDER_PROP_DURATION);
}
}
grinderProperties.setProperty(NGRINDER_PROP_ETC_HOSTS,
StringUtils.defaultIfBlank(perfTest.getTargetHosts(), ""));
grinderProperties.setBoolean(GRINDER_PROP_USE_CONSOLE, true);
if (BooleanUtils.isTrue(perfTest.getUseRampUp())) {
grinderProperties.setInt(GRINDER_PROP_PROCESS_INCREMENT, perfTest.getProcessIncrement());
grinderProperties.setInt(GRINDER_PROP_PROCESS_INCREMENT_INTERVAL,
perfTest.getProcessIncrementInterval());
grinderProperties.setInt(GRINDER_PROP_INITIAL_SLEEP_TIME, perfTest.getInitSleepTime());
} else {
grinderProperties.setInt(GRINDER_PROP_PROCESS_INCREMENT, 0);
}
grinderProperties.setProperty(GRINDER_PROP_USER, perfTest.getCreatedUser().getUserId());
grinderProperties.setProperty(GRINDER_PROP_JVM_CLASSPATH, getCustomClassPath(perfTest));
grinderProperties.setInt(GRINDER_PROP_IGNORE_SAMPLE_COUNT, perfTest.getIgnoreSampleCount());
grinderProperties.setBoolean(GRINDER_PROP_SECURITY, config.isSecurityEnabled());
// fileWriter = new FileWriter(userGrinderPropertiesPath);
// grinderProperties.store(fileWriter, perfTest.getTestIdentifier());
LOGGER.info("Grinder Properties : {} ", grinderProperties);
return grinderProperties;
} catch (Exception e) {
throw new NGrinderRuntimeException("error while prepare grinder property for " + perfTest.getTestName(), e);
} finally {
IOUtils.closeQuietly(fileWriter);
}
}
/**
* Prepare files for distribution. This method store the files on the path
* ${NGRINDER_HOME}/perftest/{test_id}/dist folder.
*
* @param perfTest
* perfTest
* @return File location in which the perftest should have.
*/
public File prepareDistribution(PerfTest perfTest) {
checkNotNull(perfTest.getId(), "perfTest should have id");
String scriptName = checkNotEmpty(perfTest.getScriptName(), "perfTest should have script name");
User user = perfTest.getCreatedUser();
// Get all files in the script path
FileEntry scriptEntry = checkNotNull(
fileEntryService.getFileEntry(user, perfTest.getScriptName(), perfTest.getScriptRevision()),
"script should exist");
List<FileEntry> fileEntries = fileEntryService.getLibAndResourcesEntries(user, checkNotEmpty(scriptName),
perfTest.getScriptRevision());
fileEntries.add(scriptEntry);
File perfTestDirectory = getPerfTestDistributionPath(perfTest);
perfTestDirectory.mkdirs();
String basePath = FilenameUtils.getPath(scriptEntry.getPath());
if (config.getSystemProperties().getPropertyBoolean("ngrinder.dist.logback", true)) {
// To minimize log..
InputStream io = null;
FileOutputStream fos = null;
try {
io = new ClassPathResource("/logback/logback-worker.xml").getInputStream();
fos = new FileOutputStream(new File(perfTestDirectory, "logback-worker.xml"));
IOUtils.copy(io, fos);
} catch (IOException e) {
LOGGER.error("error while writing logback-worker", e);
} finally {
IOUtils.closeQuietly(io);
IOUtils.closeQuietly(fos);
}
}
// Distribute each files in that folder.
for (FileEntry each : fileEntries) {
// Directory is not subject to be distributed.
if (each.getFileType() == FileType.DIR) {
continue;
}
String path = FilenameUtils.getPath(each.getPath());
path = path.substring(basePath.length());
File toDir = new File(perfTestDirectory, path);
LOGGER.info("{} is being written in {} for test {}",
new Object[] { each.getPath(), toDir, perfTest.getTestIdentifier() });
fileEntryService.writeContentTo(user, each.getPath(), toDir);
}
LOGGER.info("File write is completed in {}", perfTestDirectory);
return perfTestDirectory;
}
/**
* Get the process and thread policy java script.
*
* @return policy javascript
*/
public String getProcessAndThreadPolicyScript() {
return config.getProcessAndThreadPolicyScript();
}
/**
* Get the optimal process and thread count.
*
*
* @param newVuser
* the count of virtual users per agent
* @return optimal process thread count
*/
public ProcessAndThread calcProcessAndThread(int newVuser) {
try {
String script = getProcessAndThreadPolicyScript();
ScriptEngine engine = new ScriptEngineManager().getEngineByName("javascript");
engine.eval(script);
int processCount = ((Double) engine.eval("getProcessCount(" + newVuser + ")")).intValue();
int threadCount = ((Double) engine.eval("getThreadCount(" + newVuser + ")")).intValue();
return new ProcessAndThread(processCount, threadCount);
} catch (ScriptException e) {
LOGGER.error("Error occurs while calc process and thread", e);
}
return new ProcessAndThread(1, 1);
}
/**
* get the data point interval of report data. Use dataPointCount / imgWidth as the interval. if
* interval is 1, it means we will get all point from report. If interval is 2, it means we will
* get 1 point from every 2 data.
*
* @param testId
* test id
* @param dataType
* data type
* @param imgWidth
* image width
* @return interval interval value
*/
public int getReportDataInterval(long testId, String dataType, int imgWidth) {
int pointCount = Math.max(imgWidth, MAX_POINT_COUNT);
File reportFolder = config.getHome().getPerfTestReportDirectory(String.valueOf(testId));
int lineNumber;
int interval = 0;
File targetFile = new File(reportFolder, dataType + DATA_FILE_EXTENSION);
if (!targetFile.exists()) {
LOGGER.error("Report data for {} in {} does not exisit.", testId, dataType);
return 0;
}
LineNumberReader lnr = null;
FileInputStream in = null;
InputStreamReader isr = null;
try {
in = new FileInputStream(targetFile);
isr = new InputStreamReader(in);
lnr = new LineNumberReader(isr);
lnr.skip(targetFile.length());
lineNumber = lnr.getLineNumber() + 1;
interval = Math.max((int) (lineNumber / pointCount), 1);
} catch (Exception e) {
LOGGER.error("Get report data for " + dataType + " failed:" + e.getMessage(), e);
} finally {
IOUtils.closeQuietly(lnr);
IOUtils.closeQuietly(isr);
IOUtils.closeQuietly(in);
}
return interval;
}
/**
* get the test report data as a string. Use interval to control the data point count. interval
* is 1, mean get all data point.
*
* @param testId
* test id
* @param dataType
* data type
* @param interval
* interval to collect data
* @return report data report data of that type
*/
public String getReportDataAsString(long testId, String dataType, int interval) {
StringBuilder reportData = new StringBuilder("[");
File reportFolder = config.getHome().getPerfTestReportDirectory(String.valueOf(testId));
File targetFile = new File(reportFolder, dataType + DATA_FILE_EXTENSION);
if (!targetFile.exists()) {
LOGGER.error("Report data for {} in {} does not exisit.", testId, dataType);
return "[ ]";
}
FileReader reader = null;
BufferedReader br = null;
try {
reader = new FileReader(targetFile);
br = new BufferedReader(reader);
String data = br.readLine();
int current = 0;
while (StringUtils.isNotBlank(data)) {
if (0 == current) {
double number = NumberUtils.createDouble(StringUtils.defaultIfBlank(data, "0"));
reportData.append(number);
reportData.append(",");
}
if (++current >= interval) {
current = 0;
}
data = br.readLine();
}
if (reportData.charAt(reportData.length() - 1) == ',') {
reportData.deleteCharAt(reportData.length() - 1);
}
reportData.append("]");
} catch (IOException e) {
LOGGER.error("Get report data for {} failed: {}", dataType, e.getMessage());
LOGGER.debug("Trace is : ", e);
} finally {
IOUtils.closeQuietly(reader);
IOUtils.closeQuietly(br);
}
return reportData.toString();
}
/**
* Get report file(csv data) for give test .
*
* @param perfTest
* test
* @return reportFile data report file
*/
public File getReportFile(PerfTest perfTest) {
return new File(config.getHome().getPerfTestReportDirectory(perfTest), NGrinderConstants.REPORT_CSV);
}
/**
* Get log file names for give test .
*
* @param perfTest
* perfTest
* @param fileName
* file name of one logs of the test
* @return file report file path
*/
public File getLogFile(PerfTest perfTest, String fileName) {
return new File(getLogFileDirectory(perfTest), fileName);
}
/**
* Get log file names for give test id.
*
* @param testId
* test id
* @param fileName
* file name of one logs of the test
* @return file report file path
*/
public File getLogFile(long testId, String fileName) {
return new File(getLogFileDirectory(String.valueOf(testId)), fileName);
}
/**
* Get report file directory for give test .
*
* @param perfTest
* perfTest
* @return logDir log file path of the test
*/
public File getLogFileDirectory(PerfTest perfTest) {
return config.getHome().getPerfTestLogDirectory(perfTest);
}
/**
* Get report file directory for give test id.
*
* @param testId
* test id
* @return logDir log file path of the test
*/
public File getLogFileDirectory(String testId) {
return config.getHome().getPerfTestLogDirectory(testId);
}
/**
* Get log files list on the given test is.
*
* @param testId
* testId
* @return logFilesList log file list of that test
*/
public List<String> getLogFiles(long testId) {
File logFileDirectory = getLogFileDirectory(String.valueOf(testId));
if (!logFileDirectory.exists() || !logFileDirectory.isDirectory()) {
return Collections.emptyList();
}
return Arrays.asList(logFileDirectory.list());
}
/**
* Get report file directory for give test id .
*
* @param testId
* testId
* @return reportDir report file path
*/
public File getReportFileDirectory(long testId) {
return config.getHome().getPerfTestReportDirectory(String.valueOf(testId));
}
/**
* Get report file directory for give test .
*
* @param perfTest
* perftest
* @return reportDir report file path
*/
public File getReportFileDirectory(PerfTest perfTest) {
return config.getHome().getPerfTestReportDirectory(perfTest);
}
/**
* To save statistics data when test is running and put into cache after that. If the console is
* not available, it returns null.
*
* @param singleConsole
* console signle console.
* @param perfTestId
* perfTest Id
* @return statistics
*/
@Transactional
public Map<String, Object> saveStatistics(SingleConsole singleConsole, Long perfTestId) {
Map<String, Object> statictisData = singleConsole.getStatictisData();
Map<String, SystemDataModel> agentStatusMap = Maps.newHashMap();
final int singleConsolePort = singleConsole.getConsolePort();
for (AgentStatus each : agentManager.getAgentStatusSetConnectingToPort(singleConsolePort)) {
agentStatusMap.put(each.getAgentName(), each.getSystemDataModel());
}
PerfTest perfTest = getPerfTest(perfTestId);
perfTest.setRunningSample(gson.toJson(statictisData));
perfTest.setAgentStatus(gson.toJson(agentStatusMap));
savePerfTest(perfTest);
CoreLogger.LOGGER.debug("Data is {}", statictisData);
return statictisData;
}
/**
* get test running statistic data from cache. If there is no cache data, will return empty
* statistic data.
*
* @param perfTest
* perfTest
*
* @return test running statistic data
*/
@SuppressWarnings("unchecked")
public Map<String, Object> getStatistics(PerfTest perfTest) {
return gson.fromJson(perfTest.getRunningSample(), HashMap.class);
}
/**
* get test running statistic data from cache. If there is no cache data, will return empty
* statistic data.
*
* @param perfTest
* perfTest
*
* @return test running statistic data
*/
public String getStatisticsJson(PerfTest perfTest) {
return perfTest.getRunningSample();
}
private Gson gson = new Gson();
/**
* Save system monitor data of all agents connected to one console. If the console is not
* available, it returns empty map. After getting, it will be put into cache.
*
* @param singleConsole
* singleConsole of the test add this parameter just for the key of cache.
* @param perfTest
* perfTest
*/
public void saveAgentsInfo(SingleConsole singleConsole, PerfTest perfTest) {
savePerfTest(perfTest);
}
/**
* Get agent info from saved file.
*
* @param perfTest
* perftest
* @return agent info map
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public Map<String, HashMap> getAgentStat(PerfTest perfTest) {
return gson.fromJson(perfTest.getAgentStatus(), HashMap.class);
}
/*
* (non-Javadoc)
*
* @see org.ngrinder.perftest.service.IPerfTestService#getAllPerfTest()
*/
@Override
public List<PerfTest> getAllPerfTest() {
return perfTestRepository.findAll();
}
/**
* Create {@link ConsoleProperties} based on given {@link PerfTest} instance.
*
* @param perfTest
* perfTest
* @return {@link ConsoleProperties}
*/
public ConsoleProperties createConsoleProperties(PerfTest perfTest) {
ConsoleProperties consoleProperties = ConsolePropertiesFactory.createEmptyConsoleProperties();
try {
consoleProperties.setAndSaveDistributionDirectory(new Directory(getPerfTestDistributionPath(perfTest)));
consoleProperties.setConsoleHost(config.getCurrentIP());
} catch (Exception e) {
throw new NGrinderRuntimeException("Error while setting console properties", e);
}
return consoleProperties;
}
double parseDoubleWithSafety(Map<?, ?> map, Object key, Double defaultValue) {
Double doubleValue = MapUtils.getDouble(map, key, defaultValue);
return Math.round(doubleValue * 100D) / 100D;
}
/**
* Check if the given perfTest has too many errors. (20%)
*
* @param perfTest
* perftes t
* @return true if too many errors.
*/
@SuppressWarnings("unchecked")
public boolean hasTooManError(PerfTest perfTest) {
Map<String, Object> result = getStatistics(perfTest);
Map<String, Object> totalStatistics = MapUtils.getMap(result, "totalStatistics", MapUtils.EMPTY_MAP);
long tests = MapUtils.getDouble(totalStatistics, "Tests", 0D).longValue();
long errors = MapUtils.getDouble(totalStatistics, "Errors", 0D).longValue();
return ((((double) errors) / (tests + errors)) > 0.2d);
}
/**
* Update the given {@link PerfTest} properties after test finished.
*
* @param perfTest
* perfTest
*/
public void updatePerfTestAfterTestFinish(PerfTest perfTest) {
checkNotNull(perfTest);
Map<String, Object> result = getStatistics(perfTest);
@SuppressWarnings("unchecked")
Map<String, Object> totalStatistics = MapUtils.getMap(result, "totalStatistics", MapUtils.EMPTY_MAP);
LOGGER.info("Total Statistics for test {} is {}", perfTest.getId(), totalStatistics);
perfTest.setTps(parseDoubleWithSafety(totalStatistics, "TPS", 0D));
perfTest.setMeanTestTime(parseDoubleWithSafety(totalStatistics, "Mean_Test_Time_(ms)", 0D));
perfTest.setPeakTps(parseDoubleWithSafety(totalStatistics, "Peak_TPS", 0D));
perfTest.setTests(MapUtils.getDouble(totalStatistics, "Tests", 0D).longValue());
perfTest.setErrors(MapUtils.getDouble(totalStatistics, "Errors", 0D).longValue());
}
/**
* Get maximum concurrent test count.
*
* @return maximum concurrent test
*/
public int getMaximumConcurrentTestCount() {
return config.getSystemProperties().getPropertyInt(NGrinderConstants.NGRINDER_PROP_MAX_CONCURRENT_TEST,
NGrinderConstants.NGRINDER_PROP_MAX_CONCURRENT_TEST_VALUE);
}
/**
* Check the test can be executed more.
*
* @return true if possible
*/
public boolean canExecuteTestMore() {
return getPerfTestCount(null, Status.getProcessingOrTestingTestStatus()) < getMaximumConcurrentTestCount();
}
/*
* (non-Javadoc)
*
* @see org.ngrinder.perftest.service.IPerfTestService#stopPerfTest(org.ngrinder .model.User,
* java.lang.Long)
*/
@Override
@Transactional
public void stopPerfTest(User user, Long id) {
PerfTest perfTest = getPerfTest(id);
// If it's not requested by user who started job. It's wrong request.
if (!hasPermission(perfTest, user, Permission.STOP_TEST_OFOTHER)) {
return;
}
// If it's not stoppable status.. It's wrong request.
if (!perfTest.getStatus().isStoppable()) {
return;
}
// Just mark cancel on console
consoleManager.getConsoleUsingPort(perfTest.getPort()).cancel();
perfTest.setStopRequest(true);
perfTestRepository.save(perfTest);
}
/**
* Check if given user has a permission on perftest.
*
* @param perfTest
* perf test
* @param user
* user
* @param type
* permission type to check
* @return true if it has
*/
public boolean hasPermission(PerfTest perfTest, User user, Permission type) {
if (perfTest == null) {
return false;
}
if (perfTest.getCreatedUser().equals(user)) {
return true;
}
return user.getRole().hasPermission(type);
}
/*
* (non-Javadoc)
*
* @see org.ngrinder.perftest.service.IPerfTestService#getStopRequestedPerfTest()
*/
@Override
public List<PerfTest> getStopRequestedPerfTest() {
final List<PerfTest> perfTests = getPerfTest(null, config.getRegion(), getProcessingOrTestingTestStatus());
CollectionUtils.filter(perfTests, new Predicate() {
@Override
public boolean evaluate(Object object) {
return (((PerfTest) object).getStopRequest() == Boolean.TRUE);
}
});
return perfTests;
}
/*
* (non-Javadoc)
*
* @see org.ngrinder.perftest.service.IPerfTestService#addCommentOn(org.ngrinder .model.User,
* int, java.lang.String)
*/
@Override
@Transactional
public void addCommentOn(User user, Long testId, String testComment, String tagString) {
PerfTest perfTest = getPerfTest(user, testId);
perfTest.setTestComment(testComment);
perfTest.setTagString(tagString);
perfTest.setTags(tagSerivce.addTags(user, StringUtils.split(StringUtils.trimToEmpty(tagString), ",")));
perfTestRepository.save(perfTest);
}
/**
* get current running test status, which is, how many user run how many tests with some agents.
*
* @return PerfTestStatisticsList PerfTestStatistics list
*/
@Cacheable("current_perftest_statistics")
@Transactional
public Collection<PerfTestStatistics> getCurrentPerfTestStatistics() {
Map<User, PerfTestStatistics> perfTestPerUser = new HashMap<User, PerfTestStatistics>();
for (PerfTest each : getPerfTest(null, getProcessingOrTestingTestStatus())) {
User lastModifiedUser = each.getCreatedUser().getUserBaseInfo();
PerfTestStatistics perfTestStatistics = perfTestPerUser.get(lastModifiedUser);
if (perfTestStatistics == null) {
perfTestStatistics = new PerfTestStatistics(lastModifiedUser);
perfTestPerUser.put(lastModifiedUser, perfTestStatistics);
}
perfTestStatistics.addPerfTest(each);
}
return perfTestPerUser.values();
}
/**
* Get PerfTest directory in which {@link PerfTest} related files are saved.
*
* @param perfTest
* perfTest
* @return directory
*/
@Override
public File getPerfTestDirectory(PerfTest perfTest) {
return config.getHome().getPerfTestDirectory(perfTest);
}
/**
* Delete All PerfTests and related tags belonging to given user.
*
* @param user
* user
* @return deleted {@link PerfTest} list
*/
@Transactional
public List<PerfTest> deleteAllPerfTests(User user) {
List<PerfTest> perfTestList = getPerfTestList(user);
for (PerfTest each : perfTestList) {
each.getTags().clear();
}
perfTestRepository.save(perfTestList);
perfTestRepository.flush();
perfTestRepository.delete(perfTestList);
perfTestRepository.flush();
tagSerivce.deleteTags(user);
return perfTestList;
}
/**
* Remove given tag on the collection of {@link PerfTest}.
*
* @param perfTests
* perftest collection
* @param tag
* tag to be deleted
*/
@Transactional
public void removeTag(Collection<PerfTest> perfTests, Tag tag) {
for (PerfTest each : perfTests) {
each.getTags().remove(tag);
}
perfTestRepository.save(perfTests);
}
public PerfTestRepository getPerfTestRepository() {
return perfTestRepository;
}
public Config getConfig() {
return config;
}
public void setConfig(Config config) {
this.config = config;
}
/**
* Delete the distribution folder for the give perf test.
*
* @param perfTest
* perf test
*/
public void cleanUpDistFolder(PerfTest perfTest) {
FileUtils.deleteQuietly(getPerfTestDistributionPath(perfTest));
}
/**
* Clean up the data which is used in runtime only.
*
* @param perfTest
* perfTest
*/
public void cleanUpRuntimeOnlyData(PerfTest perfTest) {
perfTest.setRunningSample(null);
perfTest.setAgentStatus(null);
perfTest.setMonitorStatus(null);
savePerfTest(perfTest);
}
/**
* Put the given {@link org.ngrinder.monitor.share.domain.SystemInfo} maps into the given
* perftest entity.
*
* @param perfTestId
* id of perf test
* @param systemInfos
* systemDataModel map
*/
@Transactional
public void updateMonitorStat(Long perfTestId, Map<String, SystemDataModel> systemInfos) {
String json = gson.toJson(systemInfos);
if (json.length() >= 2000) {
Map<String, SystemDataModel> systemInfosNew = Maps.newHashMap();
int i = 0;
for (Entry<String, SystemDataModel> each : systemInfos.entrySet()) {
if (i++ > 3) {
break;
}
systemInfosNew.put(each.getKey(), each.getValue());
}
json = gson.toJson(systemInfosNew);
}
PerfTest perfTest = perfTestRepository.findOne(checkNotNull(perfTestId));
perfTest.setMonitorStatus(json);
perfTestRepository.save(perfTest);
}
/**
* Get monitor status map for the given perfTest.
*
* @param perfTest
* perf test
* @return map of monitor name and monitor status.
*/
@SuppressWarnings({ "unchecked", "rawtypes" })
public Map<String, HashMap> getMonitorStat(PerfTest perfTest) {
return gson.fromJson(perfTest.getMonitorStatus(), HashMap.class);
}
/**
* Get the monitor data interval value.
* In the normal, the image width is 700, and if the data count is too big, there will be too many points
* in the chart. So we will calculate the interval to get appropriate count of data to display.
* For example, interval value "2" means, get one record for every "2" records.
* @param testId
* test id
* @param monitorIP
* ip address of monitor target
* @param imageWidth
* image with of the chart.
* @return
* interval value.
*/
public int getSystemMonitorDataInterval(long testId, String monitorIP, int imageWidth) {
File monitorDataFile = new File(config.getHome().getPerfTestReportDirectory(String.valueOf(testId)),
Config.MONITOR_FILE_PREFIX + monitorIP + ".data");
int pointCount = Math.max(imageWidth, MAX_POINT_COUNT);
FileInputStream in = null;
InputStreamReader isr = null;
LineNumberReader lnr = null;
int lineNumber = 0;
int interval = 0;
try {
in = new FileInputStream(monitorDataFile);
isr = new InputStreamReader(in);
lnr = new LineNumberReader(isr);
lnr.skip(monitorDataFile.length());
lineNumber = lnr.getLineNumber() + 1;
interval = Math.max((int) (lineNumber / pointCount), 1);
} catch (FileNotFoundException e) {
LOGGER.error("Monitor data file not exist:{}", monitorDataFile);
LOGGER.error(e.getMessage(), e);
} catch (IOException e) {
LOGGER.error("Error while getting monitor:{} data file:{}", monitorIP, monitorDataFile);
LOGGER.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(lnr);
IOUtils.closeQuietly(isr);
IOUtils.closeQuietly(in);
}
return interval;
}
/**
* get system monitor data and wrap the data as a string value like "[22,11,12,34,....]", which can be used directly
* in JS as a vector
* @param testId
* test id
* @param monitorIP
* ip address of the monitor target
* @param dataInterval
* interval value to get data. Interval value "2" means, get one record for every "2" records.
* @return
* return the data in map
*/
public Map<String, String> getSystemMonitorDataAsString(long testId, String monitorIP, int dataInterval) {
Map<String, String> rtnMap = new HashMap<String, String>();
File monitorDataFile = new File(config.getHome().getPerfTestReportDirectory(String.valueOf(testId)),
Config.MONITOR_FILE_PREFIX + monitorIP + ".data");
BufferedReader br = null;
try {
StringBuilder sbUsedMem = new StringBuilder("[");
StringBuilder sbCPUUsed = new StringBuilder("[");
StringBuilder sbNetReceieved = null;
StringBuilder sbNetSent = null;
br = new BufferedReader(new FileReader(monitorDataFile));
br.readLine(); // skip the header.
// header: "ip,system,collectTime,freeMemory,totalMemory,cpuUsedPercentage,recivedPerSec,sentPerSec"
String line = br.readLine();
int skipCount = dataInterval;
//to be compatible with previous version, check the length before adding
boolean isNetDataExist = false;
if (StringUtils.split(line, ",").length > 6) {
isNetDataExist = true;
sbNetReceieved = new StringBuilder("[");
sbNetSent = new StringBuilder("[");
}
+ int kbSize = 1024;
while (StringUtils.isNotBlank(line)) {
if (skipCount < dataInterval) {
skipCount++;
continue;
} else {
skipCount = 1;
String[] datalist = StringUtils.split(line, ",");
- long usedMem = Long.valueOf(datalist[4]) - Long.valueOf(datalist[3]);
+ long usedMem = (Long.valueOf(datalist[4]) - Long.valueOf(datalist[3]))/kbSize;
sbUsedMem.append(usedMem).append(",");
sbCPUUsed.append(Float.valueOf(datalist[5])).append(",");
if (isNetDataExist) {
sbNetReceieved.append(Long.valueOf(datalist[6])).append(",");
sbNetSent.append(Long.valueOf(datalist[7])).append(",");
}
line = br.readLine();
}
}
int lastCharIndex = sbUsedMem.length()-1;
sbUsedMem.delete(lastCharIndex, lastCharIndex + 1); //remove last ","
sbUsedMem.append("]");
lastCharIndex = sbCPUUsed.length()-1;
sbCPUUsed.delete(lastCharIndex, lastCharIndex + 1);
sbCPUUsed.append("]");
rtnMap.put("cpu", sbCPUUsed.toString());
rtnMap.put("memory", sbUsedMem.toString());
if (isNetDataExist) {
lastCharIndex = sbNetReceieved.length()-1;
sbNetReceieved.delete(lastCharIndex, lastCharIndex + 1);
sbNetReceieved.append("]");
lastCharIndex = sbNetSent.length()-1;
sbNetSent.delete(lastCharIndex, lastCharIndex + 1);
sbNetSent.append("]");
rtnMap.put("received", sbNetReceieved.toString());
rtnMap.put("sent", sbNetSent.toString());
}
} catch (FileNotFoundException e) {
LOGGER.error("Monitor data file not exist:{}", monitorDataFile);
LOGGER.error(e.getMessage(), e);
} catch (IOException e) {
LOGGER.error("Error while getting monitor:{} data file:{}", monitorIP, monitorDataFile);
LOGGER.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(br);
}
return rtnMap;
}
/**
* Get all{@link SystemDataModel} from monitor data file of one test and target.
*
* @param testId
* test id
* @param monitorIP
* IP address of the monitor target
* @return SystemDataModel list
*/
public List<SystemDataModel> getSystemMonitorData(long testId, String monitorIP) {
LOGGER.debug("Get SystemMonitorData of test:{} ip:{}", testId, monitorIP);
List<SystemDataModel> rtnList = Lists.newArrayList();
File monitorDataFile = new File(config.getHome().getPerfTestReportDirectory(String.valueOf(testId)),
Config.MONITOR_FILE_PREFIX + monitorIP + ".data");
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(monitorDataFile));
br.readLine(); // skip the header.
// header: "ip,system,collectTime,freeMemory,totalMemory,cpuUsedPercentage"
String line = br.readLine();
while (StringUtils.isNotBlank(line)) {
SystemDataModel model = new SystemDataModel();
String[] datalist = StringUtils.split(line, ",");
model.setIp(datalist[0]);
model.setSystem(datalist[1]);
model.setCollectTime(Long.valueOf(datalist[2]));
model.setFreeMemory(Long.valueOf(datalist[3]));
model.setTotalMemory(Long.valueOf(datalist[4]));
model.setCpuUsedPercentage(Float.valueOf(datalist[5]));
rtnList.add(model);
line = br.readLine();
}
} catch (FileNotFoundException e) {
LOGGER.error("Monitor data file not exist:{}", monitorDataFile);
LOGGER.error(e.getMessage(), e);
} catch (IOException e) {
LOGGER.error("Error while getting monitor:{} data file:{}", monitorIP, monitorDataFile);
LOGGER.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(br);
}
LOGGER.debug("Finish getSystemMonitorData of test:{} ip:{}", testId, monitorIP);
return rtnList;
}
}
| false | true | public Map<String, String> getSystemMonitorDataAsString(long testId, String monitorIP, int dataInterval) {
Map<String, String> rtnMap = new HashMap<String, String>();
File monitorDataFile = new File(config.getHome().getPerfTestReportDirectory(String.valueOf(testId)),
Config.MONITOR_FILE_PREFIX + monitorIP + ".data");
BufferedReader br = null;
try {
StringBuilder sbUsedMem = new StringBuilder("[");
StringBuilder sbCPUUsed = new StringBuilder("[");
StringBuilder sbNetReceieved = null;
StringBuilder sbNetSent = null;
br = new BufferedReader(new FileReader(monitorDataFile));
br.readLine(); // skip the header.
// header: "ip,system,collectTime,freeMemory,totalMemory,cpuUsedPercentage,recivedPerSec,sentPerSec"
String line = br.readLine();
int skipCount = dataInterval;
//to be compatible with previous version, check the length before adding
boolean isNetDataExist = false;
if (StringUtils.split(line, ",").length > 6) {
isNetDataExist = true;
sbNetReceieved = new StringBuilder("[");
sbNetSent = new StringBuilder("[");
}
while (StringUtils.isNotBlank(line)) {
if (skipCount < dataInterval) {
skipCount++;
continue;
} else {
skipCount = 1;
String[] datalist = StringUtils.split(line, ",");
long usedMem = Long.valueOf(datalist[4]) - Long.valueOf(datalist[3]);
sbUsedMem.append(usedMem).append(",");
sbCPUUsed.append(Float.valueOf(datalist[5])).append(",");
if (isNetDataExist) {
sbNetReceieved.append(Long.valueOf(datalist[6])).append(",");
sbNetSent.append(Long.valueOf(datalist[7])).append(",");
}
line = br.readLine();
}
}
int lastCharIndex = sbUsedMem.length()-1;
sbUsedMem.delete(lastCharIndex, lastCharIndex + 1); //remove last ","
sbUsedMem.append("]");
lastCharIndex = sbCPUUsed.length()-1;
sbCPUUsed.delete(lastCharIndex, lastCharIndex + 1);
sbCPUUsed.append("]");
rtnMap.put("cpu", sbCPUUsed.toString());
rtnMap.put("memory", sbUsedMem.toString());
if (isNetDataExist) {
lastCharIndex = sbNetReceieved.length()-1;
sbNetReceieved.delete(lastCharIndex, lastCharIndex + 1);
sbNetReceieved.append("]");
lastCharIndex = sbNetSent.length()-1;
sbNetSent.delete(lastCharIndex, lastCharIndex + 1);
sbNetSent.append("]");
rtnMap.put("received", sbNetReceieved.toString());
rtnMap.put("sent", sbNetSent.toString());
}
} catch (FileNotFoundException e) {
LOGGER.error("Monitor data file not exist:{}", monitorDataFile);
LOGGER.error(e.getMessage(), e);
} catch (IOException e) {
LOGGER.error("Error while getting monitor:{} data file:{}", monitorIP, monitorDataFile);
LOGGER.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(br);
}
return rtnMap;
}
| public Map<String, String> getSystemMonitorDataAsString(long testId, String monitorIP, int dataInterval) {
Map<String, String> rtnMap = new HashMap<String, String>();
File monitorDataFile = new File(config.getHome().getPerfTestReportDirectory(String.valueOf(testId)),
Config.MONITOR_FILE_PREFIX + monitorIP + ".data");
BufferedReader br = null;
try {
StringBuilder sbUsedMem = new StringBuilder("[");
StringBuilder sbCPUUsed = new StringBuilder("[");
StringBuilder sbNetReceieved = null;
StringBuilder sbNetSent = null;
br = new BufferedReader(new FileReader(monitorDataFile));
br.readLine(); // skip the header.
// header: "ip,system,collectTime,freeMemory,totalMemory,cpuUsedPercentage,recivedPerSec,sentPerSec"
String line = br.readLine();
int skipCount = dataInterval;
//to be compatible with previous version, check the length before adding
boolean isNetDataExist = false;
if (StringUtils.split(line, ",").length > 6) {
isNetDataExist = true;
sbNetReceieved = new StringBuilder("[");
sbNetSent = new StringBuilder("[");
}
int kbSize = 1024;
while (StringUtils.isNotBlank(line)) {
if (skipCount < dataInterval) {
skipCount++;
continue;
} else {
skipCount = 1;
String[] datalist = StringUtils.split(line, ",");
long usedMem = (Long.valueOf(datalist[4]) - Long.valueOf(datalist[3]))/kbSize;
sbUsedMem.append(usedMem).append(",");
sbCPUUsed.append(Float.valueOf(datalist[5])).append(",");
if (isNetDataExist) {
sbNetReceieved.append(Long.valueOf(datalist[6])).append(",");
sbNetSent.append(Long.valueOf(datalist[7])).append(",");
}
line = br.readLine();
}
}
int lastCharIndex = sbUsedMem.length()-1;
sbUsedMem.delete(lastCharIndex, lastCharIndex + 1); //remove last ","
sbUsedMem.append("]");
lastCharIndex = sbCPUUsed.length()-1;
sbCPUUsed.delete(lastCharIndex, lastCharIndex + 1);
sbCPUUsed.append("]");
rtnMap.put("cpu", sbCPUUsed.toString());
rtnMap.put("memory", sbUsedMem.toString());
if (isNetDataExist) {
lastCharIndex = sbNetReceieved.length()-1;
sbNetReceieved.delete(lastCharIndex, lastCharIndex + 1);
sbNetReceieved.append("]");
lastCharIndex = sbNetSent.length()-1;
sbNetSent.delete(lastCharIndex, lastCharIndex + 1);
sbNetSent.append("]");
rtnMap.put("received", sbNetReceieved.toString());
rtnMap.put("sent", sbNetSent.toString());
}
} catch (FileNotFoundException e) {
LOGGER.error("Monitor data file not exist:{}", monitorDataFile);
LOGGER.error(e.getMessage(), e);
} catch (IOException e) {
LOGGER.error("Error while getting monitor:{} data file:{}", monitorIP, monitorDataFile);
LOGGER.error(e.getMessage(), e);
} finally {
IOUtils.closeQuietly(br);
}
return rtnMap;
}
|
diff --git a/src/main/java/ch/o2it/weblounge/test/site/GreeterJob.java b/src/main/java/ch/o2it/weblounge/test/site/GreeterJob.java
index 83a69ff53..e1819b633 100644
--- a/src/main/java/ch/o2it/weblounge/test/site/GreeterJob.java
+++ b/src/main/java/ch/o2it/weblounge/test/site/GreeterJob.java
@@ -1,70 +1,70 @@
/*
* Weblounge: Web Content Management System
* Copyright (c) 2010 The Weblounge Team
* http://weblounge.o2it.ch
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package ch.o2it.weblounge.test.site;
import ch.o2it.weblounge.common.scheduler.JobWorker;
import ch.o2it.weblounge.common.scheduler.JobException;
import ch.o2it.weblounge.test.util.TestSiteUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.Dictionary;
import java.util.Map;
/**
* Test job that will print a friendly greeting to <code>System.out</code>.
*/
@SuppressWarnings("unchecked")
public class GreeterJob implements JobWorker {
/** Logging facility */
protected static final Logger logger = LoggerFactory.getLogger(GreeterJob.class);
/** Hello world in many languages */
protected static Map.Entry<String, String>[] greetings = null;
static {
Map<String, String> hellos = TestSiteUtils.loadGreetings();
greetings = hellos.entrySet().toArray(new Map.Entry[hellos.size()]);
}
/**
* {@inheritDoc}
*
* @see ch.o2it.weblounge.common.scheduler.JobWorker#execute(java.lang.String,
* java.util.Dictionary)
*/
public void execute(String name, Dictionary<String, Serializable> ctx)
throws JobException {
int index = (int) ((greetings.length - 1) * Math.random());
Map.Entry<String, String> entry = greetings[index];
try {
- logger.info(new String(entry.getValue().getBytes("utf-8")) + " (" + entry.getKey() + ")");
+ logger.info(new String(entry.getValue().getBytes("utf-8"), "utf-8") + " (" + entry.getKey() + ")");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| true | true | public void execute(String name, Dictionary<String, Serializable> ctx)
throws JobException {
int index = (int) ((greetings.length - 1) * Math.random());
Map.Entry<String, String> entry = greetings[index];
try {
logger.info(new String(entry.getValue().getBytes("utf-8")) + " (" + entry.getKey() + ")");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
| public void execute(String name, Dictionary<String, Serializable> ctx)
throws JobException {
int index = (int) ((greetings.length - 1) * Math.random());
Map.Entry<String, String> entry = greetings[index];
try {
logger.info(new String(entry.getValue().getBytes("utf-8"), "utf-8") + " (" + entry.getKey() + ")");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
diff --git a/src/mainWindow.java b/src/mainWindow.java
index 7146153..cc85da2 100644
--- a/src/mainWindow.java
+++ b/src/mainWindow.java
@@ -1,834 +1,834 @@
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.ButtonGroup;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JList;
import javax.swing.JSeparator;
import javax.swing.JTextArea;
import java.awt.CardLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.GridLayout;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.Transparency;
import javax.swing.JButton;
import javax.swing.border.BevelBorder;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.AbstractListModel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.PixelGrabber;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import javax.swing.JTable;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
public class mainWindow {
/**
* The list of command categories
*/
final JList groupList = new JList();
/**
* The entire panel on the left-hand side
*/
final JList cmdList = new JList();
JTextArea mAr, tAr, bAa, bAb;
JPanel argPanel,codePanel;
private CardLayout cl;
JTextArea codeTextArea;
private double angle = 0;
/**
* The main window for the program
*/
JFrame window;
Driver d;
int gnum=-1;
private JTable rightTable;
final int RUN_MENU = 0;
final int SCAN_MENU = 1;
final int BULLET_MENU = 2;
final int WALL_MENU = 3;
private final Font labelFont = new Font(null, 1, 15);
/**
* Create the application.
*/
public mainWindow(Driver d) {
this.d = d;
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
Font labelFont = new Font(null, 1, 15);
ImageIcon icon = new ImageIcon("images/icon.png");
// Setup the window
window = new JFrame("RoboCode");
window.setSize(new Dimension(1400, 700));
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setIconImage(icon.getImage());
//----[Begin Left-Hand Panel]----
int cmdPanelWidth = 200;
int cmdPanelHeight = window.getHeight();
int groupListHeight = 200;
int cmdListHeight = 400;
// Setup the panel to hold the left side
JPanel cmdPanel = new JPanel();
cmdPanel.setPreferredSize(new Dimension(cmdPanelWidth, cmdPanelHeight));
cmdPanel.setLayout(new BoxLayout(cmdPanel, BoxLayout.PAGE_AXIS));
// Setup the list of groups of commands
JLabel groupListText = new JLabel("Action Categories");
groupListText.setFont(labelFont);
groupListText.setAlignmentX(Component.LEFT_ALIGNMENT);
groupList.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent arg0) {
switchCmdList(groupList.getSelectedIndex());
}
});
groupList.setModel(new AbstractListModel() {
private static final long serialVersionUID = 1L;
String[] values = new String[] {"Basic Movement", "Basic Turning", "Basic Gun Control", "Advanced Turning"};
public int getSize() {
return values.length;
}
public Object getElementAt(int index) {
return values[index];
}
});
groupList.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
groupList.setPreferredSize(new Dimension(groupListHeight, cmdPanelWidth));
groupList.setSelectedIndex(0);
groupList.setAlignmentX(Component.LEFT_ALIGNMENT);
groupList.setFixedCellWidth(cmdPanelWidth);
// Setup the list of commands
JLabel cmdListText = new JLabel("Available Actions");
//cmdListText.setBounds(10, 145, 200, 20);
cmdListText.setFont(labelFont);
cmdListText.setAlignmentX(Component.LEFT_ALIGNMENT);
cmdList.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent me) {
switchCmd(groupList.getSelectedIndex(), cmdList.getSelectedIndex());
}
});
cmdList.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
cmdList.setAlignmentX(Component.LEFT_ALIGNMENT);
cmdList.setPreferredSize(new Dimension(cmdListHeight, cmdPanelWidth));
cmdList.setFixedCellWidth(200);
cmdPanel.add(Box.createRigidArea(new Dimension(0,10)));
cmdPanel.add(groupListText);
cmdPanel.add(Box.createRigidArea(new Dimension(0,5)));
cmdPanel.add(groupList);
cmdPanel.add(Box.createRigidArea(new Dimension(0,10)));
cmdPanel.add(cmdListText);
cmdPanel.add(Box.createRigidArea(new Dimension(0,5)));
cmdPanel.add(cmdList);
cmdPanel.add(Box.createVerticalGlue());
//----[End Left-Hand Panel]----
//----[Begin Middle Panel]----
int controlPanelWidth = 100;
int controlPanelHeight = window.getHeight();
JPanel addPanel = new JPanel();
addPanel.setPreferredSize(new Dimension(controlPanelWidth, controlPanelHeight));
addPanel.setLayout(new BoxLayout(addPanel, BoxLayout.PAGE_AXIS));
JLabel paramText = new JLabel("Parameters");
paramText.setFont(labelFont);
paramText.setAlignmentX(Component.CENTER_ALIGNMENT);
//=========================================================START PETER'S CODE
JPanel turning, moving, fire, wait, both, blank=new JPanel();
turning=new JPanel();
JLabel tLb=new JLabel("Degrees: ");
tAr=new JTextArea("0",1,4);
turning.add(tLb);
turning.add(tAr);
tAr.getDocument().addDocumentListener(new DocumentListener(){
@Override
public void changedUpdate(DocumentEvent source) {
Document sourceDocument = source.getDocument();
if(sourceDocument.getLength() == 0){
angle = 0;
}else{
try {
angle = Math.toRadians(Integer.parseInt(sourceDocument.getText(0, sourceDocument.getLength())));
} catch (NumberFormatException e) {
// Do nothing
} catch (BadLocationException e) {
// Do nothing
}
window.repaint();
}
}
@Override
public void insertUpdate(DocumentEvent source) {
changedUpdate(source);
}
@Override
public void removeUpdate(DocumentEvent source) {
changedUpdate(source);
}
});
moving=new JPanel();
JLabel mLb=new JLabel("Pixels: ");
mAr=new JTextArea("0",1,4);
moving.add(mLb);
moving.add(mAr);
both=new JPanel();
both.add(new JLabel("Pixels: "));
bAa=new JTextArea("0",1,4);
both.add(bAa);
both.add(new JLabel("Degrees: "));
bAb=new JTextArea("0",1,4);
both.add(bAb);
fire=new JPanel();
fire.add(new JLabel("Fire"));
wait=new JPanel();
wait.add(new JLabel("Wait"));
cl=new CardLayout();
argPanel=new JPanel(cl);
argPanel.add(blank,"Blank");
argPanel.add(turning,"Turning");
argPanel.add(moving,"Moving");
argPanel.add(both,"Both");
argPanel.add(fire,"Fire");
argPanel.add(wait,"Wait");
argPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
argPanel.setMaximumSize(new Dimension(controlPanelWidth, 300));
switchCmdList(0);
//////////////////////
//===========================================================END PETER'S CODE
JLabel addBtnText = new JLabel("Add Action");
addBtnText.setFont(labelFont);
addBtnText.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton addBtn = new JButton(">>");
addBtn.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent evt) {
addCmd();
}
});
addBtn.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel rmvBtnText = new JLabel("Remove Action");
rmvBtnText.setFont(labelFont);
rmvBtnText.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton rmvBtn = new JButton("<<");
rmvBtn.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent evt){
removeCmd();
}
});
rmvBtn.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel generateBtnText = new JLabel("Generate Code");
generateBtnText.setFont(labelFont);
generateBtnText.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton generateBtn = new JButton("Start!");
generateBtn.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent me) {
Writer.writeToJavaFile(d.run.data,d.scan.data,d.bullet.data,d.wall.data);
addCodeToWindow();
JOptionPane.showMessageDialog(null, "Code Generated to D drive","Generation Success", 1);
}
});
generateBtn.setAlignmentX(Component.CENTER_ALIGNMENT);
addPanel.add(Box.createRigidArea(new Dimension(0,10)));
addPanel.add(programInfo());
addPanel.add(Box.createRigidArea(new Dimension(0,10)));
addPanel.add(robotDisplay());
addPanel.add(Box.createRigidArea(new Dimension(0,10)));
addPanel.add(paramText);
addPanel.add(Box.createRigidArea(new Dimension(0,5)));
addPanel.add(argPanel);
addPanel.add(Box.createRigidArea(new Dimension(0,10)));
addPanel.add(addBtnText);
addPanel.add(Box.createRigidArea(new Dimension(0,5)));
addPanel.add(addBtn);
addPanel.add(Box.createRigidArea(new Dimension(0,10)));
addPanel.add(rmvBtnText);
addPanel.add(Box.createRigidArea(new Dimension(0,5)));
addPanel.add(rmvBtn);
addPanel.add(Box.createRigidArea(new Dimension(0,10)));
addPanel.add(generateBtnText);
addPanel.add(Box.createRigidArea(new Dimension(0,5)));
addPanel.add(generateBtn);
addPanel.add(Box.createVerticalGlue());
//addPanel.setBorder(BorderFactory.createLineBorder(Color.black));
//----[End Middle Panel]----
//----[Begin Right-Hand Panel]----
//addPanel.setBounds(220, 10, 200, 420);
//addPanel.setLayout(new BoxLayout(addPanel, BoxLayout.PAGE_AXIS));
JPanel rightPanel = new JPanel();
rightPanel.setPreferredSize(new Dimension(200, 600));
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.PAGE_AXIS));
JLabel modeBtnText = new JLabel("Operating Modes");
modeBtnText.setFont(labelFont);
modeBtnText.setAlignmentX(Component.LEFT_ALIGNMENT);
JPanel radioButtons = new JPanel();
radioButtons.setLayout(new GridLayout(2, 2));
radioButtons.setMaximumSize(new Dimension(250, 50));
JRadioButton radioRun = new JRadioButton("Standard Behavior");
radioRun.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent arg0) {
switchRightList(RUN_MENU);
}
});
radioRun.setSelected(true);
JRadioButton radioScan = new JRadioButton("Scan Robot");
radioScan.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
switchRightList(SCAN_MENU);
}
});
JRadioButton radioBullet = new JRadioButton("Hit By Bullet");
radioBullet.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
switchRightList(BULLET_MENU);
}
});
JRadioButton radioWall = new JRadioButton("Hit Wall");
radioWall.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
switchRightList(WALL_MENU);
}
});
// Group the radio buttons
ButtonGroup methodChoice = new ButtonGroup();
methodChoice.add(radioRun);
methodChoice.add(radioScan);
methodChoice.add(radioBullet);
methodChoice.add(radioWall);
radioButtons.add(radioRun);
radioButtons.add(radioScan);
radioButtons.add(radioBullet);
radioButtons.add(radioWall);
radioButtons.setAlignmentX(Component.LEFT_ALIGNMENT);
JLabel currActionsText = new JLabel("Current Actions");
currActionsText.setFont(labelFont);
String columnNames[] = {"Action", "Parameters"};
rightTable = new JTable(null, columnNames);
rightTable.setModel(d.run);
rightTable.getColumnModel().getColumn(0).setResizable(false);
rightTable.getColumnModel().getColumn(1).setResizable(false);
rightTable.setPreferredScrollableViewportSize(new Dimension(200, 300));
JScrollPane rightScrollPane = new JScrollPane(rightTable);
rightScrollPane.setAlignmentX(Component.LEFT_ALIGNMENT);
//rightScrollPane.setLocation(0, 70);
//rightScrollPane.setSize(278, 607);
rightPanel.add(Box.createRigidArea(new Dimension(0,10)));
rightPanel.add(modeBtnText);
rightPanel.add(Box.createRigidArea(new Dimension(0,5)));
rightPanel.add(radioButtons);
rightPanel.add(Box.createRigidArea(new Dimension(0,10)));
rightPanel.add(currActionsText);
rightPanel.add(Box.createRigidArea(new Dimension(0,5)));
rightPanel.add(rightScrollPane);
rightPanel.add(Box.createVerticalGlue());
// Create the live text editor
int codePanelWidth = 600;
int codeAreaHeight = 400;
codePanel = new JPanel();
codePanel.setPreferredSize(new Dimension(codePanelWidth,window.getHeight()));
codePanel.setLayout(new BoxLayout(codePanel, BoxLayout.PAGE_AXIS));
JLabel codePanelText = new JLabel("Generated Code");
codePanelText.setFont(labelFont);
codePanelText.setAlignmentX(Component.LEFT_ALIGNMENT);
codeTextArea = new JTextArea();
codeTextArea.setEditable(false);
- codeTextArea.setPreferredSize(new Dimension(codePanelWidth-10, codeAreaHeight-10));
+ //codeTextArea.setPreferredSize(new Dimension(codePanelWidth-10, codeAreaHeight-10));
codeTextArea.setText("No Actions");
codeTextArea.setAlignmentX(Component.LEFT_ALIGNMENT);
JScrollPane codeScrollPane = new JScrollPane(codeTextArea);
codeScrollPane.setPreferredSize(new Dimension(codePanelWidth, codeAreaHeight));
codeScrollPane.setAlignmentX(Component.LEFT_ALIGNMENT);
codePanel.add(Box.createRigidArea(new Dimension(0,10)));
codePanel.add(codePanelText);
codePanel.add(Box.createRigidArea(new Dimension(0,5)));
codePanel.add(codeScrollPane);
codePanel.add(Box.createVerticalGlue());
// Add the panes to the windows
Container windowContent = window.getContentPane();
windowContent.setLayout(new BoxLayout(windowContent, BoxLayout.LINE_AXIS));
windowContent.add(Box.createHorizontalGlue());
windowContent.add(cmdPanel);
windowContent.add(Box.createRigidArea(new Dimension(10, 0)));
windowContent.add(addPanel);
windowContent.add(Box.createRigidArea(new Dimension(10, 0)));
windowContent.add(rightPanel);
windowContent.add(Box.createRigidArea(new Dimension(10, 0)));
windowContent.add(codePanel);
windowContent.add(Box.createHorizontalGlue());
window.setJMenuBar(createMenuBar());
}
protected void addCodeToWindow() {
File codeFile = new File("D:\\DD_Robot.java");
try {
Scanner fileScan = new Scanner(codeFile);
String fileLine = "";
while(fileScan.hasNext()){
fileLine += fileScan.nextLine() + "\n";
}
codeTextArea.setText(fileLine);
fileScan.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
codePanel.repaint();
}
private JMenuBar createMenuBar(){
JMenuBar menuBar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
fileMenu.setMnemonic(KeyEvent.VK_F);
JMenuItem fileQuit = new JMenuItem("Quit");
fileQuit.setMnemonic(KeyEvent.VK_Q);
fileQuit.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
if(JOptionPane.showConfirmDialog(window, "Are you sure you want to quit?") == JOptionPane.YES_OPTION){
System.exit(0);
}
}
});
JMenuItem fileAbout = new JMenuItem("About");
fileAbout.setMnemonic(KeyEvent.VK_A);
fileAbout.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent arg0) {
ImageIcon icon = new ImageIcon("images/acmLogo.png");
JOptionPane.showMessageDialog(window, "RoboGen V1.0\n" +
"Written by the members of the MSOE Chapter of ACM\n" +
"�2011\n\n" +
"Designed for use with Robocode\n" +
"http://robocode.sourceforge.net/",
"About RoboGen", JOptionPane.INFORMATION_MESSAGE, icon);
}
});
fileMenu.add(fileAbout);
fileMenu.add(new JSeparator());
fileMenu.add(fileQuit);
menuBar.add(fileMenu);
return menuBar;
}
private JPanel robotDisplay(){
JPanel returnPanel = new JPanel();
returnPanel.setLayout(new BoxLayout(returnPanel, BoxLayout.PAGE_AXIS));
returnPanel.setMinimumSize(new Dimension(100, 200));
try{
JLayeredPane robotPane = new JLayeredPane();
robotPane.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel robotText = new JLabel("Sample Robot");
robotText.setFont(labelFont);
robotText.setAlignmentX(Component.CENTER_ALIGNMENT);
ImageIcon bodyIcon = new ImageIcon("images/body.png");
final BufferedImage turretIcon = toBufferedImage(Toolkit.getDefaultToolkit().createImage("images/turret.png"));
JLabel bodyLabel = new JLabel(bodyIcon);
bodyLabel.setBounds(60, 10, bodyIcon.getIconWidth(), bodyIcon.getIconHeight());
bodyLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
JPanel turretLabel = new JPanel(){
private static final long serialVersionUID = 1L;
@Override
public Dimension getPreferredSize(){
return new Dimension(turretIcon.getWidth(), turretIcon.getHeight());
}
@Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.rotate(angle, (turretIcon.getWidth() / 2) + 26, (turretIcon.getHeight() / 2));
g2.drawImage(turretIcon, 26, 0, null);
}
};
turretLabel.setBounds(42, 0, 70, 70);
turretLabel.setAlignmentX(Component.CENTER_ALIGNMENT);
turretLabel.setOpaque(false);
robotPane.add(bodyLabel, new Integer(0));
robotPane.add(turretLabel, new Integer(1));
//turretLabel.setBorder(BorderFactory.createLineBorder(Color.black));
returnPanel.add(robotText);
returnPanel.add(Box.createRigidArea(new Dimension(0,5)));
returnPanel.add(robotPane);
//returnPanel.add(Box.createVerticalGlue());
//returnPanel.setBorder(BorderFactory.createLineBorder(Color.black));
}catch(Exception e){
}
return returnPanel;
}
private JPanel programInfo(){
ImageIcon icon = new ImageIcon("images/icon.png");
JPanel returnPanel = new JPanel();
returnPanel.setLayout(new BoxLayout(returnPanel, BoxLayout.PAGE_AXIS));
JLabel programIcon = new JLabel(icon);
programIcon.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel programName = new JLabel("RoboGen");
programName.setFont(labelFont);
programName.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel programVersion = new JLabel("Version 1.0");
programVersion.setFont(labelFont);
programVersion.setAlignmentX(Component.CENTER_ALIGNMENT);
returnPanel.add(programIcon);
returnPanel.add(Box.createRigidArea(new Dimension(0, 10)));
returnPanel.add(programName);
returnPanel.add(programVersion);
return returnPanel;
}
private void switchCmdList(int index) {
switch(index) {
case 0:
cmdList.setModel(d.bMove);
break;
case 1:
cmdList.setModel(d.bTurn);
break;
case 2:
cmdList.setModel(d.bGun);
break;
case 3:
cmdList.setModel(d.aTurn);
break;
default:
cmdList.setModel(d.bMove);
break;
}
cmdList.setSelectedIndex(0);
switchCmd(index,0);
gnum=index;
}
public void switchCmd(int group, int cmd) {
switch(group){
case 0:
switch(cmd){
case 0:
case 1:
cl.show(argPanel, "Moving");
break;
case 2:
cl.show(argPanel, "Wait");
break;
}
break;
case 1:
cl.show(argPanel, "Turning");
break;
case 2:
switch(cmd){
case 0:
cl.show(argPanel, "Fire");
break;
case 1:
case 2:
case 3:
cl.show(argPanel, "Turning");
break;
}
break;
case 3:
cl.show(argPanel, "Both");
break;
}
}
public String getParams() {
int group=gnum;
int cmd=cmdList.getSelectedIndex();
switch(group){
case 0:
if(cmd!=2)
{
return mAr.getText();
}
break;
case 1:
return tAr.getText();
case 2:
if(cmd!=0){
return tAr.getText();
}
break;
case 3:
return bAa.getText()+", "+bAb.getText();
}
return "";
}
private void switchRightList(int menu) {
switch(menu) {
case RUN_MENU:
rightTable.setModel(d.run);
break;
case SCAN_MENU:
rightTable.setModel(d.scan);
break;
case BULLET_MENU:
rightTable.setModel(d.bullet);
break;
case WALL_MENU:
rightTable.setModel(d.wall);
break;
default:
rightTable.setModel(d.run);
break;
}
}
/**
* Pressing the add button. Gets the method chosen
* and any arguments associated with the method.
*/
private void addCmd() {
rightTableModel rModel = (rightTableModel) rightTable.getModel();
String selectedValue = (String)cmdList.getSelectedValue();
rModel.addValueAt(selectedValue,getParams());
rightTable.repaint();
}
private void removeCmd(){
rightTableModel rModel = (rightTableModel) rightTable.getModel();
int[] selectedRows = rightTable.getSelectedRows();
for(int i = 0; i < selectedRows.length; i++){
System.out.println("" + i + " - Removing index: " + (selectedRows[i] - i));
rModel.removeValueAt(selectedRows[i] - i);
}
rightTable.repaint();
}
// This method returns a buffered image with the contents of an image
private static BufferedImage toBufferedImage(Image image) {
if (image instanceof BufferedImage) {
return (BufferedImage)image;
}
// This code ensures that all the pixels in the image are loaded
image = new ImageIcon(image).getImage();
// Determine if the image has transparent pixels; for this method's
// implementation, see Determining If an Image Has Transparent Pixels
boolean hasAlpha = hasAlpha(image);
// Create a buffered image with a format that's compatible with the screen
BufferedImage bimage = null;
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
try {
// Determine the type of transparency of the new buffered image
int transparency = Transparency.OPAQUE;
if (hasAlpha) {
transparency = Transparency.BITMASK;
}
// Create the buffered image
GraphicsDevice gs = ge.getDefaultScreenDevice();
GraphicsConfiguration gc = gs.getDefaultConfiguration();
bimage = gc.createCompatibleImage(
image.getWidth(null), image.getHeight(null), transparency);
} catch (HeadlessException e) {
// The system does not have a screen
}
if (bimage == null) {
// Create a buffered image using the default color model
int type = BufferedImage.TYPE_INT_RGB;
if (hasAlpha) {
type = BufferedImage.TYPE_INT_ARGB;
}
bimage = new BufferedImage(image.getWidth(null), image.getHeight(null), type);
}
// Copy image to buffered image
Graphics g = bimage.createGraphics();
// Paint the image onto the buffered image
g.drawImage(image, 0, 0, null);
g.dispose();
return bimage;
}
// This method returns true if the specified image has transparent pixels
private static boolean hasAlpha(Image image) {
// If buffered image, the color model is readily available
if (image instanceof BufferedImage) {
BufferedImage bimage = (BufferedImage)image;
return bimage.getColorModel().hasAlpha();
}
// Use a pixel grabber to retrieve the image's color model;
// grabbing a single pixel is usually sufficient
PixelGrabber pg = new PixelGrabber(image, 0, 0, 1, 1, false);
try {
pg.grabPixels();
} catch (InterruptedException e) {
}
// Get the image's color model
ColorModel cm = pg.getColorModel();
return cm.hasAlpha();
}
}
| true | true | private void initialize() {
Font labelFont = new Font(null, 1, 15);
ImageIcon icon = new ImageIcon("images/icon.png");
// Setup the window
window = new JFrame("RoboCode");
window.setSize(new Dimension(1400, 700));
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setIconImage(icon.getImage());
//----[Begin Left-Hand Panel]----
int cmdPanelWidth = 200;
int cmdPanelHeight = window.getHeight();
int groupListHeight = 200;
int cmdListHeight = 400;
// Setup the panel to hold the left side
JPanel cmdPanel = new JPanel();
cmdPanel.setPreferredSize(new Dimension(cmdPanelWidth, cmdPanelHeight));
cmdPanel.setLayout(new BoxLayout(cmdPanel, BoxLayout.PAGE_AXIS));
// Setup the list of groups of commands
JLabel groupListText = new JLabel("Action Categories");
groupListText.setFont(labelFont);
groupListText.setAlignmentX(Component.LEFT_ALIGNMENT);
groupList.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent arg0) {
switchCmdList(groupList.getSelectedIndex());
}
});
groupList.setModel(new AbstractListModel() {
private static final long serialVersionUID = 1L;
String[] values = new String[] {"Basic Movement", "Basic Turning", "Basic Gun Control", "Advanced Turning"};
public int getSize() {
return values.length;
}
public Object getElementAt(int index) {
return values[index];
}
});
groupList.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
groupList.setPreferredSize(new Dimension(groupListHeight, cmdPanelWidth));
groupList.setSelectedIndex(0);
groupList.setAlignmentX(Component.LEFT_ALIGNMENT);
groupList.setFixedCellWidth(cmdPanelWidth);
// Setup the list of commands
JLabel cmdListText = new JLabel("Available Actions");
//cmdListText.setBounds(10, 145, 200, 20);
cmdListText.setFont(labelFont);
cmdListText.setAlignmentX(Component.LEFT_ALIGNMENT);
cmdList.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent me) {
switchCmd(groupList.getSelectedIndex(), cmdList.getSelectedIndex());
}
});
cmdList.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
cmdList.setAlignmentX(Component.LEFT_ALIGNMENT);
cmdList.setPreferredSize(new Dimension(cmdListHeight, cmdPanelWidth));
cmdList.setFixedCellWidth(200);
cmdPanel.add(Box.createRigidArea(new Dimension(0,10)));
cmdPanel.add(groupListText);
cmdPanel.add(Box.createRigidArea(new Dimension(0,5)));
cmdPanel.add(groupList);
cmdPanel.add(Box.createRigidArea(new Dimension(0,10)));
cmdPanel.add(cmdListText);
cmdPanel.add(Box.createRigidArea(new Dimension(0,5)));
cmdPanel.add(cmdList);
cmdPanel.add(Box.createVerticalGlue());
//----[End Left-Hand Panel]----
//----[Begin Middle Panel]----
int controlPanelWidth = 100;
int controlPanelHeight = window.getHeight();
JPanel addPanel = new JPanel();
addPanel.setPreferredSize(new Dimension(controlPanelWidth, controlPanelHeight));
addPanel.setLayout(new BoxLayout(addPanel, BoxLayout.PAGE_AXIS));
JLabel paramText = new JLabel("Parameters");
paramText.setFont(labelFont);
paramText.setAlignmentX(Component.CENTER_ALIGNMENT);
//=========================================================START PETER'S CODE
JPanel turning, moving, fire, wait, both, blank=new JPanel();
turning=new JPanel();
JLabel tLb=new JLabel("Degrees: ");
tAr=new JTextArea("0",1,4);
turning.add(tLb);
turning.add(tAr);
tAr.getDocument().addDocumentListener(new DocumentListener(){
@Override
public void changedUpdate(DocumentEvent source) {
Document sourceDocument = source.getDocument();
if(sourceDocument.getLength() == 0){
angle = 0;
}else{
try {
angle = Math.toRadians(Integer.parseInt(sourceDocument.getText(0, sourceDocument.getLength())));
} catch (NumberFormatException e) {
// Do nothing
} catch (BadLocationException e) {
// Do nothing
}
window.repaint();
}
}
@Override
public void insertUpdate(DocumentEvent source) {
changedUpdate(source);
}
@Override
public void removeUpdate(DocumentEvent source) {
changedUpdate(source);
}
});
moving=new JPanel();
JLabel mLb=new JLabel("Pixels: ");
mAr=new JTextArea("0",1,4);
moving.add(mLb);
moving.add(mAr);
both=new JPanel();
both.add(new JLabel("Pixels: "));
bAa=new JTextArea("0",1,4);
both.add(bAa);
both.add(new JLabel("Degrees: "));
bAb=new JTextArea("0",1,4);
both.add(bAb);
fire=new JPanel();
fire.add(new JLabel("Fire"));
wait=new JPanel();
wait.add(new JLabel("Wait"));
cl=new CardLayout();
argPanel=new JPanel(cl);
argPanel.add(blank,"Blank");
argPanel.add(turning,"Turning");
argPanel.add(moving,"Moving");
argPanel.add(both,"Both");
argPanel.add(fire,"Fire");
argPanel.add(wait,"Wait");
argPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
argPanel.setMaximumSize(new Dimension(controlPanelWidth, 300));
switchCmdList(0);
//////////////////////
//===========================================================END PETER'S CODE
JLabel addBtnText = new JLabel("Add Action");
addBtnText.setFont(labelFont);
addBtnText.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton addBtn = new JButton(">>");
addBtn.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent evt) {
addCmd();
}
});
addBtn.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel rmvBtnText = new JLabel("Remove Action");
rmvBtnText.setFont(labelFont);
rmvBtnText.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton rmvBtn = new JButton("<<");
rmvBtn.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent evt){
removeCmd();
}
});
rmvBtn.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel generateBtnText = new JLabel("Generate Code");
generateBtnText.setFont(labelFont);
generateBtnText.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton generateBtn = new JButton("Start!");
generateBtn.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent me) {
Writer.writeToJavaFile(d.run.data,d.scan.data,d.bullet.data,d.wall.data);
addCodeToWindow();
JOptionPane.showMessageDialog(null, "Code Generated to D drive","Generation Success", 1);
}
});
generateBtn.setAlignmentX(Component.CENTER_ALIGNMENT);
addPanel.add(Box.createRigidArea(new Dimension(0,10)));
addPanel.add(programInfo());
addPanel.add(Box.createRigidArea(new Dimension(0,10)));
addPanel.add(robotDisplay());
addPanel.add(Box.createRigidArea(new Dimension(0,10)));
addPanel.add(paramText);
addPanel.add(Box.createRigidArea(new Dimension(0,5)));
addPanel.add(argPanel);
addPanel.add(Box.createRigidArea(new Dimension(0,10)));
addPanel.add(addBtnText);
addPanel.add(Box.createRigidArea(new Dimension(0,5)));
addPanel.add(addBtn);
addPanel.add(Box.createRigidArea(new Dimension(0,10)));
addPanel.add(rmvBtnText);
addPanel.add(Box.createRigidArea(new Dimension(0,5)));
addPanel.add(rmvBtn);
addPanel.add(Box.createRigidArea(new Dimension(0,10)));
addPanel.add(generateBtnText);
addPanel.add(Box.createRigidArea(new Dimension(0,5)));
addPanel.add(generateBtn);
addPanel.add(Box.createVerticalGlue());
//addPanel.setBorder(BorderFactory.createLineBorder(Color.black));
//----[End Middle Panel]----
//----[Begin Right-Hand Panel]----
//addPanel.setBounds(220, 10, 200, 420);
//addPanel.setLayout(new BoxLayout(addPanel, BoxLayout.PAGE_AXIS));
JPanel rightPanel = new JPanel();
rightPanel.setPreferredSize(new Dimension(200, 600));
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.PAGE_AXIS));
JLabel modeBtnText = new JLabel("Operating Modes");
modeBtnText.setFont(labelFont);
modeBtnText.setAlignmentX(Component.LEFT_ALIGNMENT);
JPanel radioButtons = new JPanel();
radioButtons.setLayout(new GridLayout(2, 2));
radioButtons.setMaximumSize(new Dimension(250, 50));
JRadioButton radioRun = new JRadioButton("Standard Behavior");
radioRun.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent arg0) {
switchRightList(RUN_MENU);
}
});
radioRun.setSelected(true);
JRadioButton radioScan = new JRadioButton("Scan Robot");
radioScan.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
switchRightList(SCAN_MENU);
}
});
JRadioButton radioBullet = new JRadioButton("Hit By Bullet");
radioBullet.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
switchRightList(BULLET_MENU);
}
});
JRadioButton radioWall = new JRadioButton("Hit Wall");
radioWall.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
switchRightList(WALL_MENU);
}
});
// Group the radio buttons
ButtonGroup methodChoice = new ButtonGroup();
methodChoice.add(radioRun);
methodChoice.add(radioScan);
methodChoice.add(radioBullet);
methodChoice.add(radioWall);
radioButtons.add(radioRun);
radioButtons.add(radioScan);
radioButtons.add(radioBullet);
radioButtons.add(radioWall);
radioButtons.setAlignmentX(Component.LEFT_ALIGNMENT);
JLabel currActionsText = new JLabel("Current Actions");
currActionsText.setFont(labelFont);
String columnNames[] = {"Action", "Parameters"};
rightTable = new JTable(null, columnNames);
rightTable.setModel(d.run);
rightTable.getColumnModel().getColumn(0).setResizable(false);
rightTable.getColumnModel().getColumn(1).setResizable(false);
rightTable.setPreferredScrollableViewportSize(new Dimension(200, 300));
JScrollPane rightScrollPane = new JScrollPane(rightTable);
rightScrollPane.setAlignmentX(Component.LEFT_ALIGNMENT);
//rightScrollPane.setLocation(0, 70);
//rightScrollPane.setSize(278, 607);
rightPanel.add(Box.createRigidArea(new Dimension(0,10)));
rightPanel.add(modeBtnText);
rightPanel.add(Box.createRigidArea(new Dimension(0,5)));
rightPanel.add(radioButtons);
rightPanel.add(Box.createRigidArea(new Dimension(0,10)));
rightPanel.add(currActionsText);
rightPanel.add(Box.createRigidArea(new Dimension(0,5)));
rightPanel.add(rightScrollPane);
rightPanel.add(Box.createVerticalGlue());
// Create the live text editor
int codePanelWidth = 600;
int codeAreaHeight = 400;
codePanel = new JPanel();
codePanel.setPreferredSize(new Dimension(codePanelWidth,window.getHeight()));
codePanel.setLayout(new BoxLayout(codePanel, BoxLayout.PAGE_AXIS));
JLabel codePanelText = new JLabel("Generated Code");
codePanelText.setFont(labelFont);
codePanelText.setAlignmentX(Component.LEFT_ALIGNMENT);
codeTextArea = new JTextArea();
codeTextArea.setEditable(false);
codeTextArea.setPreferredSize(new Dimension(codePanelWidth-10, codeAreaHeight-10));
codeTextArea.setText("No Actions");
codeTextArea.setAlignmentX(Component.LEFT_ALIGNMENT);
JScrollPane codeScrollPane = new JScrollPane(codeTextArea);
codeScrollPane.setPreferredSize(new Dimension(codePanelWidth, codeAreaHeight));
codeScrollPane.setAlignmentX(Component.LEFT_ALIGNMENT);
codePanel.add(Box.createRigidArea(new Dimension(0,10)));
codePanel.add(codePanelText);
codePanel.add(Box.createRigidArea(new Dimension(0,5)));
codePanel.add(codeScrollPane);
codePanel.add(Box.createVerticalGlue());
// Add the panes to the windows
Container windowContent = window.getContentPane();
windowContent.setLayout(new BoxLayout(windowContent, BoxLayout.LINE_AXIS));
windowContent.add(Box.createHorizontalGlue());
windowContent.add(cmdPanel);
windowContent.add(Box.createRigidArea(new Dimension(10, 0)));
windowContent.add(addPanel);
windowContent.add(Box.createRigidArea(new Dimension(10, 0)));
windowContent.add(rightPanel);
windowContent.add(Box.createRigidArea(new Dimension(10, 0)));
windowContent.add(codePanel);
windowContent.add(Box.createHorizontalGlue());
window.setJMenuBar(createMenuBar());
}
| private void initialize() {
Font labelFont = new Font(null, 1, 15);
ImageIcon icon = new ImageIcon("images/icon.png");
// Setup the window
window = new JFrame("RoboCode");
window.setSize(new Dimension(1400, 700));
window.setLocationRelativeTo(null);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.setIconImage(icon.getImage());
//----[Begin Left-Hand Panel]----
int cmdPanelWidth = 200;
int cmdPanelHeight = window.getHeight();
int groupListHeight = 200;
int cmdListHeight = 400;
// Setup the panel to hold the left side
JPanel cmdPanel = new JPanel();
cmdPanel.setPreferredSize(new Dimension(cmdPanelWidth, cmdPanelHeight));
cmdPanel.setLayout(new BoxLayout(cmdPanel, BoxLayout.PAGE_AXIS));
// Setup the list of groups of commands
JLabel groupListText = new JLabel("Action Categories");
groupListText.setFont(labelFont);
groupListText.setAlignmentX(Component.LEFT_ALIGNMENT);
groupList.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent arg0) {
switchCmdList(groupList.getSelectedIndex());
}
});
groupList.setModel(new AbstractListModel() {
private static final long serialVersionUID = 1L;
String[] values = new String[] {"Basic Movement", "Basic Turning", "Basic Gun Control", "Advanced Turning"};
public int getSize() {
return values.length;
}
public Object getElementAt(int index) {
return values[index];
}
});
groupList.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
groupList.setPreferredSize(new Dimension(groupListHeight, cmdPanelWidth));
groupList.setSelectedIndex(0);
groupList.setAlignmentX(Component.LEFT_ALIGNMENT);
groupList.setFixedCellWidth(cmdPanelWidth);
// Setup the list of commands
JLabel cmdListText = new JLabel("Available Actions");
//cmdListText.setBounds(10, 145, 200, 20);
cmdListText.setFont(labelFont);
cmdListText.setAlignmentX(Component.LEFT_ALIGNMENT);
cmdList.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent me) {
switchCmd(groupList.getSelectedIndex(), cmdList.getSelectedIndex());
}
});
cmdList.setBorder(new BevelBorder(BevelBorder.LOWERED, null, null, null, null));
cmdList.setAlignmentX(Component.LEFT_ALIGNMENT);
cmdList.setPreferredSize(new Dimension(cmdListHeight, cmdPanelWidth));
cmdList.setFixedCellWidth(200);
cmdPanel.add(Box.createRigidArea(new Dimension(0,10)));
cmdPanel.add(groupListText);
cmdPanel.add(Box.createRigidArea(new Dimension(0,5)));
cmdPanel.add(groupList);
cmdPanel.add(Box.createRigidArea(new Dimension(0,10)));
cmdPanel.add(cmdListText);
cmdPanel.add(Box.createRigidArea(new Dimension(0,5)));
cmdPanel.add(cmdList);
cmdPanel.add(Box.createVerticalGlue());
//----[End Left-Hand Panel]----
//----[Begin Middle Panel]----
int controlPanelWidth = 100;
int controlPanelHeight = window.getHeight();
JPanel addPanel = new JPanel();
addPanel.setPreferredSize(new Dimension(controlPanelWidth, controlPanelHeight));
addPanel.setLayout(new BoxLayout(addPanel, BoxLayout.PAGE_AXIS));
JLabel paramText = new JLabel("Parameters");
paramText.setFont(labelFont);
paramText.setAlignmentX(Component.CENTER_ALIGNMENT);
//=========================================================START PETER'S CODE
JPanel turning, moving, fire, wait, both, blank=new JPanel();
turning=new JPanel();
JLabel tLb=new JLabel("Degrees: ");
tAr=new JTextArea("0",1,4);
turning.add(tLb);
turning.add(tAr);
tAr.getDocument().addDocumentListener(new DocumentListener(){
@Override
public void changedUpdate(DocumentEvent source) {
Document sourceDocument = source.getDocument();
if(sourceDocument.getLength() == 0){
angle = 0;
}else{
try {
angle = Math.toRadians(Integer.parseInt(sourceDocument.getText(0, sourceDocument.getLength())));
} catch (NumberFormatException e) {
// Do nothing
} catch (BadLocationException e) {
// Do nothing
}
window.repaint();
}
}
@Override
public void insertUpdate(DocumentEvent source) {
changedUpdate(source);
}
@Override
public void removeUpdate(DocumentEvent source) {
changedUpdate(source);
}
});
moving=new JPanel();
JLabel mLb=new JLabel("Pixels: ");
mAr=new JTextArea("0",1,4);
moving.add(mLb);
moving.add(mAr);
both=new JPanel();
both.add(new JLabel("Pixels: "));
bAa=new JTextArea("0",1,4);
both.add(bAa);
both.add(new JLabel("Degrees: "));
bAb=new JTextArea("0",1,4);
both.add(bAb);
fire=new JPanel();
fire.add(new JLabel("Fire"));
wait=new JPanel();
wait.add(new JLabel("Wait"));
cl=new CardLayout();
argPanel=new JPanel(cl);
argPanel.add(blank,"Blank");
argPanel.add(turning,"Turning");
argPanel.add(moving,"Moving");
argPanel.add(both,"Both");
argPanel.add(fire,"Fire");
argPanel.add(wait,"Wait");
argPanel.setAlignmentX(Component.CENTER_ALIGNMENT);
argPanel.setMaximumSize(new Dimension(controlPanelWidth, 300));
switchCmdList(0);
//////////////////////
//===========================================================END PETER'S CODE
JLabel addBtnText = new JLabel("Add Action");
addBtnText.setFont(labelFont);
addBtnText.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton addBtn = new JButton(">>");
addBtn.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent evt) {
addCmd();
}
});
addBtn.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel rmvBtnText = new JLabel("Remove Action");
rmvBtnText.setFont(labelFont);
rmvBtnText.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton rmvBtn = new JButton("<<");
rmvBtn.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent evt){
removeCmd();
}
});
rmvBtn.setAlignmentX(Component.CENTER_ALIGNMENT);
JLabel generateBtnText = new JLabel("Generate Code");
generateBtnText.setFont(labelFont);
generateBtnText.setAlignmentX(Component.CENTER_ALIGNMENT);
JButton generateBtn = new JButton("Start!");
generateBtn.addMouseListener(new MouseAdapter() {
public void mouseReleased(MouseEvent me) {
Writer.writeToJavaFile(d.run.data,d.scan.data,d.bullet.data,d.wall.data);
addCodeToWindow();
JOptionPane.showMessageDialog(null, "Code Generated to D drive","Generation Success", 1);
}
});
generateBtn.setAlignmentX(Component.CENTER_ALIGNMENT);
addPanel.add(Box.createRigidArea(new Dimension(0,10)));
addPanel.add(programInfo());
addPanel.add(Box.createRigidArea(new Dimension(0,10)));
addPanel.add(robotDisplay());
addPanel.add(Box.createRigidArea(new Dimension(0,10)));
addPanel.add(paramText);
addPanel.add(Box.createRigidArea(new Dimension(0,5)));
addPanel.add(argPanel);
addPanel.add(Box.createRigidArea(new Dimension(0,10)));
addPanel.add(addBtnText);
addPanel.add(Box.createRigidArea(new Dimension(0,5)));
addPanel.add(addBtn);
addPanel.add(Box.createRigidArea(new Dimension(0,10)));
addPanel.add(rmvBtnText);
addPanel.add(Box.createRigidArea(new Dimension(0,5)));
addPanel.add(rmvBtn);
addPanel.add(Box.createRigidArea(new Dimension(0,10)));
addPanel.add(generateBtnText);
addPanel.add(Box.createRigidArea(new Dimension(0,5)));
addPanel.add(generateBtn);
addPanel.add(Box.createVerticalGlue());
//addPanel.setBorder(BorderFactory.createLineBorder(Color.black));
//----[End Middle Panel]----
//----[Begin Right-Hand Panel]----
//addPanel.setBounds(220, 10, 200, 420);
//addPanel.setLayout(new BoxLayout(addPanel, BoxLayout.PAGE_AXIS));
JPanel rightPanel = new JPanel();
rightPanel.setPreferredSize(new Dimension(200, 600));
rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.PAGE_AXIS));
JLabel modeBtnText = new JLabel("Operating Modes");
modeBtnText.setFont(labelFont);
modeBtnText.setAlignmentX(Component.LEFT_ALIGNMENT);
JPanel radioButtons = new JPanel();
radioButtons.setLayout(new GridLayout(2, 2));
radioButtons.setMaximumSize(new Dimension(250, 50));
JRadioButton radioRun = new JRadioButton("Standard Behavior");
radioRun.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent arg0) {
switchRightList(RUN_MENU);
}
});
radioRun.setSelected(true);
JRadioButton radioScan = new JRadioButton("Scan Robot");
radioScan.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
switchRightList(SCAN_MENU);
}
});
JRadioButton radioBullet = new JRadioButton("Hit By Bullet");
radioBullet.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
switchRightList(BULLET_MENU);
}
});
JRadioButton radioWall = new JRadioButton("Hit Wall");
radioWall.addMouseListener(new MouseAdapter() {
@Override
public void mouseReleased(MouseEvent e) {
switchRightList(WALL_MENU);
}
});
// Group the radio buttons
ButtonGroup methodChoice = new ButtonGroup();
methodChoice.add(radioRun);
methodChoice.add(radioScan);
methodChoice.add(radioBullet);
methodChoice.add(radioWall);
radioButtons.add(radioRun);
radioButtons.add(radioScan);
radioButtons.add(radioBullet);
radioButtons.add(radioWall);
radioButtons.setAlignmentX(Component.LEFT_ALIGNMENT);
JLabel currActionsText = new JLabel("Current Actions");
currActionsText.setFont(labelFont);
String columnNames[] = {"Action", "Parameters"};
rightTable = new JTable(null, columnNames);
rightTable.setModel(d.run);
rightTable.getColumnModel().getColumn(0).setResizable(false);
rightTable.getColumnModel().getColumn(1).setResizable(false);
rightTable.setPreferredScrollableViewportSize(new Dimension(200, 300));
JScrollPane rightScrollPane = new JScrollPane(rightTable);
rightScrollPane.setAlignmentX(Component.LEFT_ALIGNMENT);
//rightScrollPane.setLocation(0, 70);
//rightScrollPane.setSize(278, 607);
rightPanel.add(Box.createRigidArea(new Dimension(0,10)));
rightPanel.add(modeBtnText);
rightPanel.add(Box.createRigidArea(new Dimension(0,5)));
rightPanel.add(radioButtons);
rightPanel.add(Box.createRigidArea(new Dimension(0,10)));
rightPanel.add(currActionsText);
rightPanel.add(Box.createRigidArea(new Dimension(0,5)));
rightPanel.add(rightScrollPane);
rightPanel.add(Box.createVerticalGlue());
// Create the live text editor
int codePanelWidth = 600;
int codeAreaHeight = 400;
codePanel = new JPanel();
codePanel.setPreferredSize(new Dimension(codePanelWidth,window.getHeight()));
codePanel.setLayout(new BoxLayout(codePanel, BoxLayout.PAGE_AXIS));
JLabel codePanelText = new JLabel("Generated Code");
codePanelText.setFont(labelFont);
codePanelText.setAlignmentX(Component.LEFT_ALIGNMENT);
codeTextArea = new JTextArea();
codeTextArea.setEditable(false);
//codeTextArea.setPreferredSize(new Dimension(codePanelWidth-10, codeAreaHeight-10));
codeTextArea.setText("No Actions");
codeTextArea.setAlignmentX(Component.LEFT_ALIGNMENT);
JScrollPane codeScrollPane = new JScrollPane(codeTextArea);
codeScrollPane.setPreferredSize(new Dimension(codePanelWidth, codeAreaHeight));
codeScrollPane.setAlignmentX(Component.LEFT_ALIGNMENT);
codePanel.add(Box.createRigidArea(new Dimension(0,10)));
codePanel.add(codePanelText);
codePanel.add(Box.createRigidArea(new Dimension(0,5)));
codePanel.add(codeScrollPane);
codePanel.add(Box.createVerticalGlue());
// Add the panes to the windows
Container windowContent = window.getContentPane();
windowContent.setLayout(new BoxLayout(windowContent, BoxLayout.LINE_AXIS));
windowContent.add(Box.createHorizontalGlue());
windowContent.add(cmdPanel);
windowContent.add(Box.createRigidArea(new Dimension(10, 0)));
windowContent.add(addPanel);
windowContent.add(Box.createRigidArea(new Dimension(10, 0)));
windowContent.add(rightPanel);
windowContent.add(Box.createRigidArea(new Dimension(10, 0)));
windowContent.add(codePanel);
windowContent.add(Box.createHorizontalGlue());
window.setJMenuBar(createMenuBar());
}
|
diff --git a/src/main/java/com/onarandombox/MultiverseCore/commands/InfoCommand.java b/src/main/java/com/onarandombox/MultiverseCore/commands/InfoCommand.java
index bbcf947..83bfa3a 100644
--- a/src/main/java/com/onarandombox/MultiverseCore/commands/InfoCommand.java
+++ b/src/main/java/com/onarandombox/MultiverseCore/commands/InfoCommand.java
@@ -1,271 +1,272 @@
/******************************************************************************
* Multiverse 2 Copyright (c) the Multiverse Team 2011. *
* Multiverse 2 is licensed under the BSD License. *
* For more information please check the README.md file included *
* with this project. *
******************************************************************************/
package com.onarandombox.MultiverseCore.commands;
import com.onarandombox.MultiverseCore.MultiverseCore;
import com.onarandombox.MultiverseCore.api.FancyText;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.utils.FancyColorScheme;
import com.onarandombox.MultiverseCore.utils.FancyHeader;
import com.onarandombox.MultiverseCore.utils.FancyMessage;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.permissions.PermissionDefault;
import java.util.ArrayList;
import java.util.List;
// Will use when we can compile with JDK 6
//import com.sun.xml.internal.ws.util.StringUtils;
/**
* Returns detailed information about a world.
*/
public class InfoCommand extends MultiverseCommand {
private MVWorldManager worldManager;
public InfoCommand(MultiverseCore plugin) {
super(plugin);
this.setName("World Information");
this.setCommandUsage("/mv info" + ChatColor.GOLD + " [WORLD] [PAGE]");
this.setArgRange(0, 2);
this.addKey("mvinfo");
this.addKey("mvi");
this.addKey("mv info");
this.addCommandExample("/mv info " + ChatColor.GOLD + "1");
this.addCommandExample("/mv info " + ChatColor.GOLD + "3");
this.setPermission("multiverse.core.info", "Returns detailed information on the world.", PermissionDefault.OP);
this.worldManager = this.plugin.getMVWorldManager();
}
@Override
public void runCommand(CommandSender sender, List<String> args) {
// Check if the command was sent from a Player.
String worldName = "";
int pageNum = 0;
if (args.size() == 0) {
if (sender instanceof Player) {
Player p = (Player) sender;
worldName = p.getWorld().getName();
} else {
sender.sendMessage("You must enter a" + ChatColor.LIGHT_PURPLE + " world" + ChatColor.WHITE + " from the console!");
return;
}
} else if (args.size() == 1) {
if (this.worldManager.isMVWorld(args.get(0))) {
// then we have a world!
worldName = args.get(0);
} else if (this.worldManager.getUnloadedWorlds().contains(args.get(0))) {
sender.sendMessage("That world exists, but it is unloaded!");
sender.sendMessage(String.format("You can load it with: %s/mv load %s", ChatColor.AQUA, args.get(0)));
return;
} else {
if (sender instanceof Player) {
Player p = (Player) sender;
worldName = p.getWorld().getName();
try {
pageNum = Integer.parseInt(args.get(0)) - 1;
} catch (NumberFormatException e) {
sender.sendMessage("That world does not exist.");
return;
}
} else {
sender.sendMessage("You must enter a" + ChatColor.LIGHT_PURPLE + " world" + ChatColor.WHITE + " from the console!");
return;
}
}
} else if (args.size() == 2) {
worldName = args.get(0);
try {
pageNum = Integer.parseInt(args.get(1)) - 1;
} catch (NumberFormatException e) {
pageNum = 0;
}
}
if (this.worldManager.isMVWorld(worldName)) {
Player p = null;
if (sender instanceof Player) {
p = (Player) sender;
}
showPage(pageNum, sender, this.buildEntireCommand(this.worldManager.getMVWorld(worldName), p));
} else if (this.worldManager.getUnloadedWorlds().contains(worldName)) {
sender.sendMessage("That world exists, but it is unloaded!");
sender.sendMessage(String.format("You can load it with: %s/mv load %s", ChatColor.AQUA, worldName));
} else if (this.plugin.getServer().getWorld(worldName) != null) {
sender.sendMessage("That world exists, but Multiverse does not know about it!");
sender.sendMessage("You can import it with" + ChatColor.AQUA + "/mv import " + ChatColor.GREEN + worldName + ChatColor.LIGHT_PURPLE + "{ENV}");
sender.sendMessage("For available environments type " + ChatColor.GREEN + "/mv env");
}
}
private List<List<FancyText>> buildEntireCommand(MultiverseWorld world, Player p) {
List<FancyText> message = new ArrayList<FancyText>();
List<List<FancyText>> worldInfo = new ArrayList<List<FancyText>>();
// Page 1
FancyColorScheme colors = new FancyColorScheme(ChatColor.AQUA, ChatColor.AQUA, ChatColor.GOLD, ChatColor.WHITE);
message.add(new FancyHeader("General Info", colors));
message.add(new FancyMessage("World Name: ", world.getName(), colors));
message.add(new FancyMessage("World Alias: ", world.getColoredWorldString(), colors));
message.add(new FancyMessage("Game Mode: ", world.getGameMode().toString(), colors));
message.add(new FancyMessage("Difficulty: ", world.getDifficulty().toString(), colors));
//message.add(new FancyMessage("Game Mode: ", StringUtils.capitalize(world.getGameMode().toString()), colors));
Location spawn = world.getSpawnLocation();
message.add(new FancyMessage("Spawn Location: ", plugin.getLocationManipulation().strCoords(spawn), colors));
- message.add(new FancyMessage("World Scale: ", world.getScaling() + "", colors));
+ message.add(new FancyMessage("World Scale: ", String.valueOf(world.getScaling()), colors));
+ message.add(new FancyMessage("World Seed: ", String.valueOf(world.getSeed()), colors));
if (world.getPrice() > 0) {
final String formattedAmount;
if (world.getCurrency() <= 0 && plugin.getVaultHandler().getEconomy() != null) {
formattedAmount = plugin.getVaultHandler().getEconomy().format(world.getPrice());
} else {
formattedAmount = this.plugin.getBank().getFormattedAmount(p, world.getPrice(), world.getCurrency());
}
message.add(new FancyMessage("Price to enter this world: ", formattedAmount, colors));
} else {
message.add(new FancyMessage("Price to enter this world: ", ChatColor.GREEN + "FREE!", colors));
}
if (world.getRespawnToWorld() != null) {
MultiverseWorld respawn = this.worldManager.getMVWorld(world.getRespawnToWorld());
if (respawn != null) {
message.add(new FancyMessage("Players will respawn in: ", respawn.getColoredWorldString(), colors));
} else {
message.add(new FancyMessage("Players will respawn in: ", ChatColor.RED + "!!INVALID!!", colors));
}
}
worldInfo.add(message);
// Page 2
message = new ArrayList<FancyText>();
message.add(new FancyHeader("More World Settings", colors));
message.add(new FancyMessage("World Type: ", world.getWorldType().toString(), colors));
message.add(new FancyMessage("Structures: ", world.getCBWorld().canGenerateStructures() + "", colors));
message.add(new FancyMessage("Weather: ", world.isWeatherEnabled() + "", colors));
message.add(new FancyMessage("Players will get hungry: ", world.getHunger() + "", colors));
message.add(new FancyMessage("Keep spawn in memory: ", world.isKeepingSpawnInMemory() + "", colors));
message.add(new FancyHeader("PVP Settings", colors));
message.add(new FancyMessage("Multiverse Setting: ", world.isPVPEnabled() + "", colors));
message.add(new FancyMessage("Bukkit Setting: ", world.getCBWorld().getPVP() + "", colors));
worldInfo.add(message);
// Page 3
message = new ArrayList<FancyText>();
message.add(new FancyHeader("Monster Settings", colors));
message.add(new FancyMessage("Multiverse Setting: ", world.canMonstersSpawn() + "", colors));
message.add(new FancyMessage("Bukkit Setting: ", world.getCBWorld().getAllowMonsters() + "", colors));
if (world.getMonsterList().size() > 0) {
if (world.canMonstersSpawn()) {
message.add(new FancyMessage("Monsters that" + ChatColor.RED + " CAN NOT "
+ ChatColor.GREEN + "spawn: ", toCommaSeperated(world.getMonsterList()), colors));
} else {
message.add(new FancyMessage("Monsters that" + ChatColor.GREEN + " CAN SPAWN: ", toCommaSeperated(world.getMonsterList()), colors));
}
} else {
message.add(new FancyMessage("Monsters that CAN spawn: ", world.canMonstersSpawn() ? "ALL" : "NONE", colors));
}
worldInfo.add(message);
// Page 4
message = new ArrayList<FancyText>();
message.add(new FancyHeader("Animal Settings", colors));
message.add(new FancyMessage("Multiverse Setting: ", world.canAnimalsSpawn() + "", colors));
message.add(new FancyMessage("Bukkit Setting: ", world.getCBWorld().getAllowAnimals() + "", colors));
if (world.getMonsterList().size() > 0) {
if (world.canMonstersSpawn()) {
message.add(new FancyMessage("Animals that" + ChatColor.RED + " CAN NOT "
+ ChatColor.GREEN + "spawn: ", toCommaSeperated(world.getAnimalList()), colors));
} else {
message.add(new FancyMessage("Animals that" + ChatColor.GREEN + " CAN SPAWN: ", toCommaSeperated(world.getAnimalList()), colors));
}
} else {
message.add(new FancyMessage("Animals that CAN spawn: ", world.canAnimalsSpawn() ? "ALL" : "NONE", colors));
}
worldInfo.add(message);
return worldInfo;
}
private static String toCommaSeperated(List<String> list) {
if (list == null || list.size() == 0) {
return "";
}
if (list.size() == 1) {
return list.get(0);
}
String result = list.get(0);
for (int i = 1; i < list.size() - 1; i++) {
result += ", " + list.get(i);
}
result += " and " + list.get(list.size() - 1);
return result;
}
/**
* Gets a "positive" or "negative" {@link ChatColor}.
*
* @param positive Whether this {@link ChatColor} should be "positive".
* @return The {@link ChatColor}.
*/
protected ChatColor getChatColor(boolean positive) {
return positive ? ChatColor.GREEN : ChatColor.RED;
}
private static void showPage(int page, CommandSender sender, List<List<FancyText>> doc) {
page = page < 0 ? 0 : page;
page = page > doc.size() - 1 ? doc.size() - 1 : page;
boolean altColor = false;
boolean appendedPageNum = false;
if (sender instanceof Player) {
List<FancyText> list = doc.get(page);
for (FancyText fancyT : list) {
if (fancyT instanceof FancyMessage) {
FancyMessage text = (FancyMessage) fancyT;
text.setAltColor(altColor);
altColor = !altColor;
sender.sendMessage(text.getFancyText());
} else if (fancyT instanceof FancyHeader) {
FancyHeader text = (FancyHeader) fancyT;
if (!appendedPageNum) {
text.appendText(ChatColor.DARK_PURPLE + " [ Page " + (page + 1) + " of " + doc.size() + " ]");
appendedPageNum = true;
}
sender.sendMessage(text.getFancyText());
altColor = false;
}
}
} else {
for (List<FancyText> list : doc) {
for (FancyText fancyT : list) {
if (fancyT instanceof FancyMessage) {
FancyMessage text = (FancyMessage) fancyT;
text.setAltColor(altColor);
altColor = !altColor;
sender.sendMessage(text.getFancyText());
} else {
FancyText text = fancyT;
if (appendedPageNum) {
sender.sendMessage(" ");
} else {
appendedPageNum = true;
}
sender.sendMessage(text.getFancyText());
altColor = false;
}
}
}
}
}
}
| true | true | private List<List<FancyText>> buildEntireCommand(MultiverseWorld world, Player p) {
List<FancyText> message = new ArrayList<FancyText>();
List<List<FancyText>> worldInfo = new ArrayList<List<FancyText>>();
// Page 1
FancyColorScheme colors = new FancyColorScheme(ChatColor.AQUA, ChatColor.AQUA, ChatColor.GOLD, ChatColor.WHITE);
message.add(new FancyHeader("General Info", colors));
message.add(new FancyMessage("World Name: ", world.getName(), colors));
message.add(new FancyMessage("World Alias: ", world.getColoredWorldString(), colors));
message.add(new FancyMessage("Game Mode: ", world.getGameMode().toString(), colors));
message.add(new FancyMessage("Difficulty: ", world.getDifficulty().toString(), colors));
//message.add(new FancyMessage("Game Mode: ", StringUtils.capitalize(world.getGameMode().toString()), colors));
Location spawn = world.getSpawnLocation();
message.add(new FancyMessage("Spawn Location: ", plugin.getLocationManipulation().strCoords(spawn), colors));
message.add(new FancyMessage("World Scale: ", world.getScaling() + "", colors));
if (world.getPrice() > 0) {
final String formattedAmount;
if (world.getCurrency() <= 0 && plugin.getVaultHandler().getEconomy() != null) {
formattedAmount = plugin.getVaultHandler().getEconomy().format(world.getPrice());
} else {
formattedAmount = this.plugin.getBank().getFormattedAmount(p, world.getPrice(), world.getCurrency());
}
message.add(new FancyMessage("Price to enter this world: ", formattedAmount, colors));
} else {
message.add(new FancyMessage("Price to enter this world: ", ChatColor.GREEN + "FREE!", colors));
}
if (world.getRespawnToWorld() != null) {
MultiverseWorld respawn = this.worldManager.getMVWorld(world.getRespawnToWorld());
if (respawn != null) {
message.add(new FancyMessage("Players will respawn in: ", respawn.getColoredWorldString(), colors));
} else {
message.add(new FancyMessage("Players will respawn in: ", ChatColor.RED + "!!INVALID!!", colors));
}
}
worldInfo.add(message);
// Page 2
message = new ArrayList<FancyText>();
message.add(new FancyHeader("More World Settings", colors));
message.add(new FancyMessage("World Type: ", world.getWorldType().toString(), colors));
message.add(new FancyMessage("Structures: ", world.getCBWorld().canGenerateStructures() + "", colors));
message.add(new FancyMessage("Weather: ", world.isWeatherEnabled() + "", colors));
message.add(new FancyMessage("Players will get hungry: ", world.getHunger() + "", colors));
message.add(new FancyMessage("Keep spawn in memory: ", world.isKeepingSpawnInMemory() + "", colors));
message.add(new FancyHeader("PVP Settings", colors));
message.add(new FancyMessage("Multiverse Setting: ", world.isPVPEnabled() + "", colors));
message.add(new FancyMessage("Bukkit Setting: ", world.getCBWorld().getPVP() + "", colors));
worldInfo.add(message);
// Page 3
message = new ArrayList<FancyText>();
message.add(new FancyHeader("Monster Settings", colors));
message.add(new FancyMessage("Multiverse Setting: ", world.canMonstersSpawn() + "", colors));
message.add(new FancyMessage("Bukkit Setting: ", world.getCBWorld().getAllowMonsters() + "", colors));
if (world.getMonsterList().size() > 0) {
if (world.canMonstersSpawn()) {
message.add(new FancyMessage("Monsters that" + ChatColor.RED + " CAN NOT "
+ ChatColor.GREEN + "spawn: ", toCommaSeperated(world.getMonsterList()), colors));
} else {
message.add(new FancyMessage("Monsters that" + ChatColor.GREEN + " CAN SPAWN: ", toCommaSeperated(world.getMonsterList()), colors));
}
} else {
message.add(new FancyMessage("Monsters that CAN spawn: ", world.canMonstersSpawn() ? "ALL" : "NONE", colors));
}
worldInfo.add(message);
// Page 4
message = new ArrayList<FancyText>();
message.add(new FancyHeader("Animal Settings", colors));
message.add(new FancyMessage("Multiverse Setting: ", world.canAnimalsSpawn() + "", colors));
message.add(new FancyMessage("Bukkit Setting: ", world.getCBWorld().getAllowAnimals() + "", colors));
if (world.getMonsterList().size() > 0) {
if (world.canMonstersSpawn()) {
message.add(new FancyMessage("Animals that" + ChatColor.RED + " CAN NOT "
+ ChatColor.GREEN + "spawn: ", toCommaSeperated(world.getAnimalList()), colors));
} else {
message.add(new FancyMessage("Animals that" + ChatColor.GREEN + " CAN SPAWN: ", toCommaSeperated(world.getAnimalList()), colors));
}
} else {
message.add(new FancyMessage("Animals that CAN spawn: ", world.canAnimalsSpawn() ? "ALL" : "NONE", colors));
}
worldInfo.add(message);
return worldInfo;
}
| private List<List<FancyText>> buildEntireCommand(MultiverseWorld world, Player p) {
List<FancyText> message = new ArrayList<FancyText>();
List<List<FancyText>> worldInfo = new ArrayList<List<FancyText>>();
// Page 1
FancyColorScheme colors = new FancyColorScheme(ChatColor.AQUA, ChatColor.AQUA, ChatColor.GOLD, ChatColor.WHITE);
message.add(new FancyHeader("General Info", colors));
message.add(new FancyMessage("World Name: ", world.getName(), colors));
message.add(new FancyMessage("World Alias: ", world.getColoredWorldString(), colors));
message.add(new FancyMessage("Game Mode: ", world.getGameMode().toString(), colors));
message.add(new FancyMessage("Difficulty: ", world.getDifficulty().toString(), colors));
//message.add(new FancyMessage("Game Mode: ", StringUtils.capitalize(world.getGameMode().toString()), colors));
Location spawn = world.getSpawnLocation();
message.add(new FancyMessage("Spawn Location: ", plugin.getLocationManipulation().strCoords(spawn), colors));
message.add(new FancyMessage("World Scale: ", String.valueOf(world.getScaling()), colors));
message.add(new FancyMessage("World Seed: ", String.valueOf(world.getSeed()), colors));
if (world.getPrice() > 0) {
final String formattedAmount;
if (world.getCurrency() <= 0 && plugin.getVaultHandler().getEconomy() != null) {
formattedAmount = plugin.getVaultHandler().getEconomy().format(world.getPrice());
} else {
formattedAmount = this.plugin.getBank().getFormattedAmount(p, world.getPrice(), world.getCurrency());
}
message.add(new FancyMessage("Price to enter this world: ", formattedAmount, colors));
} else {
message.add(new FancyMessage("Price to enter this world: ", ChatColor.GREEN + "FREE!", colors));
}
if (world.getRespawnToWorld() != null) {
MultiverseWorld respawn = this.worldManager.getMVWorld(world.getRespawnToWorld());
if (respawn != null) {
message.add(new FancyMessage("Players will respawn in: ", respawn.getColoredWorldString(), colors));
} else {
message.add(new FancyMessage("Players will respawn in: ", ChatColor.RED + "!!INVALID!!", colors));
}
}
worldInfo.add(message);
// Page 2
message = new ArrayList<FancyText>();
message.add(new FancyHeader("More World Settings", colors));
message.add(new FancyMessage("World Type: ", world.getWorldType().toString(), colors));
message.add(new FancyMessage("Structures: ", world.getCBWorld().canGenerateStructures() + "", colors));
message.add(new FancyMessage("Weather: ", world.isWeatherEnabled() + "", colors));
message.add(new FancyMessage("Players will get hungry: ", world.getHunger() + "", colors));
message.add(new FancyMessage("Keep spawn in memory: ", world.isKeepingSpawnInMemory() + "", colors));
message.add(new FancyHeader("PVP Settings", colors));
message.add(new FancyMessage("Multiverse Setting: ", world.isPVPEnabled() + "", colors));
message.add(new FancyMessage("Bukkit Setting: ", world.getCBWorld().getPVP() + "", colors));
worldInfo.add(message);
// Page 3
message = new ArrayList<FancyText>();
message.add(new FancyHeader("Monster Settings", colors));
message.add(new FancyMessage("Multiverse Setting: ", world.canMonstersSpawn() + "", colors));
message.add(new FancyMessage("Bukkit Setting: ", world.getCBWorld().getAllowMonsters() + "", colors));
if (world.getMonsterList().size() > 0) {
if (world.canMonstersSpawn()) {
message.add(new FancyMessage("Monsters that" + ChatColor.RED + " CAN NOT "
+ ChatColor.GREEN + "spawn: ", toCommaSeperated(world.getMonsterList()), colors));
} else {
message.add(new FancyMessage("Monsters that" + ChatColor.GREEN + " CAN SPAWN: ", toCommaSeperated(world.getMonsterList()), colors));
}
} else {
message.add(new FancyMessage("Monsters that CAN spawn: ", world.canMonstersSpawn() ? "ALL" : "NONE", colors));
}
worldInfo.add(message);
// Page 4
message = new ArrayList<FancyText>();
message.add(new FancyHeader("Animal Settings", colors));
message.add(new FancyMessage("Multiverse Setting: ", world.canAnimalsSpawn() + "", colors));
message.add(new FancyMessage("Bukkit Setting: ", world.getCBWorld().getAllowAnimals() + "", colors));
if (world.getMonsterList().size() > 0) {
if (world.canMonstersSpawn()) {
message.add(new FancyMessage("Animals that" + ChatColor.RED + " CAN NOT "
+ ChatColor.GREEN + "spawn: ", toCommaSeperated(world.getAnimalList()), colors));
} else {
message.add(new FancyMessage("Animals that" + ChatColor.GREEN + " CAN SPAWN: ", toCommaSeperated(world.getAnimalList()), colors));
}
} else {
message.add(new FancyMessage("Animals that CAN spawn: ", world.canAnimalsSpawn() ? "ALL" : "NONE", colors));
}
worldInfo.add(message);
return worldInfo;
}
|
diff --git a/ccw.core/src/java/ccw/repl/ConnectDialog.java b/ccw.core/src/java/ccw/repl/ConnectDialog.java
index 38ce57e3..1e8673b8 100644
--- a/ccw.core/src/java/ccw/repl/ConnectDialog.java
+++ b/ccw.core/src/java/ccw/repl/ConnectDialog.java
@@ -1,78 +1,79 @@
package ccw.repl;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.events.VerifyListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
public class ConnectDialog extends Dialog {
private Combo hosts;
private Text port;
private String host;
private int portNumber;
public ConnectDialog(Shell parentShell) {
super(parentShell);
setBlockOnOpen(true);
}
@Override
protected void configureShell(Shell newShell) {
super.configureShell(newShell);
newShell.setText("Connect to REPL");
}
@Override
protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
parent = new Composite(composite, 0);
parent.setLayout(new GridLayout(2, false));
new Label(parent, 0).setText("Hostname");
hosts = new Combo(parent, SWT.BORDER);
hosts.setText("127.0.0.1"); // don't know much about swt layouts yet :-(
hosts.setSelection(new Point(0, hosts.getText().length()));
new Label(parent, 0).setText("Port");
port = new Text(parent, SWT.BORDER);
port.addVerifyListener(new VerifyListener() {
public void verifyText(VerifyEvent e) {
- e.doit = (e.text.equals("") || Character.isDigit(e.character));
+ String newText = port.getText().substring(0, e.start) + e.text + port.getText().substring(e.end);
+ e.doit = newText.matches("\\d*");
}
});
port.setFocus();
return composite;
}
protected void okPressed () {
host = hosts.getText();
try {
portNumber = Integer.parseInt(port.getText());
} catch (NumberFormatException e) {
// shouldn't happen given the keylistener above
}
super.okPressed();
}
public String getHost () {
return host;
}
public int getPort () {
return portNumber;
}
}
| true | true | protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
parent = new Composite(composite, 0);
parent.setLayout(new GridLayout(2, false));
new Label(parent, 0).setText("Hostname");
hosts = new Combo(parent, SWT.BORDER);
hosts.setText("127.0.0.1"); // don't know much about swt layouts yet :-(
hosts.setSelection(new Point(0, hosts.getText().length()));
new Label(parent, 0).setText("Port");
port = new Text(parent, SWT.BORDER);
port.addVerifyListener(new VerifyListener() {
public void verifyText(VerifyEvent e) {
e.doit = (e.text.equals("") || Character.isDigit(e.character));
}
});
port.setFocus();
return composite;
}
| protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);
parent = new Composite(composite, 0);
parent.setLayout(new GridLayout(2, false));
new Label(parent, 0).setText("Hostname");
hosts = new Combo(parent, SWT.BORDER);
hosts.setText("127.0.0.1"); // don't know much about swt layouts yet :-(
hosts.setSelection(new Point(0, hosts.getText().length()));
new Label(parent, 0).setText("Port");
port = new Text(parent, SWT.BORDER);
port.addVerifyListener(new VerifyListener() {
public void verifyText(VerifyEvent e) {
String newText = port.getText().substring(0, e.start) + e.text + port.getText().substring(e.end);
e.doit = newText.matches("\\d*");
}
});
port.setFocus();
return composite;
}
|
diff --git a/src/renderer/UIRenderer.java b/src/renderer/UIRenderer.java
index 65eb907..63054a6 100644
--- a/src/renderer/UIRenderer.java
+++ b/src/renderer/UIRenderer.java
@@ -1,369 +1,389 @@
package renderer;
import java.awt.Container;
import java.awt.MediaTracker;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import playable.Player;
import playable.TypeOfPlayer;
import dispatcher.Dispatcher;
import dispatcher.TypeOfTower;
import engine.Base;
import engine.Element;
public class UIRenderer {
private final int UI_LAYER = 200;
private JLabel winnerBackground;
private JLabel loserBackground;
private JLabel radialMenuMovment;
private MultipleSprite radialMenuTower;
private Container container;
private int width;
private int height;
/**
* playerSprites contains all sprites which display the info of players (total nbAgents...)
*/
private final ArrayList<PlayerSprite> playerSprites;
/**
* Represent the state of UIRenderer during unit to send choice.
* 0 = not choosing,
* 1 = choosing,
* 2 = already chosen
*/
private static int choosingUnitFlag = 0;
private static double unitPercentChosen = 0.5;
/**
* Represent the state of UIRenderer during tower choice.
* 0 = not choosing,
* 1 = chose tower super type,
* 2 = chose offensive tower,
* 3 = chose defensive tower,
* 4 = already chosen
*/
private static int choosingTowerFlag = 0;
public UIRenderer(Container c, int width, int height){
super();
this.winnerBackground = new JLabel();
this.loserBackground = new JLabel();
this.radialMenuMovment = new JLabel();
this.radialMenuTower = new MultipleSprite(3);
this.container = c;
this.height=height;
this.width=width;
this.playerSprites = new ArrayList<PlayerSprite>();
}
public void init() throws IOException{
//Load the winner background image
ImageIcon bgWinnerImage = new ImageIcon("./tex/youWin.png");
if(bgWinnerImage.getImageLoadStatus() != MediaTracker.COMPLETE){
throw new IOException();
}
this.winnerBackground.setBounds(0, 0, this.width, this.height);
this.winnerBackground.setIcon(bgWinnerImage);
//Load the looser background image
ImageIcon bgLoserImage = new ImageIcon("./tex/youLose.png");
if(bgLoserImage.getImageLoadStatus() != MediaTracker.COMPLETE){
throw new IOException();
}
this.loserBackground.setBounds(0, 0, this.width, this.height);
this.loserBackground.setIcon(bgLoserImage);
//Load the radial menu image for unit choice
ImageIcon rmImage = new ImageIcon("./tex/radialmenu_movment.png");
if(rmImage.getImageLoadStatus() != MediaTracker.COMPLETE){
throw new IOException();
}
this.radialMenuMovment.setIcon(rmImage);
this.radialMenuMovment.setSize(rmImage.getIconWidth(), rmImage.getIconHeight());
//Load the radial menu image for tower choice
this.radialMenuTower.setSize(80);
this.radialMenuTower.setImage(ImageIO.read(new File("./tex/radialmenu_tower.png")));
this.radialMenuTower.setSize(this.radialMenuTower.getSpriteSize(), this.radialMenuTower.getSpriteSize());
//Manage events
this.radialMenuMovment.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent arg0) {}
@Override
public void mousePressed(MouseEvent arg0) {}
@Override
public void mouseExited(MouseEvent arg0) {}
@Override
public void mouseEntered(MouseEvent arg0) {}
@Override
public void mouseClicked(MouseEvent arg0) {
//fix the bug of controling opponent units when he takes our base during the choice
boolean aSeletedBaseIsNotAPlayerBase = false;
for(Element element:SelectedSprite.startingElements){
if(element.getClass() == Base.class){
if(!((Base) element).isAPlayerBase())
aSeletedBaseIsNotAPlayerBase = true;
}
}
if(aSeletedBaseIsNotAPlayerBase){
SelectedSprite.resetStartingElements();
SelectedSprite.resetEndingElement();
TowerSprite.resetTowerToBuild();
Dispatcher.getRenderer().hideRadialMenus();
return;
}
UIRenderer.choosingUnitFlag = 2;
JLabel radialMenu = (JLabel) arg0.getComponent();
Point rmCenter = new Point(radialMenu.getWidth()/2, radialMenu.getHeight()/2);
Point mousePosition = arg0.getPoint();
if(rmCenter.distance(mousePosition) < 10){ //click on the center 50%
UIRenderer.unitPercentChosen = 0.5;
}else{
if(mousePosition.x > mousePosition.y && radialMenu.getWidth()-mousePosition.x > mousePosition.y){ //click on top quarter 50%
UIRenderer.unitPercentChosen = 0.5;
}else if(mousePosition.x > mousePosition.y && radialMenu.getWidth()-mousePosition.x < mousePosition.y){ //click on right quarter 75%
UIRenderer.unitPercentChosen = 0.75;
}else if(mousePosition.x < mousePosition.y && radialMenu.getWidth()-mousePosition.x > mousePosition.y){ //click on left quarter 25%
UIRenderer.unitPercentChosen = 0.25;
}else if(mousePosition.x < mousePosition.y && radialMenu.getWidth()-mousePosition.x < mousePosition.y){ //click on bottom quarter 99%
UIRenderer.unitPercentChosen = 1.;
}
}
}
});
this.radialMenuTower.addMouseListener(new MouseListener() {
@Override
public void mousePressed(MouseEvent arg0) {}
@Override
public void mouseReleased(MouseEvent arg0) {}
@Override
public void mouseExited(MouseEvent arg0) {}
@Override
public void mouseEntered(MouseEvent arg0) {}
@Override
public void mouseClicked(MouseEvent arg0) {
MultipleSprite radialMenu = (MultipleSprite) arg0.getComponent();
Point rmCenter = new Point(radialMenu.getWidth()/2, radialMenu.getHeight()/2);
Point mousePosition = arg0.getPoint();
//click out of the center circle
if(rmCenter.distance(mousePosition) > 10){
if(UIRenderer.choosingTowerFlag == 1){
//choose offensive or defensive
if(mousePosition.x - rmCenter.x < 0){ //left side offensive
UIRenderer.choosingTowerFlag = 2;
}else{ //right side defensive
UIRenderer.choosingTowerFlag = 3;
}
}else{
- if(UIRenderer.choosingTowerFlag == 2){ //offensive wheel
- TowerSprite.setChosenTowerType(TypeOfTower.SPEED);
- }else if(UIRenderer.choosingTowerFlag == 3){ //defensive wheel
- TowerSprite.setChosenTowerType(TypeOfTower.ZONE);
+ if(mousePosition.x > mousePosition.y && radialMenu.getWidth()-mousePosition.x > mousePosition.y){ //click on top quarter
+ if(UIRenderer.choosingTowerFlag == 2){ //offensive wheel
+ TowerSprite.setChosenTowerType(TypeOfTower.SPEED);
+ }else if(UIRenderer.choosingTowerFlag == 3){ //defensive wheel
+ TowerSprite.setChosenTowerType(TypeOfTower.FREEZE);
+ }
+ }else if(mousePosition.x > mousePosition.y && radialMenu.getWidth()-mousePosition.x < mousePosition.y){ //click on right quarter
+ if(UIRenderer.choosingTowerFlag == 2){ //offensive wheel
+ TowerSprite.setChosenTowerType(TypeOfTower.DIVISION);
+ }else if(UIRenderer.choosingTowerFlag == 3){ //defensive wheel
+ TowerSprite.setChosenTowerType(TypeOfTower.ZONE);
+ }
+ }else if(mousePosition.x < mousePosition.y && radialMenu.getWidth()-mousePosition.x > mousePosition.y){ //click on left quarter
+ if(UIRenderer.choosingTowerFlag == 2){ //offensive wheel
+ TowerSprite.setChosenTowerType(TypeOfTower.RESISTANT);
+ }else if(UIRenderer.choosingTowerFlag == 3){ //defensive wheel
+ TowerSprite.setChosenTowerType(TypeOfTower.DAMAGE);
+ }
+ }else if(mousePosition.x < mousePosition.y && radialMenu.getWidth()-mousePosition.x < mousePosition.y){ //click on bottom quarter
+ if(UIRenderer.choosingTowerFlag == 2){ //offensive wheel
+ TowerSprite.setChosenTowerType(TypeOfTower.PROLIFERATION);
+ }else if(UIRenderer.choosingTowerFlag == 3){ //defensive wheel
+ TowerSprite.setChosenTowerType(TypeOfTower.POISON);
+ }
}
UIRenderer.choosingTowerFlag = 4;
}
}
}
});
}
/**
* Display a "WINNER" message when the player win and before exit program
*/
public void displayWinner(){
this.container.add(this.winnerBackground, Layer.UI.id());
}
/**
* Display a "LOSER" message when the player lose and before exit program
*/
public void displayLoser(){
this.container.add(this.loserBackground, Layer.UI.id());
}
/**
* Display or hide a radial menu to choose how many units send
*/
public void refreshRadialMenuMovment(){
switch(UIRenderer.choosingUnitFlag){
//if the player haven't chosen yet
case 0:
if(SelectedSprite.isThereAtLeastOneStartingElement() && SelectedSprite.isThereAnEndingElement()){
UIRenderer.choosingUnitFlag = 1;
Point mousePosition = MouseInfo.getPointerInfo().getLocation();
SwingUtilities.convertPointFromScreen(mousePosition, this.container);
mousePosition.x -= this.radialMenuMovment.getWidth()/2;
mousePosition.y -= this.radialMenuMovment.getHeight()/2;
this.radialMenuMovment.setLocation(mousePosition);
}
break;
//if the player is choosing
case 1:
if(this.radialMenuMovment.getParent() == null){
this.container.add(this.radialMenuMovment, Layer.UI.id());
}
break;
//if the player have just chosen
case 2:
this.container.remove(this.radialMenuMovment);
UIRenderer.choosingUnitFlag = 0;
break;
default:
break;
}
}
/**
* Display or hide the radial menu to choose tower
*/
public void refreshRadialMenuTower(){
switch(UIRenderer.choosingTowerFlag){
//if the player haven't chosen yet
case 0:
if(TowerSprite.isThereOneTowerToBuild()){
UIRenderer.choosingTowerFlag = 1;
Point mousePosition = MouseInfo.getPointerInfo().getLocation();
SwingUtilities.convertPointFromScreen(mousePosition, this.container);
mousePosition.x -= this.radialMenuTower.getWidth()/2;
mousePosition.y -= this.radialMenuTower.getHeight()/2;
this.radialMenuTower.setLocation(mousePosition);
}
break;
//if the player is choosing tower type
case 1:
if(this.radialMenuTower.getParent() == null){
this.container.add(this.radialMenuTower, Layer.UI.id());
}
break;
//if the player is choosing offensive tower
case 2:
this.radialMenuTower.goToSprite(1);
break;
//if the player is choosing defensive tower
case 3:
this.radialMenuTower.goToSprite(2);
break;
//if the player have just chosen
case 4:
if(!TowerSprite.isThereOneTowerToBuild()){
this.container.remove(this.radialMenuTower);
this.radialMenuTower.goToSprite(0);
UIRenderer.choosingTowerFlag = 0;
TowerSprite.setChosenTowerType(null);
}
break;
default:
break;
}
}
/**
* Hide the radial menu for unit choice and re-initialize it
*/
public void hideRadialMenuMovment(){
UIRenderer.choosingUnitFlag = 0;
if(this.radialMenuMovment.getParent() != null){
this.container.remove(this.radialMenuMovment);
}
}
/**
* Add the player's images at the bottom of the window.
* @param newPlayers
*/
public void addPlayerSprites(HashMap<String, Player> newPlayers){
PlayerSprite newSpritePlayer = new PlayerSprite(newPlayers.get("Player"));
newSpritePlayer.setImage(TypeOfPlayer.PLAYER.getImageOfPlayer());
newSpritePlayer.setBounds(10, this.height - newSpritePlayer.size - 30, newSpritePlayer.size, newSpritePlayer.size);
this.container.add(newSpritePlayer, new Integer(UI_LAYER));
this.playerSprites.add(newSpritePlayer);
PlayerSprite newSpriteIA_1 = new PlayerSprite(newPlayers.get("IA_1"));
newSpriteIA_1.setImage(TypeOfPlayer.IA_1.getImageOfPlayer());
newSpriteIA_1.setBounds(this.width - 10 - newSpriteIA_1.size, this.height - newSpriteIA_1.size - 30, newSpriteIA_1.size, newSpriteIA_1.size);
this.container.add(newSpriteIA_1, new Integer(UI_LAYER));
this.playerSprites.add(newSpriteIA_1);
if(newPlayers.size() == 3){
PlayerSprite newSpriteIA_2 = new PlayerSprite(newPlayers.get("IA_2"));
newSpriteIA_2.setImage(TypeOfPlayer.IA_2.getImageOfPlayer());
newSpriteIA_2.setBounds(this.width / 2, this.height - newSpriteIA_2.size - 30, newSpriteIA_2.size, newSpriteIA_2.size);
this.container.add(newSpriteIA_2, new Integer(UI_LAYER));
this.playerSprites.add(newSpriteIA_2);
}
}
// GETTERS & SETTERS
/**
* Hide the radial menu for tower choice and re-initialize it
*/
public void hideRadialMenuTower(){
UIRenderer.choosingTowerFlag = 0;
if(this.radialMenuTower.getParent() != null){
this.container.remove(this.radialMenuTower);
}
}
public boolean isChoosingUnitFlag(){
if(UIRenderer.choosingUnitFlag == 1){
return true;
}
return false;
}
public double getUnitPercentChosen(){
return UIRenderer.unitPercentChosen;
}
/**
* Check if the player have chosen his tower type
* @return boolean - true if te tower type is chosen
*/
public boolean isTowerTypeChosen(){
if(UIRenderer.choosingTowerFlag == 4){
return true;
}
return false;
}
public ArrayList<PlayerSprite> getPlayerSprites() {
return playerSprites;
}
}
| true | true | public void init() throws IOException{
//Load the winner background image
ImageIcon bgWinnerImage = new ImageIcon("./tex/youWin.png");
if(bgWinnerImage.getImageLoadStatus() != MediaTracker.COMPLETE){
throw new IOException();
}
this.winnerBackground.setBounds(0, 0, this.width, this.height);
this.winnerBackground.setIcon(bgWinnerImage);
//Load the looser background image
ImageIcon bgLoserImage = new ImageIcon("./tex/youLose.png");
if(bgLoserImage.getImageLoadStatus() != MediaTracker.COMPLETE){
throw new IOException();
}
this.loserBackground.setBounds(0, 0, this.width, this.height);
this.loserBackground.setIcon(bgLoserImage);
//Load the radial menu image for unit choice
ImageIcon rmImage = new ImageIcon("./tex/radialmenu_movment.png");
if(rmImage.getImageLoadStatus() != MediaTracker.COMPLETE){
throw new IOException();
}
this.radialMenuMovment.setIcon(rmImage);
this.radialMenuMovment.setSize(rmImage.getIconWidth(), rmImage.getIconHeight());
//Load the radial menu image for tower choice
this.radialMenuTower.setSize(80);
this.radialMenuTower.setImage(ImageIO.read(new File("./tex/radialmenu_tower.png")));
this.radialMenuTower.setSize(this.radialMenuTower.getSpriteSize(), this.radialMenuTower.getSpriteSize());
//Manage events
this.radialMenuMovment.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent arg0) {}
@Override
public void mousePressed(MouseEvent arg0) {}
@Override
public void mouseExited(MouseEvent arg0) {}
@Override
public void mouseEntered(MouseEvent arg0) {}
@Override
public void mouseClicked(MouseEvent arg0) {
//fix the bug of controling opponent units when he takes our base during the choice
boolean aSeletedBaseIsNotAPlayerBase = false;
for(Element element:SelectedSprite.startingElements){
if(element.getClass() == Base.class){
if(!((Base) element).isAPlayerBase())
aSeletedBaseIsNotAPlayerBase = true;
}
}
if(aSeletedBaseIsNotAPlayerBase){
SelectedSprite.resetStartingElements();
SelectedSprite.resetEndingElement();
TowerSprite.resetTowerToBuild();
Dispatcher.getRenderer().hideRadialMenus();
return;
}
UIRenderer.choosingUnitFlag = 2;
JLabel radialMenu = (JLabel) arg0.getComponent();
Point rmCenter = new Point(radialMenu.getWidth()/2, radialMenu.getHeight()/2);
Point mousePosition = arg0.getPoint();
if(rmCenter.distance(mousePosition) < 10){ //click on the center 50%
UIRenderer.unitPercentChosen = 0.5;
}else{
if(mousePosition.x > mousePosition.y && radialMenu.getWidth()-mousePosition.x > mousePosition.y){ //click on top quarter 50%
UIRenderer.unitPercentChosen = 0.5;
}else if(mousePosition.x > mousePosition.y && radialMenu.getWidth()-mousePosition.x < mousePosition.y){ //click on right quarter 75%
UIRenderer.unitPercentChosen = 0.75;
}else if(mousePosition.x < mousePosition.y && radialMenu.getWidth()-mousePosition.x > mousePosition.y){ //click on left quarter 25%
UIRenderer.unitPercentChosen = 0.25;
}else if(mousePosition.x < mousePosition.y && radialMenu.getWidth()-mousePosition.x < mousePosition.y){ //click on bottom quarter 99%
UIRenderer.unitPercentChosen = 1.;
}
}
}
});
this.radialMenuTower.addMouseListener(new MouseListener() {
@Override
public void mousePressed(MouseEvent arg0) {}
@Override
public void mouseReleased(MouseEvent arg0) {}
@Override
public void mouseExited(MouseEvent arg0) {}
@Override
public void mouseEntered(MouseEvent arg0) {}
@Override
public void mouseClicked(MouseEvent arg0) {
MultipleSprite radialMenu = (MultipleSprite) arg0.getComponent();
Point rmCenter = new Point(radialMenu.getWidth()/2, radialMenu.getHeight()/2);
Point mousePosition = arg0.getPoint();
//click out of the center circle
if(rmCenter.distance(mousePosition) > 10){
if(UIRenderer.choosingTowerFlag == 1){
//choose offensive or defensive
if(mousePosition.x - rmCenter.x < 0){ //left side offensive
UIRenderer.choosingTowerFlag = 2;
}else{ //right side defensive
UIRenderer.choosingTowerFlag = 3;
}
}else{
if(UIRenderer.choosingTowerFlag == 2){ //offensive wheel
TowerSprite.setChosenTowerType(TypeOfTower.SPEED);
}else if(UIRenderer.choosingTowerFlag == 3){ //defensive wheel
TowerSprite.setChosenTowerType(TypeOfTower.ZONE);
}
UIRenderer.choosingTowerFlag = 4;
}
}
}
});
}
| public void init() throws IOException{
//Load the winner background image
ImageIcon bgWinnerImage = new ImageIcon("./tex/youWin.png");
if(bgWinnerImage.getImageLoadStatus() != MediaTracker.COMPLETE){
throw new IOException();
}
this.winnerBackground.setBounds(0, 0, this.width, this.height);
this.winnerBackground.setIcon(bgWinnerImage);
//Load the looser background image
ImageIcon bgLoserImage = new ImageIcon("./tex/youLose.png");
if(bgLoserImage.getImageLoadStatus() != MediaTracker.COMPLETE){
throw new IOException();
}
this.loserBackground.setBounds(0, 0, this.width, this.height);
this.loserBackground.setIcon(bgLoserImage);
//Load the radial menu image for unit choice
ImageIcon rmImage = new ImageIcon("./tex/radialmenu_movment.png");
if(rmImage.getImageLoadStatus() != MediaTracker.COMPLETE){
throw new IOException();
}
this.radialMenuMovment.setIcon(rmImage);
this.radialMenuMovment.setSize(rmImage.getIconWidth(), rmImage.getIconHeight());
//Load the radial menu image for tower choice
this.radialMenuTower.setSize(80);
this.radialMenuTower.setImage(ImageIO.read(new File("./tex/radialmenu_tower.png")));
this.radialMenuTower.setSize(this.radialMenuTower.getSpriteSize(), this.radialMenuTower.getSpriteSize());
//Manage events
this.radialMenuMovment.addMouseListener(new MouseListener() {
@Override
public void mouseReleased(MouseEvent arg0) {}
@Override
public void mousePressed(MouseEvent arg0) {}
@Override
public void mouseExited(MouseEvent arg0) {}
@Override
public void mouseEntered(MouseEvent arg0) {}
@Override
public void mouseClicked(MouseEvent arg0) {
//fix the bug of controling opponent units when he takes our base during the choice
boolean aSeletedBaseIsNotAPlayerBase = false;
for(Element element:SelectedSprite.startingElements){
if(element.getClass() == Base.class){
if(!((Base) element).isAPlayerBase())
aSeletedBaseIsNotAPlayerBase = true;
}
}
if(aSeletedBaseIsNotAPlayerBase){
SelectedSprite.resetStartingElements();
SelectedSprite.resetEndingElement();
TowerSprite.resetTowerToBuild();
Dispatcher.getRenderer().hideRadialMenus();
return;
}
UIRenderer.choosingUnitFlag = 2;
JLabel radialMenu = (JLabel) arg0.getComponent();
Point rmCenter = new Point(radialMenu.getWidth()/2, radialMenu.getHeight()/2);
Point mousePosition = arg0.getPoint();
if(rmCenter.distance(mousePosition) < 10){ //click on the center 50%
UIRenderer.unitPercentChosen = 0.5;
}else{
if(mousePosition.x > mousePosition.y && radialMenu.getWidth()-mousePosition.x > mousePosition.y){ //click on top quarter 50%
UIRenderer.unitPercentChosen = 0.5;
}else if(mousePosition.x > mousePosition.y && radialMenu.getWidth()-mousePosition.x < mousePosition.y){ //click on right quarter 75%
UIRenderer.unitPercentChosen = 0.75;
}else if(mousePosition.x < mousePosition.y && radialMenu.getWidth()-mousePosition.x > mousePosition.y){ //click on left quarter 25%
UIRenderer.unitPercentChosen = 0.25;
}else if(mousePosition.x < mousePosition.y && radialMenu.getWidth()-mousePosition.x < mousePosition.y){ //click on bottom quarter 99%
UIRenderer.unitPercentChosen = 1.;
}
}
}
});
this.radialMenuTower.addMouseListener(new MouseListener() {
@Override
public void mousePressed(MouseEvent arg0) {}
@Override
public void mouseReleased(MouseEvent arg0) {}
@Override
public void mouseExited(MouseEvent arg0) {}
@Override
public void mouseEntered(MouseEvent arg0) {}
@Override
public void mouseClicked(MouseEvent arg0) {
MultipleSprite radialMenu = (MultipleSprite) arg0.getComponent();
Point rmCenter = new Point(radialMenu.getWidth()/2, radialMenu.getHeight()/2);
Point mousePosition = arg0.getPoint();
//click out of the center circle
if(rmCenter.distance(mousePosition) > 10){
if(UIRenderer.choosingTowerFlag == 1){
//choose offensive or defensive
if(mousePosition.x - rmCenter.x < 0){ //left side offensive
UIRenderer.choosingTowerFlag = 2;
}else{ //right side defensive
UIRenderer.choosingTowerFlag = 3;
}
}else{
if(mousePosition.x > mousePosition.y && radialMenu.getWidth()-mousePosition.x > mousePosition.y){ //click on top quarter
if(UIRenderer.choosingTowerFlag == 2){ //offensive wheel
TowerSprite.setChosenTowerType(TypeOfTower.SPEED);
}else if(UIRenderer.choosingTowerFlag == 3){ //defensive wheel
TowerSprite.setChosenTowerType(TypeOfTower.FREEZE);
}
}else if(mousePosition.x > mousePosition.y && radialMenu.getWidth()-mousePosition.x < mousePosition.y){ //click on right quarter
if(UIRenderer.choosingTowerFlag == 2){ //offensive wheel
TowerSprite.setChosenTowerType(TypeOfTower.DIVISION);
}else if(UIRenderer.choosingTowerFlag == 3){ //defensive wheel
TowerSprite.setChosenTowerType(TypeOfTower.ZONE);
}
}else if(mousePosition.x < mousePosition.y && radialMenu.getWidth()-mousePosition.x > mousePosition.y){ //click on left quarter
if(UIRenderer.choosingTowerFlag == 2){ //offensive wheel
TowerSprite.setChosenTowerType(TypeOfTower.RESISTANT);
}else if(UIRenderer.choosingTowerFlag == 3){ //defensive wheel
TowerSprite.setChosenTowerType(TypeOfTower.DAMAGE);
}
}else if(mousePosition.x < mousePosition.y && radialMenu.getWidth()-mousePosition.x < mousePosition.y){ //click on bottom quarter
if(UIRenderer.choosingTowerFlag == 2){ //offensive wheel
TowerSprite.setChosenTowerType(TypeOfTower.PROLIFERATION);
}else if(UIRenderer.choosingTowerFlag == 3){ //defensive wheel
TowerSprite.setChosenTowerType(TypeOfTower.POISON);
}
}
UIRenderer.choosingTowerFlag = 4;
}
}
}
});
}
|
diff --git a/simplesim/RobotMap.java b/simplesim/RobotMap.java
index 6dc8f93..4c48aa2 100644
--- a/simplesim/RobotMap.java
+++ b/simplesim/RobotMap.java
@@ -1,90 +1,90 @@
import java.util.*;
import java.io.*;
/**
* Class to hold map data for use by the simulator
* (not the same as the map class in the user API)
*/
public class RobotMap {
// the map used in the methods (singleton)
private static RobotMap theMap = new RobotMap();
private HashMap<String,MapNode> nodes;
/**
* Private constructor for the singleton pattern.
*/
private RobotMap() {
try {
- Scanner input = new Scanner(new File("../corobot_map/map/waypoints.csv"));
+ Scanner input = new Scanner(new File("../../corobots/corobot_map/map/waypoints.csv"));
String nodeline = input.nextLine(); // toss the headers of the csv
nodes = new HashMap<String,MapNode>();
while (input.hasNextLine()) {
nodeline = input.nextLine();
String[] parts = nodeline.split(",");
// name xpix ypix xm ym type nbrs...
MapNode newnode = new MapNode();
newnode.name = parts[0].toUpperCase();
double x = Double.parseDouble(parts[3]);
double y = Double.parseDouble(parts[4]);
newnode.pos = new Point(x,y);
newnode.nbrs = new LinkedList<String>();
for (int i = 6; i < parts.length; i++)
if (!(parts[i].equals("")))
newnode.nbrs.add(parts[i].toUpperCase());
nodes.put(newnode.name,newnode);
}
} catch (IOException e) {
System.err.println("Map cannot be built!");
System.err.println(e);
}
}
/**
* For use in planning: all nodes, ordered by distance from given point
* Does not consider obstacles.
* @param p Point to measure from
* @return Map of distance to node, including all nodes
*/
public static TreeMap<Double,MapNode> getNodesFromLoc(Point p) {
TreeMap<Double,MapNode> pts = new TreeMap<Double,MapNode>();
for (MapNode n : theMap.nodes.values()) {
double d = p.dist(n.pos);
pts.put(d,n);
}
return pts;
}
/**
* All the waypoint nodes
* @return Map of name -> node
*/
public static HashMap<String,MapNode> getNodes() {
return theMap.nodes;
}
/**
* Just the names of the waypoints
* @return Set of names
*/
public static Set<String> getNodeNames() {
return theMap.nodes.keySet();
}
/**
* Node by name
* @return node
*/
public static MapNode getNode(String name) {
return theMap.nodes.get(name);
}
}
/**
* Map node for use internally
*/
class MapNode {
String name;
Point pos; // in meters
List<String> nbrs;
}
| true | true | private RobotMap() {
try {
Scanner input = new Scanner(new File("../corobot_map/map/waypoints.csv"));
String nodeline = input.nextLine(); // toss the headers of the csv
nodes = new HashMap<String,MapNode>();
while (input.hasNextLine()) {
nodeline = input.nextLine();
String[] parts = nodeline.split(",");
// name xpix ypix xm ym type nbrs...
MapNode newnode = new MapNode();
newnode.name = parts[0].toUpperCase();
double x = Double.parseDouble(parts[3]);
double y = Double.parseDouble(parts[4]);
newnode.pos = new Point(x,y);
newnode.nbrs = new LinkedList<String>();
for (int i = 6; i < parts.length; i++)
if (!(parts[i].equals("")))
newnode.nbrs.add(parts[i].toUpperCase());
nodes.put(newnode.name,newnode);
}
} catch (IOException e) {
System.err.println("Map cannot be built!");
System.err.println(e);
}
}
| private RobotMap() {
try {
Scanner input = new Scanner(new File("../../corobots/corobot_map/map/waypoints.csv"));
String nodeline = input.nextLine(); // toss the headers of the csv
nodes = new HashMap<String,MapNode>();
while (input.hasNextLine()) {
nodeline = input.nextLine();
String[] parts = nodeline.split(",");
// name xpix ypix xm ym type nbrs...
MapNode newnode = new MapNode();
newnode.name = parts[0].toUpperCase();
double x = Double.parseDouble(parts[3]);
double y = Double.parseDouble(parts[4]);
newnode.pos = new Point(x,y);
newnode.nbrs = new LinkedList<String>();
for (int i = 6; i < parts.length; i++)
if (!(parts[i].equals("")))
newnode.nbrs.add(parts[i].toUpperCase());
nodes.put(newnode.name,newnode);
}
} catch (IOException e) {
System.err.println("Map cannot be built!");
System.err.println(e);
}
}
|
diff --git a/src/actions/imagemosaic/src/main/java/it/geosolutions/geobatch/imagemosaic/ImageMosaicOutput.java b/src/actions/imagemosaic/src/main/java/it/geosolutions/geobatch/imagemosaic/ImageMosaicOutput.java
index f525eaad..4c5921d7 100644
--- a/src/actions/imagemosaic/src/main/java/it/geosolutions/geobatch/imagemosaic/ImageMosaicOutput.java
+++ b/src/actions/imagemosaic/src/main/java/it/geosolutions/geobatch/imagemosaic/ImageMosaicOutput.java
@@ -1,262 +1,262 @@
/*
* GeoBatch - Open Source geospatial batch processing system
* http://geobatch.geo-solutions.it/
* Copyright (C) 2007-2011 GeoSolutions S.A.S.
* http://www.geo-solutions.it
*
* GPLv3 + Classpath exception
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package it.geosolutions.geobatch.imagemosaic;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.geotools.coverage.grid.io.AbstractGridCoverage2DReader;
import org.geotools.coverage.grid.io.AbstractGridFormat;
import org.geotools.factory.Hints;
import org.geotools.gce.imagemosaic.ImageMosaicFormat;
import org.geotools.geometry.GeneralEnvelope;
import org.geotools.referencing.CRS;
import org.opengis.geometry.DirectPosition;
import org.opengis.referencing.FactoryException;
import org.opengis.referencing.NoSuchAuthorityCodeException;
import org.opengis.referencing.crs.CoordinateReferenceSystem;
import org.opengis.referencing.operation.TransformException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.XStreamException;
public class ImageMosaicOutput {
public static String NATIVE_LOWER_CORNER_FIRST_KEY = "NATIVE_LOWER_CORNER_FIRST";
public static String NATIVE_LOWER_CORNER_SECOND_KEY = "NATIVE_LOWER_CORNER_SECOND";
public static String NATIVE_UPPER_CORNER_FIRST_KEY = "NATIVE_UPPER_CORNER_FIRST";
public static String NATIVE_UPPER_CORNER_SECOND_KEY = "NATIVE_UPPER_CORNER_SECOND";
public static String LONLAT_LOWER_CORNER_FIRST_KEY = "LONLAT_LOWER_CORNER_FIRST";
public static String LONLAT_LOWER_CORNER_SECOND_KEY = "LONLAT_LOWER_CORNER_SECOND";
public static String LONLAT_UPPER_CORNER_FIRST_KEY = "LONLAT_UPPER_CORNER_FIRST";
public static String LONLAT_UPPER_CORNER_SECOND_KEY = "LONLAT_UPPER_CORNER_SECOND";
public static String CRS_KEY = "CRS";
public static String STORENAME = "STORENAME";
public static String WORKSPACE = "WORKSPACE";
public static String LAYERNAME = "LAYERNAME";
public static String DEFAULT_STYLE = "DEFAULT_STYLE";
private final static Logger LOGGER = LoggerFactory.getLogger(ImageMosaicOutput.class);
/*
* used to read properties from an already created imagemosaic.
*/
private static final AbstractGridFormat IMAGEMOSAIC_FORMAT = new ImageMosaicFormat();
/**
* /**
* Write the ImageMosaic output to an XML file using XStream
*
* @param baseDir
* @param outDir
* directory where to place the output
* @param storename
* @param workspace
* @param layername
* @return
*/
protected static File writeReturn(final File baseDir, final File outDir, final ImageMosaicCommand cmd) {
final String layerName=cmd.getLayerName();
final File layerDescriptor = new File(outDir, layerName + ".xml");
FileWriter outFile=null;
try {
final XStream xstream = new XStream();
outFile = new FileWriter(layerDescriptor);
// the output structure
Map<String, Object> outMap = new HashMap<String, Object>();
outMap.put(STORENAME, cmd.getStoreName());
outMap.put(WORKSPACE, cmd.getDefaultNamespace());
outMap.put(LAYERNAME, layerName);
outMap.put(DEFAULT_STYLE, cmd.getDefaultStyle());
// TODO ADD AS NEEDED ...
setReaderData(baseDir, outMap);
xstream.toXML(outMap, outFile);
} catch (XStreamException e) {
// XStreamException - if the object cannot be serialized
if (LOGGER.isErrorEnabled())
LOGGER.error("setReturn the object cannot be serialized");
} catch (IOException e) {
// XStreamException - if the object cannot be serialized
if (LOGGER.isErrorEnabled())
LOGGER.error("setReturn the object cannot be serialized");
} finally {
IOUtils.closeQuietly(outFile);
}
return layerDescriptor;
}
/**
* using ImageMosaic reader extract needed data from the mosaic
*/
private static boolean setReaderData(final File directory, final Map<String, Object> map)
throws IOException {
AbstractGridCoverage2DReader reader = null;
final String absolutePath = directory.getAbsolutePath();
final String inputFileName = FilenameUtils.getName(absolutePath);
try {
// /////////////////////////////////////////////////////////////////////
//
// ACQUIRING A READER
//
// /////////////////////////////////////////////////////////////////////
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Acquiring a reader for the provided directory...");
}
// ETj 20120824: ImageMosaicFormat.accepts() returns false when passing a dir,
// but the getReader will work anyway.
// Commenting out this check will make the action work properly.
// Pls recheck.
// if (!IMAGEMOSAIC_FORMAT.accepts(directory)) {
// final String message = "IMAGEMOSAIC_FORMAT do not accept the directory: "
// + directory.getAbsolutePath();
// final IOException ioe = new IOException(message);
// if (LOGGER.isErrorEnabled())
// LOGGER.error(message, ioe);
// throw ioe;
// }
reader = (AbstractGridCoverage2DReader) IMAGEMOSAIC_FORMAT.getReader(directory,
new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE));
if (reader == null) {
final String message = "Unable to find a reader for the provided file: "
+ inputFileName;
final IOException ioe = new IOException(message);
if (LOGGER.isErrorEnabled())
LOGGER.error(message, ioe);
throw ioe;
}
// HAS_TIME_DOMAIN this is a boolean String with values true|false. Meaning is obvious.
// TIME_DOMAIN this returns a String that is a comma separated list of time values in
// ZULU time using the ISO 8601 format (yyyy-MM-dd'T'HH:mm:ss.SSS)
- if (reader.getMetadataValue(AbstractGridCoverage2DReader.HAS_TIME_DOMAIN) == "true") {
+ if ("true".equals(reader.getMetadataValue(AbstractGridCoverage2DReader.HAS_TIME_DOMAIN))) {
map.put(AbstractGridCoverage2DReader.HAS_TIME_DOMAIN, Boolean.TRUE);
final String times = reader.getMetadataValue(AbstractGridCoverage2DReader.TIME_DOMAIN);
final Set<String> timesList = new TreeSet<String>();
for (String time : times.split(",")) {
timesList.add(time);
}
// Collections.sort(timesList);
map.put(AbstractGridCoverage2DReader.TIME_DOMAIN, timesList);
} else {
map.put(AbstractGridCoverage2DReader.HAS_TIME_DOMAIN, Boolean.FALSE);
}
// ELEVATION
- if (reader.getMetadataValue(AbstractGridCoverage2DReader.HAS_ELEVATION_DOMAIN) == "true") {
+ if ("true".equals(reader.getMetadataValue(AbstractGridCoverage2DReader.HAS_ELEVATION_DOMAIN))) {
map.put(AbstractGridCoverage2DReader.HAS_ELEVATION_DOMAIN, Boolean.TRUE);
final String elevations = reader.getMetadataValue(AbstractGridCoverage2DReader.ELEVATION_DOMAIN);
final Set<String> elevList = new TreeSet<String>();
for (String time : elevations.split(",")) {
elevList.add(time);
}
map.put(AbstractGridCoverage2DReader.ELEVATION_DOMAIN, elevList);
} else {
map.put(AbstractGridCoverage2DReader.HAS_ELEVATION_DOMAIN, Boolean.FALSE);
}
final GeneralEnvelope originalEnvelope = reader.getOriginalEnvelope();
// Setting BoundingBox
DirectPosition position = originalEnvelope.getLowerCorner();
double[] lowerCorner = position.getCoordinate();
map.put(NATIVE_LOWER_CORNER_FIRST_KEY, (Double) lowerCorner[0]);
map.put(NATIVE_LOWER_CORNER_SECOND_KEY, (Double) lowerCorner[1]);
position = originalEnvelope.getUpperCorner();
double[] upperCorner = position.getCoordinate();
map.put(NATIVE_UPPER_CORNER_FIRST_KEY, (Double) upperCorner[0]);
map.put(NATIVE_UPPER_CORNER_SECOND_KEY, (Double) upperCorner[1]);
// Setting crs
map.put(CRS_KEY, reader.getCrs());
// computing lon/lat bbox
final CoordinateReferenceSystem wgs84;
try {
wgs84 = CRS.decode("EPSG:4326", true);
final GeneralEnvelope lonLatBBOX = (GeneralEnvelope) CRS.transform(
originalEnvelope, wgs84);
// Setting BoundingBox
position = lonLatBBOX.getLowerCorner();
lowerCorner = position.getCoordinate();
map.put(LONLAT_LOWER_CORNER_FIRST_KEY, (Double) lowerCorner[0]);
map.put(LONLAT_LOWER_CORNER_SECOND_KEY, (Double) lowerCorner[1]);
position = lonLatBBOX.getUpperCorner();
upperCorner = position.getCoordinate();
map.put(LONLAT_UPPER_CORNER_FIRST_KEY, (Double) upperCorner[0]);
map.put(LONLAT_UPPER_CORNER_SECOND_KEY, (Double) upperCorner[1]);
} catch (NoSuchAuthorityCodeException e) {
if (LOGGER.isWarnEnabled())
LOGGER.warn(e.getLocalizedMessage(), e);
} catch (FactoryException e) {
if (LOGGER.isErrorEnabled())
LOGGER.error(e.getLocalizedMessage(), e);
} catch (TransformException e) {
if (LOGGER.isErrorEnabled())
LOGGER.error(e.getLocalizedMessage(), e);
}
} finally {
if (reader != null) {
try {
reader.dispose();
} catch (Exception e) {
if (LOGGER.isWarnEnabled())
LOGGER.warn(e.getLocalizedMessage(), e);
}
}
}
return true;
}
}
| false | true | private static boolean setReaderData(final File directory, final Map<String, Object> map)
throws IOException {
AbstractGridCoverage2DReader reader = null;
final String absolutePath = directory.getAbsolutePath();
final String inputFileName = FilenameUtils.getName(absolutePath);
try {
// /////////////////////////////////////////////////////////////////////
//
// ACQUIRING A READER
//
// /////////////////////////////////////////////////////////////////////
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Acquiring a reader for the provided directory...");
}
// ETj 20120824: ImageMosaicFormat.accepts() returns false when passing a dir,
// but the getReader will work anyway.
// Commenting out this check will make the action work properly.
// Pls recheck.
// if (!IMAGEMOSAIC_FORMAT.accepts(directory)) {
// final String message = "IMAGEMOSAIC_FORMAT do not accept the directory: "
// + directory.getAbsolutePath();
// final IOException ioe = new IOException(message);
// if (LOGGER.isErrorEnabled())
// LOGGER.error(message, ioe);
// throw ioe;
// }
reader = (AbstractGridCoverage2DReader) IMAGEMOSAIC_FORMAT.getReader(directory,
new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE));
if (reader == null) {
final String message = "Unable to find a reader for the provided file: "
+ inputFileName;
final IOException ioe = new IOException(message);
if (LOGGER.isErrorEnabled())
LOGGER.error(message, ioe);
throw ioe;
}
// HAS_TIME_DOMAIN this is a boolean String with values true|false. Meaning is obvious.
// TIME_DOMAIN this returns a String that is a comma separated list of time values in
// ZULU time using the ISO 8601 format (yyyy-MM-dd'T'HH:mm:ss.SSS)
if (reader.getMetadataValue(AbstractGridCoverage2DReader.HAS_TIME_DOMAIN) == "true") {
map.put(AbstractGridCoverage2DReader.HAS_TIME_DOMAIN, Boolean.TRUE);
final String times = reader.getMetadataValue(AbstractGridCoverage2DReader.TIME_DOMAIN);
final Set<String> timesList = new TreeSet<String>();
for (String time : times.split(",")) {
timesList.add(time);
}
// Collections.sort(timesList);
map.put(AbstractGridCoverage2DReader.TIME_DOMAIN, timesList);
} else {
map.put(AbstractGridCoverage2DReader.HAS_TIME_DOMAIN, Boolean.FALSE);
}
// ELEVATION
if (reader.getMetadataValue(AbstractGridCoverage2DReader.HAS_ELEVATION_DOMAIN) == "true") {
map.put(AbstractGridCoverage2DReader.HAS_ELEVATION_DOMAIN, Boolean.TRUE);
final String elevations = reader.getMetadataValue(AbstractGridCoverage2DReader.ELEVATION_DOMAIN);
final Set<String> elevList = new TreeSet<String>();
for (String time : elevations.split(",")) {
elevList.add(time);
}
map.put(AbstractGridCoverage2DReader.ELEVATION_DOMAIN, elevList);
} else {
map.put(AbstractGridCoverage2DReader.HAS_ELEVATION_DOMAIN, Boolean.FALSE);
}
final GeneralEnvelope originalEnvelope = reader.getOriginalEnvelope();
// Setting BoundingBox
DirectPosition position = originalEnvelope.getLowerCorner();
double[] lowerCorner = position.getCoordinate();
map.put(NATIVE_LOWER_CORNER_FIRST_KEY, (Double) lowerCorner[0]);
map.put(NATIVE_LOWER_CORNER_SECOND_KEY, (Double) lowerCorner[1]);
position = originalEnvelope.getUpperCorner();
double[] upperCorner = position.getCoordinate();
map.put(NATIVE_UPPER_CORNER_FIRST_KEY, (Double) upperCorner[0]);
map.put(NATIVE_UPPER_CORNER_SECOND_KEY, (Double) upperCorner[1]);
// Setting crs
map.put(CRS_KEY, reader.getCrs());
// computing lon/lat bbox
final CoordinateReferenceSystem wgs84;
try {
wgs84 = CRS.decode("EPSG:4326", true);
final GeneralEnvelope lonLatBBOX = (GeneralEnvelope) CRS.transform(
originalEnvelope, wgs84);
// Setting BoundingBox
position = lonLatBBOX.getLowerCorner();
lowerCorner = position.getCoordinate();
map.put(LONLAT_LOWER_CORNER_FIRST_KEY, (Double) lowerCorner[0]);
map.put(LONLAT_LOWER_CORNER_SECOND_KEY, (Double) lowerCorner[1]);
position = lonLatBBOX.getUpperCorner();
upperCorner = position.getCoordinate();
map.put(LONLAT_UPPER_CORNER_FIRST_KEY, (Double) upperCorner[0]);
map.put(LONLAT_UPPER_CORNER_SECOND_KEY, (Double) upperCorner[1]);
} catch (NoSuchAuthorityCodeException e) {
if (LOGGER.isWarnEnabled())
LOGGER.warn(e.getLocalizedMessage(), e);
} catch (FactoryException e) {
if (LOGGER.isErrorEnabled())
LOGGER.error(e.getLocalizedMessage(), e);
} catch (TransformException e) {
if (LOGGER.isErrorEnabled())
LOGGER.error(e.getLocalizedMessage(), e);
}
} finally {
if (reader != null) {
try {
reader.dispose();
} catch (Exception e) {
if (LOGGER.isWarnEnabled())
LOGGER.warn(e.getLocalizedMessage(), e);
}
}
}
return true;
}
| private static boolean setReaderData(final File directory, final Map<String, Object> map)
throws IOException {
AbstractGridCoverage2DReader reader = null;
final String absolutePath = directory.getAbsolutePath();
final String inputFileName = FilenameUtils.getName(absolutePath);
try {
// /////////////////////////////////////////////////////////////////////
//
// ACQUIRING A READER
//
// /////////////////////////////////////////////////////////////////////
if (LOGGER.isInfoEnabled()) {
LOGGER.info("Acquiring a reader for the provided directory...");
}
// ETj 20120824: ImageMosaicFormat.accepts() returns false when passing a dir,
// but the getReader will work anyway.
// Commenting out this check will make the action work properly.
// Pls recheck.
// if (!IMAGEMOSAIC_FORMAT.accepts(directory)) {
// final String message = "IMAGEMOSAIC_FORMAT do not accept the directory: "
// + directory.getAbsolutePath();
// final IOException ioe = new IOException(message);
// if (LOGGER.isErrorEnabled())
// LOGGER.error(message, ioe);
// throw ioe;
// }
reader = (AbstractGridCoverage2DReader) IMAGEMOSAIC_FORMAT.getReader(directory,
new Hints(Hints.FORCE_LONGITUDE_FIRST_AXIS_ORDER, Boolean.TRUE));
if (reader == null) {
final String message = "Unable to find a reader for the provided file: "
+ inputFileName;
final IOException ioe = new IOException(message);
if (LOGGER.isErrorEnabled())
LOGGER.error(message, ioe);
throw ioe;
}
// HAS_TIME_DOMAIN this is a boolean String with values true|false. Meaning is obvious.
// TIME_DOMAIN this returns a String that is a comma separated list of time values in
// ZULU time using the ISO 8601 format (yyyy-MM-dd'T'HH:mm:ss.SSS)
if ("true".equals(reader.getMetadataValue(AbstractGridCoverage2DReader.HAS_TIME_DOMAIN))) {
map.put(AbstractGridCoverage2DReader.HAS_TIME_DOMAIN, Boolean.TRUE);
final String times = reader.getMetadataValue(AbstractGridCoverage2DReader.TIME_DOMAIN);
final Set<String> timesList = new TreeSet<String>();
for (String time : times.split(",")) {
timesList.add(time);
}
// Collections.sort(timesList);
map.put(AbstractGridCoverage2DReader.TIME_DOMAIN, timesList);
} else {
map.put(AbstractGridCoverage2DReader.HAS_TIME_DOMAIN, Boolean.FALSE);
}
// ELEVATION
if ("true".equals(reader.getMetadataValue(AbstractGridCoverage2DReader.HAS_ELEVATION_DOMAIN))) {
map.put(AbstractGridCoverage2DReader.HAS_ELEVATION_DOMAIN, Boolean.TRUE);
final String elevations = reader.getMetadataValue(AbstractGridCoverage2DReader.ELEVATION_DOMAIN);
final Set<String> elevList = new TreeSet<String>();
for (String time : elevations.split(",")) {
elevList.add(time);
}
map.put(AbstractGridCoverage2DReader.ELEVATION_DOMAIN, elevList);
} else {
map.put(AbstractGridCoverage2DReader.HAS_ELEVATION_DOMAIN, Boolean.FALSE);
}
final GeneralEnvelope originalEnvelope = reader.getOriginalEnvelope();
// Setting BoundingBox
DirectPosition position = originalEnvelope.getLowerCorner();
double[] lowerCorner = position.getCoordinate();
map.put(NATIVE_LOWER_CORNER_FIRST_KEY, (Double) lowerCorner[0]);
map.put(NATIVE_LOWER_CORNER_SECOND_KEY, (Double) lowerCorner[1]);
position = originalEnvelope.getUpperCorner();
double[] upperCorner = position.getCoordinate();
map.put(NATIVE_UPPER_CORNER_FIRST_KEY, (Double) upperCorner[0]);
map.put(NATIVE_UPPER_CORNER_SECOND_KEY, (Double) upperCorner[1]);
// Setting crs
map.put(CRS_KEY, reader.getCrs());
// computing lon/lat bbox
final CoordinateReferenceSystem wgs84;
try {
wgs84 = CRS.decode("EPSG:4326", true);
final GeneralEnvelope lonLatBBOX = (GeneralEnvelope) CRS.transform(
originalEnvelope, wgs84);
// Setting BoundingBox
position = lonLatBBOX.getLowerCorner();
lowerCorner = position.getCoordinate();
map.put(LONLAT_LOWER_CORNER_FIRST_KEY, (Double) lowerCorner[0]);
map.put(LONLAT_LOWER_CORNER_SECOND_KEY, (Double) lowerCorner[1]);
position = lonLatBBOX.getUpperCorner();
upperCorner = position.getCoordinate();
map.put(LONLAT_UPPER_CORNER_FIRST_KEY, (Double) upperCorner[0]);
map.put(LONLAT_UPPER_CORNER_SECOND_KEY, (Double) upperCorner[1]);
} catch (NoSuchAuthorityCodeException e) {
if (LOGGER.isWarnEnabled())
LOGGER.warn(e.getLocalizedMessage(), e);
} catch (FactoryException e) {
if (LOGGER.isErrorEnabled())
LOGGER.error(e.getLocalizedMessage(), e);
} catch (TransformException e) {
if (LOGGER.isErrorEnabled())
LOGGER.error(e.getLocalizedMessage(), e);
}
} finally {
if (reader != null) {
try {
reader.dispose();
} catch (Exception e) {
if (LOGGER.isWarnEnabled())
LOGGER.warn(e.getLocalizedMessage(), e);
}
}
}
return true;
}
|
diff --git a/src/main/java/com/thoughtworks/controllers/LoginController.java b/src/main/java/com/thoughtworks/controllers/LoginController.java
index 70299e4..8bc4ec7 100644
--- a/src/main/java/com/thoughtworks/controllers/LoginController.java
+++ b/src/main/java/com/thoughtworks/controllers/LoginController.java
@@ -1,81 +1,80 @@
package com.thoughtworks.controllers;
import com.thoughtworks.models.User;
import com.thoughtworks.repositories.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Map;
@Controller
@SessionAttributes(types = User.class)
public class LoginController {
@Qualifier("userRepository")
@Autowired
private UserRepository repository;
@RequestMapping(value = "/", method = RequestMethod.GET)
public String login_request(Map<String, Object> model) {
User login = new User();
model.put("login", login);
return "user/index";
}
@RequestMapping(value = "/", method = RequestMethod.POST)
public String login(@RequestParam("employeeId") Long employeeId, @RequestParam("password") String password, HttpServletRequest request) {
User user = repository.findOne(employeeId);
if(user != null && user.getPassword().equals(password)){
request.getSession().setAttribute("isAdmin", user.isAdmin());
request.getSession().setAttribute("employeeId", employeeId);
request.getSession().setAttribute("fullName", user.getFullName());
request.getSession().setAttribute("isLogin", true);
return "redirect:book/index";
}
- request.getSession().setAttribute("isAdmin", user.isAdmin());
request.getSession().setAttribute("isLogin", false);
return "redirect:/";
}
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout(HttpServletRequest request) {
request.getSession().setAttribute("isAdmin", null);
request.getSession().setAttribute("isLogin", null);
return "redirect:/";
}
@RequestMapping(value = "/register", method = RequestMethod.GET)
public String register(Map<String, Object> model) {
User user = new User();
model.put("user", user);
return "user/register";
}
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(@ModelAttribute("user") @Valid User user, BindingResult result, HttpServletRequest request, RedirectAttributes attributes) {
if (result.hasErrors()) {
attributes.addFlashAttribute("errorMassage","you not registered...........");
return "user/register";
}
user.setActive(true);
this.repository.save(user);
request.getSession().setAttribute("isLogin", Boolean.TRUE);
request.getSession().setAttribute("isAdmin", Boolean.FALSE);
attributes.addFlashAttribute("successMessage","you are registered successfully........");
return "redirect:book/index";
}
}
| true | true | public String login(@RequestParam("employeeId") Long employeeId, @RequestParam("password") String password, HttpServletRequest request) {
User user = repository.findOne(employeeId);
if(user != null && user.getPassword().equals(password)){
request.getSession().setAttribute("isAdmin", user.isAdmin());
request.getSession().setAttribute("employeeId", employeeId);
request.getSession().setAttribute("fullName", user.getFullName());
request.getSession().setAttribute("isLogin", true);
return "redirect:book/index";
}
request.getSession().setAttribute("isAdmin", user.isAdmin());
request.getSession().setAttribute("isLogin", false);
return "redirect:/";
}
| public String login(@RequestParam("employeeId") Long employeeId, @RequestParam("password") String password, HttpServletRequest request) {
User user = repository.findOne(employeeId);
if(user != null && user.getPassword().equals(password)){
request.getSession().setAttribute("isAdmin", user.isAdmin());
request.getSession().setAttribute("employeeId", employeeId);
request.getSession().setAttribute("fullName", user.getFullName());
request.getSession().setAttribute("isLogin", true);
return "redirect:book/index";
}
request.getSession().setAttribute("isLogin", false);
return "redirect:/";
}
|
diff --git a/src/tesseract/objects/Icosahedron.java b/src/tesseract/objects/Icosahedron.java
index 7786f85..eafd1a1 100644
--- a/src/tesseract/objects/Icosahedron.java
+++ b/src/tesseract/objects/Icosahedron.java
@@ -1,193 +1,193 @@
/*
* Icosahedron.java
* TCSS 491 Computational Worlds
* Phillip Cardon
*/
package tesseract.objects;
import javax.media.j3d.Appearance;
import javax.media.j3d.ColoringAttributes;
import javax.media.j3d.GeometryArray;
import javax.media.j3d.Group;
import javax.media.j3d.Material;
import javax.media.j3d.Shape3D;
import javax.media.j3d.TransformGroup;
import javax.media.j3d.TriangleArray;
import javax.vecmath.Point3f;
import javax.vecmath.Vector3f;
import com.sun.j3d.utils.geometry.GeometryInfo;
import com.sun.j3d.utils.geometry.NormalGenerator;
/**
* Represents an Icosahedron, a 20 sided object who's
* faces are all equal equilateral triangles.
* @author Phillip Cardon
* @verson 0.9a
*/
public class Icosahedron extends ForceableObject {
//CONSTANTS
private static final int MAX_ANGLE = 120;
private static final float DEFAULT_SCALE = 1;
private static final int NUM_VERTEX = 12;
private static final float GOLDEN_RATIO = (float) ((1.0 + Math.sqrt(5.0)) / 2.0);
//FIELDS
private Shape3D myShape;
private float myScale;
private TransformGroup myTG;
//CONSTRUCTORS
/**
* Create new Icosahedron.
*/
public Icosahedron(final Vector3f position, final float mass, float scale) {
this(position, mass);
myScale = scale;
}
/**
* Create new Icosahedron.
* @param position Initial Position.
* @param mass object mass.
*/
public Icosahedron(final Vector3f position, final float mass) {
super(position, mass);
myScale = DEFAULT_SCALE;
myTG = new TransformGroup();
}
public void buildIcosahedron() {
// TODO Auto-generated method stub
Point3f coordinates[] = new Point3f[NUM_VERTEX];
float phi = GOLDEN_RATIO;
int i = 0;
// Y / Z Plane coordinates
coordinates[i++] = new Point3f(0f, 1.0f, phi); //0
coordinates[i++] = new Point3f(0f, 1.0f, -1 * phi);
coordinates[i++] = new Point3f(0f, -1.0f, -1 * phi);
coordinates[i++] = new Point3f(0f, -1.0f, phi);
// X / Y Plane coordinates
coordinates[i++] = new Point3f(1f, phi, 0); //4
coordinates[i++] = new Point3f(-1f, phi, 0);
coordinates[i++] = new Point3f(1f, -1 * phi, 0);
coordinates[i++] = new Point3f(-1f, -1 *phi, 0);
// X / Z Plane coordinates
coordinates[i++] = new Point3f(phi, 0, 1f); //8
coordinates[i++] = new Point3f(phi, 0, -1f);
coordinates[i++] = new Point3f(-1 * phi, 0, 1f);
coordinates[i++] = new Point3f(-1 * phi, 0, -1f);
// TODO: Scaling
for (int it = 0; it < coordinates.length; it++) {
- coordinates[it].scale((float) 2);
+ coordinates[it].scale((float) myScale);
}
GeometryArray die = new TriangleArray(((NUM_VERTEX / 2) - 1) *
coordinates.length, GeometryArray.COORDINATES);
int index = 0;
//Builds triangles
die.setCoordinate(index++, coordinates[0]);
die.setCoordinate(index++, coordinates[8]);
die.setCoordinate(index++, coordinates[4]);
die.setCoordinate(index++, coordinates[0]);
die.setCoordinate(index++, coordinates[4]);
die.setCoordinate(index++, coordinates[5]);
die.setCoordinate(index++, coordinates[0]);
die.setCoordinate(index++, coordinates[5]);
die.setCoordinate(index++, coordinates[10]);
die.setCoordinate(index++, coordinates[0]);
die.setCoordinate(index++, coordinates[10]);
die.setCoordinate(index++, coordinates[3]);
die.setCoordinate(index++, coordinates[0]);
die.setCoordinate(index++, coordinates[3]);
die.setCoordinate(index++, coordinates[8]);
die.setCoordinate(index++, coordinates[8]);
die.setCoordinate(index++, coordinates[9]);
die.setCoordinate(index++, coordinates[4]);
die.setCoordinate(index++, coordinates[4]);
die.setCoordinate(index++, coordinates[9]);
die.setCoordinate(index++, coordinates[1]);
die.setCoordinate(index++, coordinates[4]);
die.setCoordinate(index++, coordinates[1]);
die.setCoordinate(index++, coordinates[5]);
die.setCoordinate(index++, coordinates[5]);
die.setCoordinate(index++, coordinates[1]);
die.setCoordinate(index++, coordinates[11]);
die.setCoordinate(index++, coordinates[5]);
die.setCoordinate(index++, coordinates[11]);
die.setCoordinate(index++, coordinates[10]);
die.setCoordinate(index++, coordinates[10]);
die.setCoordinate(index++, coordinates[11]);
die.setCoordinate(index++, coordinates[7]);
die.setCoordinate(index++, coordinates[10]);
die.setCoordinate(index++, coordinates[7]);
die.setCoordinate(index++, coordinates[3]);
die.setCoordinate(index++, coordinates[3]);
die.setCoordinate(index++, coordinates[7]);
die.setCoordinate(index++, coordinates[6]);
die.setCoordinate(index++, coordinates[3]);
die.setCoordinate(index++, coordinates[6]);
die.setCoordinate(index++, coordinates[8]);
die.setCoordinate(index++, coordinates[8]);
die.setCoordinate(index++, coordinates[6]);
die.setCoordinate(index++, coordinates[9]);
die.setCoordinate(index++, coordinates[9]);
die.setCoordinate(index++, coordinates[2]);
die.setCoordinate(index++, coordinates[1]);
die.setCoordinate(index++, coordinates[1]);
die.setCoordinate(index++, coordinates[2]);
die.setCoordinate(index++, coordinates[11]);
die.setCoordinate(index++, coordinates[11]);
die.setCoordinate(index++, coordinates[2]);
die.setCoordinate(index++, coordinates[7]);
die.setCoordinate(index++, coordinates[7]);
die.setCoordinate(index++, coordinates[2]);
die.setCoordinate(index++, coordinates[6]);
die.setCoordinate(index++, coordinates[6]);
die.setCoordinate(index++, coordinates[2]);
die.setCoordinate(index++, coordinates[9]);
TransformGroup trans = new TransformGroup();
NormalGenerator norms = new NormalGenerator(MAX_ANGLE);
GeometryInfo geo = new GeometryInfo(die);
norms.generateNormals(geo);
Shape3D mesh = new Shape3D(geo.getGeometryArray());
Appearance meshApp = new Appearance();
Material surface = new Material();
surface.setDiffuseColor(.9f, .05f, .05f);
meshApp.setMaterial(surface);
meshApp.setColoringAttributes(new ColoringAttributes(.9f,
.05f, .05f, ColoringAttributes.NICEST));
mesh.setAppearance(meshApp);
myTG.addChild(mesh);
}
public Group getGroup(){
return (Group) myTG.cloneTree();
}
}
| true | true | public void buildIcosahedron() {
// TODO Auto-generated method stub
Point3f coordinates[] = new Point3f[NUM_VERTEX];
float phi = GOLDEN_RATIO;
int i = 0;
// Y / Z Plane coordinates
coordinates[i++] = new Point3f(0f, 1.0f, phi); //0
coordinates[i++] = new Point3f(0f, 1.0f, -1 * phi);
coordinates[i++] = new Point3f(0f, -1.0f, -1 * phi);
coordinates[i++] = new Point3f(0f, -1.0f, phi);
// X / Y Plane coordinates
coordinates[i++] = new Point3f(1f, phi, 0); //4
coordinates[i++] = new Point3f(-1f, phi, 0);
coordinates[i++] = new Point3f(1f, -1 * phi, 0);
coordinates[i++] = new Point3f(-1f, -1 *phi, 0);
// X / Z Plane coordinates
coordinates[i++] = new Point3f(phi, 0, 1f); //8
coordinates[i++] = new Point3f(phi, 0, -1f);
coordinates[i++] = new Point3f(-1 * phi, 0, 1f);
coordinates[i++] = new Point3f(-1 * phi, 0, -1f);
// TODO: Scaling
for (int it = 0; it < coordinates.length; it++) {
coordinates[it].scale((float) 2);
}
GeometryArray die = new TriangleArray(((NUM_VERTEX / 2) - 1) *
coordinates.length, GeometryArray.COORDINATES);
int index = 0;
//Builds triangles
die.setCoordinate(index++, coordinates[0]);
die.setCoordinate(index++, coordinates[8]);
die.setCoordinate(index++, coordinates[4]);
die.setCoordinate(index++, coordinates[0]);
die.setCoordinate(index++, coordinates[4]);
die.setCoordinate(index++, coordinates[5]);
die.setCoordinate(index++, coordinates[0]);
die.setCoordinate(index++, coordinates[5]);
die.setCoordinate(index++, coordinates[10]);
die.setCoordinate(index++, coordinates[0]);
die.setCoordinate(index++, coordinates[10]);
die.setCoordinate(index++, coordinates[3]);
die.setCoordinate(index++, coordinates[0]);
die.setCoordinate(index++, coordinates[3]);
die.setCoordinate(index++, coordinates[8]);
die.setCoordinate(index++, coordinates[8]);
die.setCoordinate(index++, coordinates[9]);
die.setCoordinate(index++, coordinates[4]);
die.setCoordinate(index++, coordinates[4]);
die.setCoordinate(index++, coordinates[9]);
die.setCoordinate(index++, coordinates[1]);
die.setCoordinate(index++, coordinates[4]);
die.setCoordinate(index++, coordinates[1]);
die.setCoordinate(index++, coordinates[5]);
die.setCoordinate(index++, coordinates[5]);
die.setCoordinate(index++, coordinates[1]);
die.setCoordinate(index++, coordinates[11]);
die.setCoordinate(index++, coordinates[5]);
die.setCoordinate(index++, coordinates[11]);
die.setCoordinate(index++, coordinates[10]);
die.setCoordinate(index++, coordinates[10]);
die.setCoordinate(index++, coordinates[11]);
die.setCoordinate(index++, coordinates[7]);
die.setCoordinate(index++, coordinates[10]);
die.setCoordinate(index++, coordinates[7]);
die.setCoordinate(index++, coordinates[3]);
die.setCoordinate(index++, coordinates[3]);
die.setCoordinate(index++, coordinates[7]);
die.setCoordinate(index++, coordinates[6]);
die.setCoordinate(index++, coordinates[3]);
die.setCoordinate(index++, coordinates[6]);
die.setCoordinate(index++, coordinates[8]);
die.setCoordinate(index++, coordinates[8]);
die.setCoordinate(index++, coordinates[6]);
die.setCoordinate(index++, coordinates[9]);
die.setCoordinate(index++, coordinates[9]);
die.setCoordinate(index++, coordinates[2]);
die.setCoordinate(index++, coordinates[1]);
die.setCoordinate(index++, coordinates[1]);
die.setCoordinate(index++, coordinates[2]);
die.setCoordinate(index++, coordinates[11]);
die.setCoordinate(index++, coordinates[11]);
die.setCoordinate(index++, coordinates[2]);
die.setCoordinate(index++, coordinates[7]);
die.setCoordinate(index++, coordinates[7]);
die.setCoordinate(index++, coordinates[2]);
die.setCoordinate(index++, coordinates[6]);
die.setCoordinate(index++, coordinates[6]);
die.setCoordinate(index++, coordinates[2]);
die.setCoordinate(index++, coordinates[9]);
TransformGroup trans = new TransformGroup();
NormalGenerator norms = new NormalGenerator(MAX_ANGLE);
GeometryInfo geo = new GeometryInfo(die);
norms.generateNormals(geo);
Shape3D mesh = new Shape3D(geo.getGeometryArray());
Appearance meshApp = new Appearance();
Material surface = new Material();
surface.setDiffuseColor(.9f, .05f, .05f);
meshApp.setMaterial(surface);
meshApp.setColoringAttributes(new ColoringAttributes(.9f,
.05f, .05f, ColoringAttributes.NICEST));
mesh.setAppearance(meshApp);
myTG.addChild(mesh);
}
| public void buildIcosahedron() {
// TODO Auto-generated method stub
Point3f coordinates[] = new Point3f[NUM_VERTEX];
float phi = GOLDEN_RATIO;
int i = 0;
// Y / Z Plane coordinates
coordinates[i++] = new Point3f(0f, 1.0f, phi); //0
coordinates[i++] = new Point3f(0f, 1.0f, -1 * phi);
coordinates[i++] = new Point3f(0f, -1.0f, -1 * phi);
coordinates[i++] = new Point3f(0f, -1.0f, phi);
// X / Y Plane coordinates
coordinates[i++] = new Point3f(1f, phi, 0); //4
coordinates[i++] = new Point3f(-1f, phi, 0);
coordinates[i++] = new Point3f(1f, -1 * phi, 0);
coordinates[i++] = new Point3f(-1f, -1 *phi, 0);
// X / Z Plane coordinates
coordinates[i++] = new Point3f(phi, 0, 1f); //8
coordinates[i++] = new Point3f(phi, 0, -1f);
coordinates[i++] = new Point3f(-1 * phi, 0, 1f);
coordinates[i++] = new Point3f(-1 * phi, 0, -1f);
// TODO: Scaling
for (int it = 0; it < coordinates.length; it++) {
coordinates[it].scale((float) myScale);
}
GeometryArray die = new TriangleArray(((NUM_VERTEX / 2) - 1) *
coordinates.length, GeometryArray.COORDINATES);
int index = 0;
//Builds triangles
die.setCoordinate(index++, coordinates[0]);
die.setCoordinate(index++, coordinates[8]);
die.setCoordinate(index++, coordinates[4]);
die.setCoordinate(index++, coordinates[0]);
die.setCoordinate(index++, coordinates[4]);
die.setCoordinate(index++, coordinates[5]);
die.setCoordinate(index++, coordinates[0]);
die.setCoordinate(index++, coordinates[5]);
die.setCoordinate(index++, coordinates[10]);
die.setCoordinate(index++, coordinates[0]);
die.setCoordinate(index++, coordinates[10]);
die.setCoordinate(index++, coordinates[3]);
die.setCoordinate(index++, coordinates[0]);
die.setCoordinate(index++, coordinates[3]);
die.setCoordinate(index++, coordinates[8]);
die.setCoordinate(index++, coordinates[8]);
die.setCoordinate(index++, coordinates[9]);
die.setCoordinate(index++, coordinates[4]);
die.setCoordinate(index++, coordinates[4]);
die.setCoordinate(index++, coordinates[9]);
die.setCoordinate(index++, coordinates[1]);
die.setCoordinate(index++, coordinates[4]);
die.setCoordinate(index++, coordinates[1]);
die.setCoordinate(index++, coordinates[5]);
die.setCoordinate(index++, coordinates[5]);
die.setCoordinate(index++, coordinates[1]);
die.setCoordinate(index++, coordinates[11]);
die.setCoordinate(index++, coordinates[5]);
die.setCoordinate(index++, coordinates[11]);
die.setCoordinate(index++, coordinates[10]);
die.setCoordinate(index++, coordinates[10]);
die.setCoordinate(index++, coordinates[11]);
die.setCoordinate(index++, coordinates[7]);
die.setCoordinate(index++, coordinates[10]);
die.setCoordinate(index++, coordinates[7]);
die.setCoordinate(index++, coordinates[3]);
die.setCoordinate(index++, coordinates[3]);
die.setCoordinate(index++, coordinates[7]);
die.setCoordinate(index++, coordinates[6]);
die.setCoordinate(index++, coordinates[3]);
die.setCoordinate(index++, coordinates[6]);
die.setCoordinate(index++, coordinates[8]);
die.setCoordinate(index++, coordinates[8]);
die.setCoordinate(index++, coordinates[6]);
die.setCoordinate(index++, coordinates[9]);
die.setCoordinate(index++, coordinates[9]);
die.setCoordinate(index++, coordinates[2]);
die.setCoordinate(index++, coordinates[1]);
die.setCoordinate(index++, coordinates[1]);
die.setCoordinate(index++, coordinates[2]);
die.setCoordinate(index++, coordinates[11]);
die.setCoordinate(index++, coordinates[11]);
die.setCoordinate(index++, coordinates[2]);
die.setCoordinate(index++, coordinates[7]);
die.setCoordinate(index++, coordinates[7]);
die.setCoordinate(index++, coordinates[2]);
die.setCoordinate(index++, coordinates[6]);
die.setCoordinate(index++, coordinates[6]);
die.setCoordinate(index++, coordinates[2]);
die.setCoordinate(index++, coordinates[9]);
TransformGroup trans = new TransformGroup();
NormalGenerator norms = new NormalGenerator(MAX_ANGLE);
GeometryInfo geo = new GeometryInfo(die);
norms.generateNormals(geo);
Shape3D mesh = new Shape3D(geo.getGeometryArray());
Appearance meshApp = new Appearance();
Material surface = new Material();
surface.setDiffuseColor(.9f, .05f, .05f);
meshApp.setMaterial(surface);
meshApp.setColoringAttributes(new ColoringAttributes(.9f,
.05f, .05f, ColoringAttributes.NICEST));
mesh.setAppearance(meshApp);
myTG.addChild(mesh);
}
|
diff --git a/SoarSuite/Environments/Soar2D/src/soar2d/player/tanksoar/SoarTank.java b/SoarSuite/Environments/Soar2D/src/soar2d/player/tanksoar/SoarTank.java
index 10071b191..51736b31f 100644
--- a/SoarSuite/Environments/Soar2D/src/soar2d/player/tanksoar/SoarTank.java
+++ b/SoarSuite/Environments/Soar2D/src/soar2d/player/tanksoar/SoarTank.java
@@ -1,998 +1,1003 @@
package soar2d.player.tanksoar;
import java.util.*;
import java.util.logging.*;
import sml.*;
import soar2d.*;
import soar2d.player.InputLinkMetadata;
import soar2d.player.MoveInfo;
import soar2d.player.Player;
import soar2d.player.PlayerConfig;
import soar2d.player.RadarCell;
import soar2d.world.PlayersManager;
import soar2d.world.World;
public class SoarTank extends Tank implements Agent.RunEventInterface {
private Agent agent;
private ArrayList<String> shutdownCommands;
private Identifier m_InputLink;
private Identifier m_BlockedWME;
private StringElement m_BlockedBackwardWME;
private StringElement m_BlockedForwardWME;
private StringElement m_BlockedLeftWME;
private StringElement m_BlockedRightWME;
private IntElement m_ClockWME;
private Identifier m_CurrentScoreWME;
private HashMap<String, IntElement> m_Scores = new HashMap<String, IntElement>(7);
private StringElement m_DirectionWME;
private IntElement m_EnergyWME;
private StringElement m_EnergyRechargerWME;
private IntElement m_HealthWME;
private StringElement m_HealthRechargerWME;
private Identifier m_IncomingWME;
private StringElement m_IncomingBackwardWME;
private StringElement m_IncomingForwardWME;
private StringElement m_IncomingLeftWME;
private StringElement m_IncomingRightWME;
private IntElement m_MissilesWME;
private StringElement m_MyColorWME;
private StringElement m_RadarStatusWME;
private IntElement m_RadarDistanceWME;
private IntElement m_RadarSettingWME;
private Identifier m_RadarWME;
private FloatElement m_RandomWME;
private StringElement m_ResurrectWME;
private Identifier m_RWavesWME;
private StringElement m_RWavesBackwardWME;
private StringElement m_RWavesForwardWME;
private StringElement m_RWavesLeftWME;
private StringElement m_RWavesRightWME;
private StringElement m_ShieldStatusWME;
private Identifier m_SmellWME;
private StringElement m_SmellColorWME;
private IntElement m_SmellDistanceWME;
private StringElement m_SmellDistanceStringWME;
private StringElement m_SoundWME;
private IntElement m_xWME;
private IntElement m_yWME;
private Identifier[][] radarCellIDs;
private StringElement[][] radarColors;
private float random = 0;
private boolean m_Reset = true;
private boolean playersChanged = true;
private boolean attemptedMove = false;
private boolean mem_exceeded = false;
InputLinkMetadata metadata;
public SoarTank(Agent agent, PlayerConfig playerConfig) {
super(playerConfig);
this.agent = agent;
this.shutdownCommands = playerConfig.getShutdownCommands();
radarCellIDs = new Identifier[Soar2D.config.tConfig.getRadarWidth()][Soar2D.config.tConfig.getRadarHeight()];
radarColors = new StringElement[Soar2D.config.tConfig.getRadarWidth()][Soar2D.config.tConfig.getRadarHeight()];
assert agent != null;
agent.RegisterForRunEvent(smlRunEventId.smlEVENT_AFTER_INTERRUPT, this, null);
agent.RegisterForRunEvent(smlRunEventId.smlEVENT_MAX_MEMORY_USAGE_EXCEEDED, this, null);
m_InputLink = agent.GetInputLink();
previousLocation = new java.awt.Point(-1, -1);
loadMetadata();
}
private void loadMetadata() {
metadata = new InputLinkMetadata(agent);
try {
if (Soar2D.config.getMetadata() != null) {
metadata.load(Soar2D.config.getMetadata());
}
if (Soar2D.simulation.world.getMap().getMetadata() != null) {
metadata.load(Soar2D.simulation.world.getMap().getMetadata());
}
} catch (Exception e) {
Soar2D.control.severeError("Failed to load metadata: " + this.getName() + ": " + e.getMessage());
Soar2D.control.stopSimulation();
}
}
public void runEventHandler(int eventID, Object data, Agent agent, int phase) {
if (eventID == smlRunEventId.smlEVENT_AFTER_INTERRUPT.swigValue()) {
if (!Soar2D.control.isStopped()) {
logger.warning(getName() + ": agent interrupted");
Soar2D.simulation.world.interruped(agent.GetAgentName());
}
} else if (!mem_exceeded && eventID == smlRunEventId.smlEVENT_MAX_MEMORY_USAGE_EXCEEDED.swigValue()) {
logger.warning(getName() + ": agent exceeded maximum memory usage");
Soar2D.simulation.world.interruped(agent.GetAgentName());
Soar2D.control.stopSimulation();
mem_exceeded = true;
} else {
assert false;
}
}
private void DestroyWME(WMElement wme) {
assert wme != null;
agent.DestroyWME(wme);
}
private void Update(StringElement wme, String value) {
assert wme != null;
assert value != null;
agent.Update(wme, value);
}
private void Update(IntElement wme, int value) {
assert wme != null;
agent.Update(wme, value);
}
private void Update(FloatElement wme, float value) {
assert wme != null;
agent.Update(wme, value);
}
private IntElement CreateIntWME(Identifier id, String attribute, int value) {
assert id != null;
assert attribute != null;
return agent.CreateIntWME(id, attribute, value);
}
private StringElement CreateStringWME(Identifier id, String attribute, String value) {
assert id != null;
assert attribute != null;
assert value != null;
return agent.CreateStringWME(id, attribute, value);
}
private FloatElement CreateFloatWME(Identifier id, String attribute, float value) {
assert id != null;
assert attribute != null;
return agent.CreateFloatWME(id, attribute, value);
}
public void update(java.awt.Point location) {
super.update(location);
}
public MoveInfo getMove() {
if (Soar2D.config.getForceHuman()) {
return super.getMove();
}
resetSensors();
attemptedMove = false;
assert agent != null;
int numberOfCommands = agent.GetNumberCommands();
if (numberOfCommands == 0) {
if (logger.isLoggable(Level.FINER)) logger.finer(getName() + " issued no command.");
return new MoveInfo();
}
Identifier moveId = null;
MoveInfo move = new MoveInfo();
boolean moveWait = false;
for (int i = 0; i < numberOfCommands; ++i) {
Identifier commandId = agent.GetCommand(i);
String commandName = commandId.GetAttribute();
if (commandName.equalsIgnoreCase(Names.kMoveID)) {
if (move.move || moveWait) {
logger.warning(getName() + ": extra move commands");
commandId.AddStatusError();
continue;
}
String moveDirection = commandId.GetParameterValue(Names.kDirectionID);
if (moveDirection == null) {
logger.warning(getName() + ": null move direction");
commandId.AddStatusError();
continue;
}
if (moveDirection.equalsIgnoreCase(Names.kForwardID)) {
move.moveDirection = getFacingInt();
} else if (moveDirection.equalsIgnoreCase(Names.kBackwardID)) {
move.moveDirection = Direction.backwardOf[this.getFacingInt()];
} else if (moveDirection.equalsIgnoreCase(Names.kLeftID)) {
move.moveDirection = Direction.leftOf[this.getFacingInt()];
} else if (moveDirection.equalsIgnoreCase(Names.kRightID)) {
move.moveDirection = Direction.rightOf[this.getFacingInt()];
} else if (moveDirection.equalsIgnoreCase(Names.kNone)) {
// legal wait
moveWait = true;
commandId.AddStatusComplete();
continue;
} else {
logger.warning(getName() + ": illegal move direction: " + moveDirection);
commandId.AddStatusError();
continue;
}
moveId = commandId;
move.move = true;
attemptedMove = true;
} else if (commandName.equalsIgnoreCase(Names.kFireID)) {
if (move.fire == true) {
logger.warning(getName() + ": extra fire commands");
commandId.AddStatusError();
continue;
}
move.fire = true;
// Weapon ignored
} else if (commandName.equalsIgnoreCase(Names.kRadarID)) {
if (move.radar == true) {
logger.warning(getName() + ": extra radar commands");
commandId.AddStatusError();
continue;
}
String radarSwitch = commandId.GetParameterValue(Names.kSwitchID);
if (radarSwitch == null) {
logger.warning(getName() + ": null radar switch");
commandId.AddStatusError();
continue;
}
move.radar = true;
move.radarSwitch = radarSwitch.equalsIgnoreCase(Names.kOn) ? true : false;
} else if (commandName.equalsIgnoreCase(Names.kRadarPowerID)) {
if (move.radarPower == true) {
logger.warning(getName() + ": extra radar power commands");
commandId.AddStatusError();
continue;
}
String powerValue = commandId.GetParameterValue(Names.kSettingID);
if (powerValue == null) {
logger.warning(getName() + ": null radar power");
commandId.AddStatusError();
continue;
}
try {
move.radarPowerSetting = Integer.decode(powerValue).intValue();
} catch (NumberFormatException e) {
logger.warning(getName() + ": unable to parse radar power setting " + powerValue + ": " + e.getMessage());
commandId.AddStatusError();
continue;
}
move.radarPower = true;
} else if (commandName.equalsIgnoreCase(Names.kShieldsID)) {
if (move.shields == true) {
logger.warning(getName() + ": extra shield commands");
commandId.AddStatusError();
continue;
}
String shieldsSetting = commandId.GetParameterValue(Names.kSwitchID);
if (shieldsSetting == null) {
logger.warning(getName() + ": null shields setting");
commandId.AddStatusError();
continue;
}
move.shields = true;
move.shieldsSetting = shieldsSetting.equalsIgnoreCase(Names.kOn) ? true : false;
} else if (commandName.equalsIgnoreCase(Names.kRotateID)) {
if (move.rotate == true) {
logger.warning(getName() + ": extra rotate commands");
commandId.AddStatusError();
continue;
}
move.rotateDirection = commandId.GetParameterValue(Names.kDirectionID);
if (move.rotateDirection == null) {
logger.warning(getName() + ": null rotation direction");
commandId.AddStatusError();
continue;
}
move.rotate = true;
} else {
logger.warning(getName() + ": unknown command: " + commandName);
commandId.AddStatusError();
continue;
}
commandId.AddStatusComplete();
}
agent.ClearOutputLinkChanges();
if (!agent.Commit()) {
Soar2D.control.severeError("Failed to commit input to Soar agent " + this.getName());
Soar2D.control.stopSimulation();
}
// Do not allow a move if we rotated.
if (move.rotate) {
if (move.move) {
if (Soar2D.logger.isLoggable(Level.FINER)) logger.finer(": move ignored (rotating)");
assert moveId != null;
moveId.AddStatusError();
moveId = null;
move.move = false;
}
}
return move;
}
public void reset() {
super.reset();
mem_exceeded = false;
if (agent == null) {
return;
}
metadata.destroy();
metadata = null;
loadMetadata();
agent.InitSoar();
}
public void fragged() {
super.fragged();
if (m_Reset == true) {
return;
}
clearWMEs();
m_Reset = true;
}
void clearWMEs() {
DestroyWME(m_BlockedWME);
m_BlockedWME = null;
DestroyWME(m_ClockWME);
m_ClockWME = null;
DestroyWME(m_CurrentScoreWME);
m_CurrentScoreWME = null;
m_Scores = new HashMap<String, IntElement>(7);
DestroyWME(m_DirectionWME);
m_DirectionWME = null;
DestroyWME(m_EnergyWME);
m_EnergyWME = null;
DestroyWME(m_EnergyRechargerWME);
m_EnergyRechargerWME = null;
DestroyWME(m_HealthWME);
m_HealthWME = null;
DestroyWME(m_HealthRechargerWME);
m_HealthRechargerWME = null;
DestroyWME(m_IncomingWME);
m_IncomingWME = null;
DestroyWME(m_MissilesWME);
m_MissilesWME = null;
DestroyWME(m_MyColorWME);
m_MyColorWME = null;
DestroyWME(m_RadarStatusWME);
m_RadarStatusWME = null;
DestroyWME(m_RadarDistanceWME);
m_RadarDistanceWME = null;
DestroyWME(m_RadarSettingWME);
m_RadarSettingWME = null;
if (m_RadarWME != null) {
DestroyWME(m_RadarWME);
m_RadarWME = null;
}
DestroyWME(m_RandomWME);
m_RandomWME = null;
DestroyWME(m_ResurrectWME);
m_ResurrectWME = null;
DestroyWME(m_RWavesWME);
m_RWavesWME = null;
DestroyWME(m_ShieldStatusWME);
m_ShieldStatusWME = null;
DestroyWME(m_SmellWME);
m_SmellWME = null;
DestroyWME(m_SoundWME);
m_SoundWME = null;
DestroyWME(m_xWME);
m_xWME = null;
DestroyWME(m_yWME);
m_yWME = null;
if (!agent.Commit()) {
Soar2D.control.severeError("Failed to commit input to Soar agent " + this.getName());
Soar2D.control.stopSimulation();
}
clearRadar();
}
void initScoreWMEs() {
if (m_CurrentScoreWME == null) {
return;
}
HashSet<String> unseen = new HashSet<String>();
unseen.add("blue");
unseen.add("red");
unseen.add("yellow");
unseen.add("green");
unseen.add("purple");
unseen.add("orange");
unseen.add("black");
PlayersManager players = Soar2D.simulation.world.getPlayers();
Iterator<Player> playersIter = players.iterator();
while (playersIter.hasNext()) {
Player player = playersIter.next();
IntElement scoreElement = m_Scores.get(player.getColor());
unseen.remove(player.getColor());
if (scoreElement == null) {
scoreElement = agent.CreateIntWME(m_CurrentScoreWME, player.getColor(), player.getPoints());
m_Scores.put(player.getColor(), scoreElement);
}
}
Iterator<String> unseenIter = unseen.iterator();
while (unseenIter.hasNext()) {
String color = unseenIter.next();
IntElement unseenElement = m_Scores.remove(color);
if (unseenElement != null) {
DestroyWME(unseenElement);
}
}
playersChanged = false;
}
public void playersChanged() {
playersChanged = true;
}
public void commit(java.awt.Point location) {
int facing = getFacingInt();
String facingString = Direction.stringOf[facing];
World world = Soar2D.simulation.world;
String shieldStatus = shieldsUp ? Names.kOn : Names.kOff;
String blockedForward = ((blocked & Direction.indicators[facing]) > 0) ? Names.kYes : Names.kNo;
String blockedBackward = ((blocked & Direction.indicators[Direction.backwardOf[facing]]) > 0) ? Names.kYes : Names.kNo;
String blockedLeft = ((blocked & Direction.indicators[Direction.leftOf[facing]]) > 0) ? Names.kYes : Names.kNo;
String blockedRight = ((blocked & Direction.indicators[Direction.rightOf[facing]]) > 0) ? Names.kYes : Names.kNo;
String incomingForward = ((incoming & Direction.indicators[facing]) > 0) ? Names.kYes : Names.kNo;
String incomingBackward = ((incoming & Direction.indicators[Direction.backwardOf[facing]]) > 0) ? Names.kYes : Names.kNo;
String incomingLeft = ((incoming & Direction.indicators[Direction.leftOf[facing]]) > 0) ? Names.kYes : Names.kNo;
String incomingRight = ((incoming & Direction.indicators[Direction.rightOf[facing]]) > 0) ? Names.kYes : Names.kNo;
String smellColorString = (smellColor == null) ? Names.kNone : smellColor;
String soundString;
if (sound == facing) {
soundString = Names.kForwardID;
} else if (sound == Direction.backwardOf[facing]) {
soundString = Names.kBackwardID;
} else if (sound == Direction.leftOf[facing]) {
soundString = Names.kLeftID;
} else if (sound == Direction.rightOf[facing]) {
soundString = Names.kRightID;
} else {
soundString = Names.kSilentID;
}
int worldCount = world.getWorldCount();
String radarStatus = radarSwitch ? Names.kOn : Names.kOff;
float oldrandom = random;
do {
random = Simulation.random.nextFloat();
} while (random == oldrandom);
String rwavesForward = (rwaves & facing) > 0 ? Names.kYes : Names.kNo;
String rwavesBackward = (rwaves & Direction.indicators[Direction.backwardOf[facing]]) > 0 ? Names.kYes : Names.kNo;;
String rwavesLeft = (rwaves & Direction.indicators[Direction.leftOf[facing]]) > 0 ? Names.kYes : Names.kNo;
String rwavesRight = (rwaves & Direction.indicators[Direction.rightOf[facing]]) > 0 ? Names.kYes : Names.kNo;
if (Soar2D.logger.isLoggable(Level.FINEST)) {
logger.finest(this.getName() + " input dump: ");
logger.finest(this.getName() + ": x,y: " + location.x + "," + location.y);
logger.finest(this.getName() + ": " + Names.kEnergyRechargerID + ": " + (onEnergyCharger ? Names.kYes : Names.kNo));
logger.finest(this.getName() + ": " + Names.kHealthRechargerID + ": " + (onHealthCharger ? Names.kYes : Names.kNo));
logger.finest(this.getName() + ": " + Names.kDirectionID + ": " + facingString);
logger.finest(this.getName() + ": " + Names.kEnergyID + ": " + energy);
logger.finest(this.getName() + ": " + Names.kHealthID + ": " + health);
logger.finest(this.getName() + ": " + Names.kShieldStatusID + ": " + shieldStatus);
logger.finest(this.getName() + ": blocked (forward): " + blockedForward);
logger.finest(this.getName() + ": blocked (backward): " + blockedBackward);
logger.finest(this.getName() + ": blocked (left): " + blockedLeft);
logger.finest(this.getName() + ": blocked (right): " + blockedRight);
logger.finest(this.getName() + ": " + Names.kCurrentScoreID + ": TODO: dump");
logger.finest(this.getName() + ": incoming (forward): " + incomingForward);
logger.finest(this.getName() + ": incoming (backward): " + incomingBackward);
logger.finest(this.getName() + ": incoming (left): " + incomingLeft);
logger.finest(this.getName() + ": incoming (right): " + incomingRight);
logger.finest(this.getName() + ": smell (color): " + smellColorString);
logger.finest(this.getName() + ": smell (distance): " + smellDistance);
logger.finest(this.getName() + ": " + Names.kSoundID + ": " + soundString);
logger.finest(this.getName() + ": " + Names.kMissilesID + ": " + missiles);
logger.finest(this.getName() + ": " + Names.kMyColorID + ": " + getColor());
logger.finest(this.getName() + ": " + Names.kClockID + ": " + worldCount);
logger.finest(this.getName() + ": " + Names.kRadarStatusID + ": " + radarStatus);
logger.finest(this.getName() + ": " + Names.kRadarDistanceID + ": " + observedPower);
logger.finest(this.getName() + ": " + Names.kRadarSettingID + ": " + radarPower);
logger.finest(this.getName() + ": " + Names.kRandomID + "random: " + random);
logger.finest(this.getName() + ": rwaves (forward): " + rwavesForward);
logger.finest(this.getName() + ": rwaves (backward): " + rwavesBackward);
logger.finest(this.getName() + ": rwaves (left): " + rwavesLeft);
logger.finest(this.getName() + ": rwaves (right): " + rwavesRight);
}
if (m_Reset) {
// location
m_xWME = CreateIntWME(m_InputLink, Names.kXID, location.x);
m_yWME = CreateIntWME(m_InputLink, Names.kYID, location.y);
// charger detection
String energyRecharger = onEnergyCharger ? Names.kYes : Names.kNo;
m_EnergyRechargerWME = CreateStringWME(m_InputLink, Names.kEnergyRechargerID, energyRecharger);
String healthRecharger = onHealthCharger ? Names.kYes : Names.kNo;
m_HealthRechargerWME = CreateStringWME(m_InputLink, Names.kHealthRechargerID, healthRecharger);
// facing
m_DirectionWME = CreateStringWME(m_InputLink, Names.kDirectionID, facingString);
// energy and health status
m_EnergyWME = CreateIntWME(m_InputLink, Names.kEnergyID, energy);
m_HealthWME = CreateIntWME(m_InputLink, Names.kHealthID, health);
// shield status
m_ShieldStatusWME = CreateStringWME(m_InputLink, Names.kShieldStatusID, shieldStatus);
// blocked sensor
m_BlockedWME = agent.CreateIdWME(m_InputLink, Names.kBlockedID);
m_BlockedForwardWME = CreateStringWME(m_BlockedWME, Names.kForwardID, blockedForward);
m_BlockedBackwardWME = CreateStringWME(m_BlockedWME, Names.kBackwardID, blockedBackward);
m_BlockedLeftWME = CreateStringWME(m_BlockedWME, Names.kLeftID, blockedLeft);
m_BlockedRightWME = CreateStringWME(m_BlockedWME, Names.kRightID, blockedRight);
// score status
m_CurrentScoreWME = agent.CreateIdWME(m_InputLink, Names.kCurrentScoreID);
initScoreWMEs();
// incoming sensor
m_IncomingWME = agent.CreateIdWME(m_InputLink, Names.kIncomingID);
m_IncomingBackwardWME = CreateStringWME(m_IncomingWME, Names.kBackwardID, incomingForward);
m_IncomingForwardWME = CreateStringWME(m_IncomingWME, Names.kForwardID, incomingBackward);
m_IncomingLeftWME = CreateStringWME(m_IncomingWME, Names.kLeftID, incomingLeft);
m_IncomingRightWME = CreateStringWME(m_IncomingWME, Names.kRightID, incomingRight);
// smell sensor
m_SmellWME = agent.CreateIdWME(m_InputLink, Names.kSmellID);
m_SmellColorWME = CreateStringWME(m_SmellWME, Names.kColorID, smellColorString);
if (smellColor == null) {
m_SmellDistanceWME = null;
m_SmellDistanceStringWME = CreateStringWME(m_SmellWME, Names.kDistanceID, Names.kNone);
} else {
m_SmellDistanceWME = CreateIntWME(m_SmellWME, Names.kDistanceID, smellDistance);
m_SmellDistanceStringWME = null;
}
// sound sensor
m_SoundWME = CreateStringWME(m_InputLink, Names.kSoundID, soundString);
// missile quantity indicator
m_MissilesWME = CreateIntWME(m_InputLink, Names.kMissilesID, missiles);
// my color
m_MyColorWME = CreateStringWME(m_InputLink, Names.kMyColorID, getColor());
// clock (world count)
m_ClockWME = CreateIntWME(m_InputLink, Names.kClockID, worldCount);
// resurrect sensor
m_ResurrectWME = CreateStringWME(m_InputLink, Names.kResurrectID, Names.kYes);
// radar sensors
m_RadarStatusWME = CreateStringWME(m_InputLink, Names.kRadarStatusID, radarStatus);
if (radarSwitch) {
m_RadarWME = agent.CreateIdWME(m_InputLink, Names.kRadarID);
generateNewRadar();
} else {
m_RadarWME = null;
}
m_RadarDistanceWME = CreateIntWME(m_InputLink, Names.kRadarDistanceID, observedPower);
m_RadarSettingWME = CreateIntWME(m_InputLink, Names.kRadarSettingID, radarPower);
// random indicator
m_RandomWME = CreateFloatWME(m_InputLink, Names.kRandomID, random);
// rwaves sensor
m_RWavesWME = agent.CreateIdWME(m_InputLink, Names.kRWavesID);
m_RWavesForwardWME = CreateStringWME(m_RWavesWME, Names.kForwardID, rwavesBackward);
m_RWavesBackwardWME = CreateStringWME(m_RWavesWME, Names.kBackwardID, rwavesForward);
m_RWavesLeftWME = CreateStringWME(m_RWavesWME, Names.kLeftID, rwavesLeft);
m_RWavesRightWME = CreateStringWME(m_RWavesWME, Names.kRightID, rwavesRight);
} else {
if (moved) {
// location
if (location.x != m_xWME.GetValue()) {
Update(m_xWME, location.x);
}
if (location.y != m_yWME.GetValue()) {
Update(m_yWME, location.y);
}
// charger detection
+ // TODO: consider SetBlinkIfNoChange(false) in constructor
String energyRecharger = onEnergyCharger ? Names.kYes : Names.kNo;
- Update(m_EnergyRechargerWME, energyRecharger);
+ if ( !m_EnergyRechargerWME.GetValue().equals(energyRecharger) ) {
+ Update(m_EnergyRechargerWME, energyRecharger);
+ }
String healthRecharger = onHealthCharger ? Names.kYes : Names.kNo;
- Update(m_HealthRechargerWME, healthRecharger);
+ if ( !m_HealthRechargerWME.GetValue().equals(healthRecharger) ) {
+ Update(m_HealthRechargerWME, healthRecharger);
+ }
}
boolean rotated = !m_DirectionWME.GetValue().equalsIgnoreCase(facingString);
if (rotated) {
// facing
Update(m_DirectionWME, facingString);
}
- // charger detection
+ // stats detection
if (m_EnergyWME.GetValue() != energy) {
Update(m_EnergyWME, energy);
}
if (m_HealthWME.GetValue() != health) {
Update(m_HealthWME, health);
}
// shield status
if (!m_ShieldStatusWME.GetValue().equalsIgnoreCase(shieldStatus)) {
Update(m_ShieldStatusWME, shieldStatus);
}
// blocked sensor
if (attemptedMove || rotated || !m_BlockedForwardWME.GetValue().equalsIgnoreCase(blockedForward)) {
Update(m_BlockedForwardWME, blockedForward);
}
if (attemptedMove || rotated || !m_BlockedBackwardWME.GetValue().equalsIgnoreCase(blockedBackward)) {
Update(m_BlockedBackwardWME, blockedBackward);
}
if (attemptedMove || rotated || !m_BlockedLeftWME.GetValue().equalsIgnoreCase(blockedLeft)) {
Update(m_BlockedLeftWME, blockedLeft);
}
if (attemptedMove || rotated || !m_BlockedRightWME.GetValue().equalsIgnoreCase(blockedRight)) {
Update(m_BlockedRightWME, blockedRight);
}
// scores
if (playersChanged) {
initScoreWMEs();
}
Iterator<Player> playerIter = world.getPlayers().iterator();
while (playerIter.hasNext()) {
Player player = playerIter.next();
if (player.pointsChanged()) {
Update(m_Scores.get(player.getColor()), player.getPoints());
}
}
// incoming sensor
if (!m_IncomingForwardWME.GetValue().equalsIgnoreCase(incomingForward)) {
Update(m_IncomingForwardWME, incomingForward);
}
if (!m_IncomingBackwardWME.GetValue().equalsIgnoreCase(incomingBackward)) {
Update(m_IncomingBackwardWME, incomingBackward);
}
if (!m_IncomingLeftWME.GetValue().equalsIgnoreCase(incomingLeft)) {
Update(m_IncomingLeftWME, incomingLeft);
}
if (!m_IncomingRightWME.GetValue().equalsIgnoreCase(incomingRight)) {
Update(m_IncomingRightWME, incomingRight);
}
// smell sensor
if (!m_SmellColorWME.GetValue().equalsIgnoreCase(smellColorString)) {
Update(m_SmellColorWME, smellColorString);
}
if (smellColor == null) {
if (m_SmellDistanceWME != null) {
DestroyWME(m_SmellDistanceWME);
m_SmellDistanceWME = null;
}
if (m_SmellDistanceStringWME == null) {
m_SmellDistanceStringWME = CreateStringWME(m_SmellWME, Names.kDistanceID, Names.kNone);
}
} else {
if (m_SmellDistanceWME == null) {
m_SmellDistanceWME = CreateIntWME(m_SmellWME, Names.kDistanceID, smellDistance);
} else {
if (m_SmellDistanceWME.GetValue() != smellDistance) {
Update(m_SmellDistanceWME, smellDistance);
}
}
if (m_SmellDistanceStringWME != null) {
DestroyWME(m_SmellDistanceStringWME);
m_SmellDistanceStringWME = null;
}
}
// sound sensor
if (!m_SoundWME.GetValue().equalsIgnoreCase(soundString)) {
Update(m_SoundWME, soundString);
}
// missile quantity indicator
if (m_MissilesWME.GetValue() != missiles) {
Update(m_MissilesWME, missiles);
}
// clock (world count)
Update(m_ClockWME, worldCount);
// resurrect sensor
if (!getResurrect()) {
if (!m_ResurrectWME.GetValue().equalsIgnoreCase(Names.kNo)) {
Update(m_ResurrectWME, Names.kNo);
}
}
// radar sensors
if (!m_RadarStatusWME.GetValue().equalsIgnoreCase(radarStatus)) {
Update(m_RadarStatusWME, radarStatus);
}
if (radarSwitch) {
if (m_RadarWME == null) {
m_RadarWME = agent.CreateIdWME(m_InputLink, Names.kRadarID);
generateNewRadar();
} else {
updateRadar(moved || rotated);
}
} else {
if (m_RadarWME != null) {
clearRadar();
DestroyWME(m_RadarWME);
m_RadarWME = null;
}
}
if (m_RadarDistanceWME.GetValue() != observedPower) {
Update(m_RadarDistanceWME, observedPower);
}
if (m_RadarSettingWME.GetValue() != radarPower) {
Update(m_RadarSettingWME, radarPower);
}
// random indicator
Update(m_RandomWME, random);
// rwaves sensor
if (!m_RWavesForwardWME.GetValue().equalsIgnoreCase(rwavesForward)) {
Update(m_RWavesForwardWME, rwavesForward);
}
if (!m_RWavesBackwardWME.GetValue().equalsIgnoreCase(rwavesBackward)) {
Update(m_RWavesBackwardWME, rwavesBackward);
}
if (!m_RWavesLeftWME.GetValue().equalsIgnoreCase(rwavesLeft)) {
Update(m_RWavesLeftWME, rwavesLeft);
}
if (!m_RWavesRightWME.GetValue().equalsIgnoreCase(rwavesRight)) {
Update(m_RWavesRightWME, rwavesRight);
}
}
m_Reset = false;
if (!agent.Commit()) {
Soar2D.control.severeError("Failed to commit input to Soar agent " + this.getName());
Soar2D.control.stopSimulation();
}
}
private void generateNewRadar() {
int height;
if (Soar2D.logger.isLoggable(Level.FINEST)) {
logger.finest(this.getName() + ": radar data: generating new");
}
for (height = 0; height < Soar2D.config.tConfig.getRadarHeight(); ++height) {
boolean done = false;
for (int width = 0; width < Soar2D.config.tConfig.getRadarWidth(); ++width) {
// Always skip self, this screws up the tanks.
if (width == 1 && height == 0) {
if (Soar2D.logger.isLoggable(Level.FINEST)) {
logger.finest(this.getName() + ": " + height + "," + width + ": skip self");
}
continue;
}
if (radar[width][height] == null) {
// if center is null, we're done
if (width == 1) {
done = true;
if (Soar2D.logger.isLoggable(Level.FINEST)) {
logger.finest(this.getName() + ": " + height + "," + width + ": done (center null)");
}
break;
}
} else {
// Create a new WME
radarCellIDs[width][height] = agent.CreateIdWME(m_RadarWME, getCellID(radar[width][height]));
CreateIntWME(radarCellIDs[width][height], Names.kDistanceID, height);
CreateStringWME(radarCellIDs[width][height], Names.kPositionID, getPositionID(width));
if (radar[width][height].player != null) {
radarColors[width][height] = CreateStringWME(radarCellIDs[width][height], Names.kColorID, radar[width][height].player.getColor());
if (Soar2D.logger.isLoggable(Level.FINEST)) {
logger.finest(this.getName() + ": " + height + "," + width + ": " + getCellID(radar[width][height]) + " " + radar[width][height].player.getColor());
}
} else {
if (Soar2D.logger.isLoggable(Level.FINEST)) {
logger.finest(this.getName() + ": " + height + "," + width + ": " + getCellID(radar[width][height]));
}
}
}
}
if (done == true) {
break;
}
}
assert (height - 1) == this.observedPower;
}
private void updateRadar(boolean movedOrRotated) {
if (Soar2D.logger.isLoggable(Level.FINEST)) {
logger.finest(this.getName() + ": radar data: updating");
}
for (int width = 0; width < Soar2D.config.tConfig.getRadarWidth(); ++width) {
for (int height = 0; height < Soar2D.config.tConfig.getRadarHeight(); ++height) {
// Always skip self, this screws up the tanks.
if (width == 1 && height == 0) {
if (Soar2D.logger.isLoggable(Level.FINEST)) {
logger.finest(this.getName() + ": " + height + "," + width + ": skip self");
}
continue;
}
if (radar[width][height] == null || (height > observedPower) || ((height == observedPower) && (width != 1))) {
// Unconditionally delete the WME
if (radarCellIDs[width][height] != null) {
DestroyWME(radarCellIDs[width][height]);
radarCellIDs[width][height] = null;
radarColors[width][height] = null;
if (Soar2D.logger.isLoggable(Level.FINEST)) {
logger.finest(this.getName() + ": " + height + "," + width + ": (deleted)");
}
} else {
if (Soar2D.logger.isLoggable(Level.FINEST)) {
logger.finest(this.getName() + ": " + height + "," + width + ": (null)");
}
}
} else {
if (radarCellIDs[width][height] == null) {
radarCellIDs[width][height] = agent.CreateIdWME(m_RadarWME, getCellID(radar[width][height]));
CreateIntWME(radarCellIDs[width][height], Names.kDistanceID, height);
CreateStringWME(radarCellIDs[width][height], Names.kPositionID, getPositionID(width));
if (radar[width][height].player != null) {
radarColors[width][height] = CreateStringWME(radarCellIDs[width][height], Names.kColorID, radar[width][height].player.getColor());
if (Soar2D.logger.isLoggable(Level.FINEST)) {
logger.finest(this.getName() + ": " + height + "," + width + ": " + getCellID(radar[width][height]) + " " + radar[width][height].player.getColor() + " (created)");
}
} else {
if (Soar2D.logger.isLoggable(Level.FINEST)) {
logger.finest(this.getName() + ": " + height + "," + width + ": " + getCellID(radar[width][height]) + " (created)");
}
}
} else {
boolean changed = !radarCellIDs[width][height].GetAttribute().equals(getCellID(radar[width][height]));
// Update if relevant change
if (movedOrRotated || changed) {
DestroyWME(radarCellIDs[width][height]);
radarCellIDs[width][height] = agent.CreateIdWME(m_RadarWME, getCellID(radar[width][height]));
CreateIntWME(radarCellIDs[width][height], Names.kDistanceID, height);
CreateStringWME(radarCellIDs[width][height], Names.kPositionID, getPositionID(width));
if (radar[width][height].player != null) {
radarColors[width][height] = CreateStringWME(radarCellIDs[width][height], Names.kColorID, radar[width][height].player.getColor());
if (Soar2D.logger.isLoggable(Level.FINEST)) {
logger.finest(this.getName() + ": " + height + "," + width + ": " + getCellID(radar[width][height]) + " " + radar[width][height].player.getColor());
}
} else {
if (Soar2D.logger.isLoggable(Level.FINEST)) {
logger.finest(this.getName() + ": " + height + "," + width + ": " + getCellID(radar[width][height]));
}
}
}
}
}
}
}
}
private void clearRadar() {
for (int width = 0; width < Soar2D.config.tConfig.getRadarWidth(); ++width) {
for (int height = 0; height < Soar2D.config.tConfig.getRadarHeight(); ++height) {
radarCellIDs[width][height] = null;
radarColors[width][height] = null;
}
}
}
private String getCellID(RadarCell cell) {
if (cell.player != null) {
return Names.kTankID;
}
if (cell.obstacle) {
return Names.kObstacleID;
}
if (cell.energy) {
return Names.kEnergyID;
}
if (cell.health) {
return Names.kHealthID;
}
if (cell.missiles) {
return Names.kMissilesID;
}
return Names.kOpenID;
}
public String getPositionID(int i) {
switch (i) {
case 0:
return Names.kLeftID;
default:
case 1:
return Names.kCenterID;
case 2:
return Names.kRightID;
}
}
public void shutdown() {
assert agent != null;
if (shutdownCommands != null) {
Iterator<String> iter = shutdownCommands.iterator();
while(iter.hasNext()) {
String command = iter.next();
String result = getName() + ": result: " + agent.ExecuteCommandLine(command, true);
Soar2D.logger.info(getName() + ": shutdown command: " + command);
if (agent.HadError()) {
Soar2D.control.severeError(result);
} else {
Soar2D.logger.info(getName() + ": result: " + result);
}
}
}
clearWMEs();
}
}
| false | true | public void commit(java.awt.Point location) {
int facing = getFacingInt();
String facingString = Direction.stringOf[facing];
World world = Soar2D.simulation.world;
String shieldStatus = shieldsUp ? Names.kOn : Names.kOff;
String blockedForward = ((blocked & Direction.indicators[facing]) > 0) ? Names.kYes : Names.kNo;
String blockedBackward = ((blocked & Direction.indicators[Direction.backwardOf[facing]]) > 0) ? Names.kYes : Names.kNo;
String blockedLeft = ((blocked & Direction.indicators[Direction.leftOf[facing]]) > 0) ? Names.kYes : Names.kNo;
String blockedRight = ((blocked & Direction.indicators[Direction.rightOf[facing]]) > 0) ? Names.kYes : Names.kNo;
String incomingForward = ((incoming & Direction.indicators[facing]) > 0) ? Names.kYes : Names.kNo;
String incomingBackward = ((incoming & Direction.indicators[Direction.backwardOf[facing]]) > 0) ? Names.kYes : Names.kNo;
String incomingLeft = ((incoming & Direction.indicators[Direction.leftOf[facing]]) > 0) ? Names.kYes : Names.kNo;
String incomingRight = ((incoming & Direction.indicators[Direction.rightOf[facing]]) > 0) ? Names.kYes : Names.kNo;
String smellColorString = (smellColor == null) ? Names.kNone : smellColor;
String soundString;
if (sound == facing) {
soundString = Names.kForwardID;
} else if (sound == Direction.backwardOf[facing]) {
soundString = Names.kBackwardID;
} else if (sound == Direction.leftOf[facing]) {
soundString = Names.kLeftID;
} else if (sound == Direction.rightOf[facing]) {
soundString = Names.kRightID;
} else {
soundString = Names.kSilentID;
}
int worldCount = world.getWorldCount();
String radarStatus = radarSwitch ? Names.kOn : Names.kOff;
float oldrandom = random;
do {
random = Simulation.random.nextFloat();
} while (random == oldrandom);
String rwavesForward = (rwaves & facing) > 0 ? Names.kYes : Names.kNo;
String rwavesBackward = (rwaves & Direction.indicators[Direction.backwardOf[facing]]) > 0 ? Names.kYes : Names.kNo;;
String rwavesLeft = (rwaves & Direction.indicators[Direction.leftOf[facing]]) > 0 ? Names.kYes : Names.kNo;
String rwavesRight = (rwaves & Direction.indicators[Direction.rightOf[facing]]) > 0 ? Names.kYes : Names.kNo;
if (Soar2D.logger.isLoggable(Level.FINEST)) {
logger.finest(this.getName() + " input dump: ");
logger.finest(this.getName() + ": x,y: " + location.x + "," + location.y);
logger.finest(this.getName() + ": " + Names.kEnergyRechargerID + ": " + (onEnergyCharger ? Names.kYes : Names.kNo));
logger.finest(this.getName() + ": " + Names.kHealthRechargerID + ": " + (onHealthCharger ? Names.kYes : Names.kNo));
logger.finest(this.getName() + ": " + Names.kDirectionID + ": " + facingString);
logger.finest(this.getName() + ": " + Names.kEnergyID + ": " + energy);
logger.finest(this.getName() + ": " + Names.kHealthID + ": " + health);
logger.finest(this.getName() + ": " + Names.kShieldStatusID + ": " + shieldStatus);
logger.finest(this.getName() + ": blocked (forward): " + blockedForward);
logger.finest(this.getName() + ": blocked (backward): " + blockedBackward);
logger.finest(this.getName() + ": blocked (left): " + blockedLeft);
logger.finest(this.getName() + ": blocked (right): " + blockedRight);
logger.finest(this.getName() + ": " + Names.kCurrentScoreID + ": TODO: dump");
logger.finest(this.getName() + ": incoming (forward): " + incomingForward);
logger.finest(this.getName() + ": incoming (backward): " + incomingBackward);
logger.finest(this.getName() + ": incoming (left): " + incomingLeft);
logger.finest(this.getName() + ": incoming (right): " + incomingRight);
logger.finest(this.getName() + ": smell (color): " + smellColorString);
logger.finest(this.getName() + ": smell (distance): " + smellDistance);
logger.finest(this.getName() + ": " + Names.kSoundID + ": " + soundString);
logger.finest(this.getName() + ": " + Names.kMissilesID + ": " + missiles);
logger.finest(this.getName() + ": " + Names.kMyColorID + ": " + getColor());
logger.finest(this.getName() + ": " + Names.kClockID + ": " + worldCount);
logger.finest(this.getName() + ": " + Names.kRadarStatusID + ": " + radarStatus);
logger.finest(this.getName() + ": " + Names.kRadarDistanceID + ": " + observedPower);
logger.finest(this.getName() + ": " + Names.kRadarSettingID + ": " + radarPower);
logger.finest(this.getName() + ": " + Names.kRandomID + "random: " + random);
logger.finest(this.getName() + ": rwaves (forward): " + rwavesForward);
logger.finest(this.getName() + ": rwaves (backward): " + rwavesBackward);
logger.finest(this.getName() + ": rwaves (left): " + rwavesLeft);
logger.finest(this.getName() + ": rwaves (right): " + rwavesRight);
}
if (m_Reset) {
// location
m_xWME = CreateIntWME(m_InputLink, Names.kXID, location.x);
m_yWME = CreateIntWME(m_InputLink, Names.kYID, location.y);
// charger detection
String energyRecharger = onEnergyCharger ? Names.kYes : Names.kNo;
m_EnergyRechargerWME = CreateStringWME(m_InputLink, Names.kEnergyRechargerID, energyRecharger);
String healthRecharger = onHealthCharger ? Names.kYes : Names.kNo;
m_HealthRechargerWME = CreateStringWME(m_InputLink, Names.kHealthRechargerID, healthRecharger);
// facing
m_DirectionWME = CreateStringWME(m_InputLink, Names.kDirectionID, facingString);
// energy and health status
m_EnergyWME = CreateIntWME(m_InputLink, Names.kEnergyID, energy);
m_HealthWME = CreateIntWME(m_InputLink, Names.kHealthID, health);
// shield status
m_ShieldStatusWME = CreateStringWME(m_InputLink, Names.kShieldStatusID, shieldStatus);
// blocked sensor
m_BlockedWME = agent.CreateIdWME(m_InputLink, Names.kBlockedID);
m_BlockedForwardWME = CreateStringWME(m_BlockedWME, Names.kForwardID, blockedForward);
m_BlockedBackwardWME = CreateStringWME(m_BlockedWME, Names.kBackwardID, blockedBackward);
m_BlockedLeftWME = CreateStringWME(m_BlockedWME, Names.kLeftID, blockedLeft);
m_BlockedRightWME = CreateStringWME(m_BlockedWME, Names.kRightID, blockedRight);
// score status
m_CurrentScoreWME = agent.CreateIdWME(m_InputLink, Names.kCurrentScoreID);
initScoreWMEs();
// incoming sensor
m_IncomingWME = agent.CreateIdWME(m_InputLink, Names.kIncomingID);
m_IncomingBackwardWME = CreateStringWME(m_IncomingWME, Names.kBackwardID, incomingForward);
m_IncomingForwardWME = CreateStringWME(m_IncomingWME, Names.kForwardID, incomingBackward);
m_IncomingLeftWME = CreateStringWME(m_IncomingWME, Names.kLeftID, incomingLeft);
m_IncomingRightWME = CreateStringWME(m_IncomingWME, Names.kRightID, incomingRight);
// smell sensor
m_SmellWME = agent.CreateIdWME(m_InputLink, Names.kSmellID);
m_SmellColorWME = CreateStringWME(m_SmellWME, Names.kColorID, smellColorString);
if (smellColor == null) {
m_SmellDistanceWME = null;
m_SmellDistanceStringWME = CreateStringWME(m_SmellWME, Names.kDistanceID, Names.kNone);
} else {
m_SmellDistanceWME = CreateIntWME(m_SmellWME, Names.kDistanceID, smellDistance);
m_SmellDistanceStringWME = null;
}
// sound sensor
m_SoundWME = CreateStringWME(m_InputLink, Names.kSoundID, soundString);
// missile quantity indicator
m_MissilesWME = CreateIntWME(m_InputLink, Names.kMissilesID, missiles);
// my color
m_MyColorWME = CreateStringWME(m_InputLink, Names.kMyColorID, getColor());
// clock (world count)
m_ClockWME = CreateIntWME(m_InputLink, Names.kClockID, worldCount);
// resurrect sensor
m_ResurrectWME = CreateStringWME(m_InputLink, Names.kResurrectID, Names.kYes);
// radar sensors
m_RadarStatusWME = CreateStringWME(m_InputLink, Names.kRadarStatusID, radarStatus);
if (radarSwitch) {
m_RadarWME = agent.CreateIdWME(m_InputLink, Names.kRadarID);
generateNewRadar();
} else {
m_RadarWME = null;
}
m_RadarDistanceWME = CreateIntWME(m_InputLink, Names.kRadarDistanceID, observedPower);
m_RadarSettingWME = CreateIntWME(m_InputLink, Names.kRadarSettingID, radarPower);
// random indicator
m_RandomWME = CreateFloatWME(m_InputLink, Names.kRandomID, random);
// rwaves sensor
m_RWavesWME = agent.CreateIdWME(m_InputLink, Names.kRWavesID);
m_RWavesForwardWME = CreateStringWME(m_RWavesWME, Names.kForwardID, rwavesBackward);
m_RWavesBackwardWME = CreateStringWME(m_RWavesWME, Names.kBackwardID, rwavesForward);
m_RWavesLeftWME = CreateStringWME(m_RWavesWME, Names.kLeftID, rwavesLeft);
m_RWavesRightWME = CreateStringWME(m_RWavesWME, Names.kRightID, rwavesRight);
} else {
if (moved) {
// location
if (location.x != m_xWME.GetValue()) {
Update(m_xWME, location.x);
}
if (location.y != m_yWME.GetValue()) {
Update(m_yWME, location.y);
}
// charger detection
String energyRecharger = onEnergyCharger ? Names.kYes : Names.kNo;
Update(m_EnergyRechargerWME, energyRecharger);
String healthRecharger = onHealthCharger ? Names.kYes : Names.kNo;
Update(m_HealthRechargerWME, healthRecharger);
}
boolean rotated = !m_DirectionWME.GetValue().equalsIgnoreCase(facingString);
if (rotated) {
// facing
Update(m_DirectionWME, facingString);
}
// charger detection
if (m_EnergyWME.GetValue() != energy) {
Update(m_EnergyWME, energy);
}
if (m_HealthWME.GetValue() != health) {
Update(m_HealthWME, health);
}
// shield status
if (!m_ShieldStatusWME.GetValue().equalsIgnoreCase(shieldStatus)) {
Update(m_ShieldStatusWME, shieldStatus);
}
// blocked sensor
if (attemptedMove || rotated || !m_BlockedForwardWME.GetValue().equalsIgnoreCase(blockedForward)) {
Update(m_BlockedForwardWME, blockedForward);
}
if (attemptedMove || rotated || !m_BlockedBackwardWME.GetValue().equalsIgnoreCase(blockedBackward)) {
Update(m_BlockedBackwardWME, blockedBackward);
}
if (attemptedMove || rotated || !m_BlockedLeftWME.GetValue().equalsIgnoreCase(blockedLeft)) {
Update(m_BlockedLeftWME, blockedLeft);
}
if (attemptedMove || rotated || !m_BlockedRightWME.GetValue().equalsIgnoreCase(blockedRight)) {
Update(m_BlockedRightWME, blockedRight);
}
// scores
if (playersChanged) {
initScoreWMEs();
}
Iterator<Player> playerIter = world.getPlayers().iterator();
while (playerIter.hasNext()) {
Player player = playerIter.next();
if (player.pointsChanged()) {
Update(m_Scores.get(player.getColor()), player.getPoints());
}
}
// incoming sensor
if (!m_IncomingForwardWME.GetValue().equalsIgnoreCase(incomingForward)) {
Update(m_IncomingForwardWME, incomingForward);
}
if (!m_IncomingBackwardWME.GetValue().equalsIgnoreCase(incomingBackward)) {
Update(m_IncomingBackwardWME, incomingBackward);
}
if (!m_IncomingLeftWME.GetValue().equalsIgnoreCase(incomingLeft)) {
Update(m_IncomingLeftWME, incomingLeft);
}
if (!m_IncomingRightWME.GetValue().equalsIgnoreCase(incomingRight)) {
Update(m_IncomingRightWME, incomingRight);
}
// smell sensor
if (!m_SmellColorWME.GetValue().equalsIgnoreCase(smellColorString)) {
Update(m_SmellColorWME, smellColorString);
}
if (smellColor == null) {
if (m_SmellDistanceWME != null) {
DestroyWME(m_SmellDistanceWME);
m_SmellDistanceWME = null;
}
if (m_SmellDistanceStringWME == null) {
m_SmellDistanceStringWME = CreateStringWME(m_SmellWME, Names.kDistanceID, Names.kNone);
}
} else {
if (m_SmellDistanceWME == null) {
m_SmellDistanceWME = CreateIntWME(m_SmellWME, Names.kDistanceID, smellDistance);
} else {
if (m_SmellDistanceWME.GetValue() != smellDistance) {
Update(m_SmellDistanceWME, smellDistance);
}
}
if (m_SmellDistanceStringWME != null) {
DestroyWME(m_SmellDistanceStringWME);
m_SmellDistanceStringWME = null;
}
}
// sound sensor
if (!m_SoundWME.GetValue().equalsIgnoreCase(soundString)) {
Update(m_SoundWME, soundString);
}
// missile quantity indicator
if (m_MissilesWME.GetValue() != missiles) {
Update(m_MissilesWME, missiles);
}
// clock (world count)
Update(m_ClockWME, worldCount);
// resurrect sensor
if (!getResurrect()) {
if (!m_ResurrectWME.GetValue().equalsIgnoreCase(Names.kNo)) {
Update(m_ResurrectWME, Names.kNo);
}
}
// radar sensors
if (!m_RadarStatusWME.GetValue().equalsIgnoreCase(radarStatus)) {
Update(m_RadarStatusWME, radarStatus);
}
if (radarSwitch) {
if (m_RadarWME == null) {
m_RadarWME = agent.CreateIdWME(m_InputLink, Names.kRadarID);
generateNewRadar();
} else {
updateRadar(moved || rotated);
}
} else {
if (m_RadarWME != null) {
clearRadar();
DestroyWME(m_RadarWME);
m_RadarWME = null;
}
}
if (m_RadarDistanceWME.GetValue() != observedPower) {
Update(m_RadarDistanceWME, observedPower);
}
if (m_RadarSettingWME.GetValue() != radarPower) {
Update(m_RadarSettingWME, radarPower);
}
// random indicator
Update(m_RandomWME, random);
// rwaves sensor
if (!m_RWavesForwardWME.GetValue().equalsIgnoreCase(rwavesForward)) {
Update(m_RWavesForwardWME, rwavesForward);
}
if (!m_RWavesBackwardWME.GetValue().equalsIgnoreCase(rwavesBackward)) {
Update(m_RWavesBackwardWME, rwavesBackward);
}
if (!m_RWavesLeftWME.GetValue().equalsIgnoreCase(rwavesLeft)) {
Update(m_RWavesLeftWME, rwavesLeft);
}
if (!m_RWavesRightWME.GetValue().equalsIgnoreCase(rwavesRight)) {
Update(m_RWavesRightWME, rwavesRight);
}
}
m_Reset = false;
if (!agent.Commit()) {
Soar2D.control.severeError("Failed to commit input to Soar agent " + this.getName());
Soar2D.control.stopSimulation();
}
}
| public void commit(java.awt.Point location) {
int facing = getFacingInt();
String facingString = Direction.stringOf[facing];
World world = Soar2D.simulation.world;
String shieldStatus = shieldsUp ? Names.kOn : Names.kOff;
String blockedForward = ((blocked & Direction.indicators[facing]) > 0) ? Names.kYes : Names.kNo;
String blockedBackward = ((blocked & Direction.indicators[Direction.backwardOf[facing]]) > 0) ? Names.kYes : Names.kNo;
String blockedLeft = ((blocked & Direction.indicators[Direction.leftOf[facing]]) > 0) ? Names.kYes : Names.kNo;
String blockedRight = ((blocked & Direction.indicators[Direction.rightOf[facing]]) > 0) ? Names.kYes : Names.kNo;
String incomingForward = ((incoming & Direction.indicators[facing]) > 0) ? Names.kYes : Names.kNo;
String incomingBackward = ((incoming & Direction.indicators[Direction.backwardOf[facing]]) > 0) ? Names.kYes : Names.kNo;
String incomingLeft = ((incoming & Direction.indicators[Direction.leftOf[facing]]) > 0) ? Names.kYes : Names.kNo;
String incomingRight = ((incoming & Direction.indicators[Direction.rightOf[facing]]) > 0) ? Names.kYes : Names.kNo;
String smellColorString = (smellColor == null) ? Names.kNone : smellColor;
String soundString;
if (sound == facing) {
soundString = Names.kForwardID;
} else if (sound == Direction.backwardOf[facing]) {
soundString = Names.kBackwardID;
} else if (sound == Direction.leftOf[facing]) {
soundString = Names.kLeftID;
} else if (sound == Direction.rightOf[facing]) {
soundString = Names.kRightID;
} else {
soundString = Names.kSilentID;
}
int worldCount = world.getWorldCount();
String radarStatus = radarSwitch ? Names.kOn : Names.kOff;
float oldrandom = random;
do {
random = Simulation.random.nextFloat();
} while (random == oldrandom);
String rwavesForward = (rwaves & facing) > 0 ? Names.kYes : Names.kNo;
String rwavesBackward = (rwaves & Direction.indicators[Direction.backwardOf[facing]]) > 0 ? Names.kYes : Names.kNo;;
String rwavesLeft = (rwaves & Direction.indicators[Direction.leftOf[facing]]) > 0 ? Names.kYes : Names.kNo;
String rwavesRight = (rwaves & Direction.indicators[Direction.rightOf[facing]]) > 0 ? Names.kYes : Names.kNo;
if (Soar2D.logger.isLoggable(Level.FINEST)) {
logger.finest(this.getName() + " input dump: ");
logger.finest(this.getName() + ": x,y: " + location.x + "," + location.y);
logger.finest(this.getName() + ": " + Names.kEnergyRechargerID + ": " + (onEnergyCharger ? Names.kYes : Names.kNo));
logger.finest(this.getName() + ": " + Names.kHealthRechargerID + ": " + (onHealthCharger ? Names.kYes : Names.kNo));
logger.finest(this.getName() + ": " + Names.kDirectionID + ": " + facingString);
logger.finest(this.getName() + ": " + Names.kEnergyID + ": " + energy);
logger.finest(this.getName() + ": " + Names.kHealthID + ": " + health);
logger.finest(this.getName() + ": " + Names.kShieldStatusID + ": " + shieldStatus);
logger.finest(this.getName() + ": blocked (forward): " + blockedForward);
logger.finest(this.getName() + ": blocked (backward): " + blockedBackward);
logger.finest(this.getName() + ": blocked (left): " + blockedLeft);
logger.finest(this.getName() + ": blocked (right): " + blockedRight);
logger.finest(this.getName() + ": " + Names.kCurrentScoreID + ": TODO: dump");
logger.finest(this.getName() + ": incoming (forward): " + incomingForward);
logger.finest(this.getName() + ": incoming (backward): " + incomingBackward);
logger.finest(this.getName() + ": incoming (left): " + incomingLeft);
logger.finest(this.getName() + ": incoming (right): " + incomingRight);
logger.finest(this.getName() + ": smell (color): " + smellColorString);
logger.finest(this.getName() + ": smell (distance): " + smellDistance);
logger.finest(this.getName() + ": " + Names.kSoundID + ": " + soundString);
logger.finest(this.getName() + ": " + Names.kMissilesID + ": " + missiles);
logger.finest(this.getName() + ": " + Names.kMyColorID + ": " + getColor());
logger.finest(this.getName() + ": " + Names.kClockID + ": " + worldCount);
logger.finest(this.getName() + ": " + Names.kRadarStatusID + ": " + radarStatus);
logger.finest(this.getName() + ": " + Names.kRadarDistanceID + ": " + observedPower);
logger.finest(this.getName() + ": " + Names.kRadarSettingID + ": " + radarPower);
logger.finest(this.getName() + ": " + Names.kRandomID + "random: " + random);
logger.finest(this.getName() + ": rwaves (forward): " + rwavesForward);
logger.finest(this.getName() + ": rwaves (backward): " + rwavesBackward);
logger.finest(this.getName() + ": rwaves (left): " + rwavesLeft);
logger.finest(this.getName() + ": rwaves (right): " + rwavesRight);
}
if (m_Reset) {
// location
m_xWME = CreateIntWME(m_InputLink, Names.kXID, location.x);
m_yWME = CreateIntWME(m_InputLink, Names.kYID, location.y);
// charger detection
String energyRecharger = onEnergyCharger ? Names.kYes : Names.kNo;
m_EnergyRechargerWME = CreateStringWME(m_InputLink, Names.kEnergyRechargerID, energyRecharger);
String healthRecharger = onHealthCharger ? Names.kYes : Names.kNo;
m_HealthRechargerWME = CreateStringWME(m_InputLink, Names.kHealthRechargerID, healthRecharger);
// facing
m_DirectionWME = CreateStringWME(m_InputLink, Names.kDirectionID, facingString);
// energy and health status
m_EnergyWME = CreateIntWME(m_InputLink, Names.kEnergyID, energy);
m_HealthWME = CreateIntWME(m_InputLink, Names.kHealthID, health);
// shield status
m_ShieldStatusWME = CreateStringWME(m_InputLink, Names.kShieldStatusID, shieldStatus);
// blocked sensor
m_BlockedWME = agent.CreateIdWME(m_InputLink, Names.kBlockedID);
m_BlockedForwardWME = CreateStringWME(m_BlockedWME, Names.kForwardID, blockedForward);
m_BlockedBackwardWME = CreateStringWME(m_BlockedWME, Names.kBackwardID, blockedBackward);
m_BlockedLeftWME = CreateStringWME(m_BlockedWME, Names.kLeftID, blockedLeft);
m_BlockedRightWME = CreateStringWME(m_BlockedWME, Names.kRightID, blockedRight);
// score status
m_CurrentScoreWME = agent.CreateIdWME(m_InputLink, Names.kCurrentScoreID);
initScoreWMEs();
// incoming sensor
m_IncomingWME = agent.CreateIdWME(m_InputLink, Names.kIncomingID);
m_IncomingBackwardWME = CreateStringWME(m_IncomingWME, Names.kBackwardID, incomingForward);
m_IncomingForwardWME = CreateStringWME(m_IncomingWME, Names.kForwardID, incomingBackward);
m_IncomingLeftWME = CreateStringWME(m_IncomingWME, Names.kLeftID, incomingLeft);
m_IncomingRightWME = CreateStringWME(m_IncomingWME, Names.kRightID, incomingRight);
// smell sensor
m_SmellWME = agent.CreateIdWME(m_InputLink, Names.kSmellID);
m_SmellColorWME = CreateStringWME(m_SmellWME, Names.kColorID, smellColorString);
if (smellColor == null) {
m_SmellDistanceWME = null;
m_SmellDistanceStringWME = CreateStringWME(m_SmellWME, Names.kDistanceID, Names.kNone);
} else {
m_SmellDistanceWME = CreateIntWME(m_SmellWME, Names.kDistanceID, smellDistance);
m_SmellDistanceStringWME = null;
}
// sound sensor
m_SoundWME = CreateStringWME(m_InputLink, Names.kSoundID, soundString);
// missile quantity indicator
m_MissilesWME = CreateIntWME(m_InputLink, Names.kMissilesID, missiles);
// my color
m_MyColorWME = CreateStringWME(m_InputLink, Names.kMyColorID, getColor());
// clock (world count)
m_ClockWME = CreateIntWME(m_InputLink, Names.kClockID, worldCount);
// resurrect sensor
m_ResurrectWME = CreateStringWME(m_InputLink, Names.kResurrectID, Names.kYes);
// radar sensors
m_RadarStatusWME = CreateStringWME(m_InputLink, Names.kRadarStatusID, radarStatus);
if (radarSwitch) {
m_RadarWME = agent.CreateIdWME(m_InputLink, Names.kRadarID);
generateNewRadar();
} else {
m_RadarWME = null;
}
m_RadarDistanceWME = CreateIntWME(m_InputLink, Names.kRadarDistanceID, observedPower);
m_RadarSettingWME = CreateIntWME(m_InputLink, Names.kRadarSettingID, radarPower);
// random indicator
m_RandomWME = CreateFloatWME(m_InputLink, Names.kRandomID, random);
// rwaves sensor
m_RWavesWME = agent.CreateIdWME(m_InputLink, Names.kRWavesID);
m_RWavesForwardWME = CreateStringWME(m_RWavesWME, Names.kForwardID, rwavesBackward);
m_RWavesBackwardWME = CreateStringWME(m_RWavesWME, Names.kBackwardID, rwavesForward);
m_RWavesLeftWME = CreateStringWME(m_RWavesWME, Names.kLeftID, rwavesLeft);
m_RWavesRightWME = CreateStringWME(m_RWavesWME, Names.kRightID, rwavesRight);
} else {
if (moved) {
// location
if (location.x != m_xWME.GetValue()) {
Update(m_xWME, location.x);
}
if (location.y != m_yWME.GetValue()) {
Update(m_yWME, location.y);
}
// charger detection
// TODO: consider SetBlinkIfNoChange(false) in constructor
String energyRecharger = onEnergyCharger ? Names.kYes : Names.kNo;
if ( !m_EnergyRechargerWME.GetValue().equals(energyRecharger) ) {
Update(m_EnergyRechargerWME, energyRecharger);
}
String healthRecharger = onHealthCharger ? Names.kYes : Names.kNo;
if ( !m_HealthRechargerWME.GetValue().equals(healthRecharger) ) {
Update(m_HealthRechargerWME, healthRecharger);
}
}
boolean rotated = !m_DirectionWME.GetValue().equalsIgnoreCase(facingString);
if (rotated) {
// facing
Update(m_DirectionWME, facingString);
}
// stats detection
if (m_EnergyWME.GetValue() != energy) {
Update(m_EnergyWME, energy);
}
if (m_HealthWME.GetValue() != health) {
Update(m_HealthWME, health);
}
// shield status
if (!m_ShieldStatusWME.GetValue().equalsIgnoreCase(shieldStatus)) {
Update(m_ShieldStatusWME, shieldStatus);
}
// blocked sensor
if (attemptedMove || rotated || !m_BlockedForwardWME.GetValue().equalsIgnoreCase(blockedForward)) {
Update(m_BlockedForwardWME, blockedForward);
}
if (attemptedMove || rotated || !m_BlockedBackwardWME.GetValue().equalsIgnoreCase(blockedBackward)) {
Update(m_BlockedBackwardWME, blockedBackward);
}
if (attemptedMove || rotated || !m_BlockedLeftWME.GetValue().equalsIgnoreCase(blockedLeft)) {
Update(m_BlockedLeftWME, blockedLeft);
}
if (attemptedMove || rotated || !m_BlockedRightWME.GetValue().equalsIgnoreCase(blockedRight)) {
Update(m_BlockedRightWME, blockedRight);
}
// scores
if (playersChanged) {
initScoreWMEs();
}
Iterator<Player> playerIter = world.getPlayers().iterator();
while (playerIter.hasNext()) {
Player player = playerIter.next();
if (player.pointsChanged()) {
Update(m_Scores.get(player.getColor()), player.getPoints());
}
}
// incoming sensor
if (!m_IncomingForwardWME.GetValue().equalsIgnoreCase(incomingForward)) {
Update(m_IncomingForwardWME, incomingForward);
}
if (!m_IncomingBackwardWME.GetValue().equalsIgnoreCase(incomingBackward)) {
Update(m_IncomingBackwardWME, incomingBackward);
}
if (!m_IncomingLeftWME.GetValue().equalsIgnoreCase(incomingLeft)) {
Update(m_IncomingLeftWME, incomingLeft);
}
if (!m_IncomingRightWME.GetValue().equalsIgnoreCase(incomingRight)) {
Update(m_IncomingRightWME, incomingRight);
}
// smell sensor
if (!m_SmellColorWME.GetValue().equalsIgnoreCase(smellColorString)) {
Update(m_SmellColorWME, smellColorString);
}
if (smellColor == null) {
if (m_SmellDistanceWME != null) {
DestroyWME(m_SmellDistanceWME);
m_SmellDistanceWME = null;
}
if (m_SmellDistanceStringWME == null) {
m_SmellDistanceStringWME = CreateStringWME(m_SmellWME, Names.kDistanceID, Names.kNone);
}
} else {
if (m_SmellDistanceWME == null) {
m_SmellDistanceWME = CreateIntWME(m_SmellWME, Names.kDistanceID, smellDistance);
} else {
if (m_SmellDistanceWME.GetValue() != smellDistance) {
Update(m_SmellDistanceWME, smellDistance);
}
}
if (m_SmellDistanceStringWME != null) {
DestroyWME(m_SmellDistanceStringWME);
m_SmellDistanceStringWME = null;
}
}
// sound sensor
if (!m_SoundWME.GetValue().equalsIgnoreCase(soundString)) {
Update(m_SoundWME, soundString);
}
// missile quantity indicator
if (m_MissilesWME.GetValue() != missiles) {
Update(m_MissilesWME, missiles);
}
// clock (world count)
Update(m_ClockWME, worldCount);
// resurrect sensor
if (!getResurrect()) {
if (!m_ResurrectWME.GetValue().equalsIgnoreCase(Names.kNo)) {
Update(m_ResurrectWME, Names.kNo);
}
}
// radar sensors
if (!m_RadarStatusWME.GetValue().equalsIgnoreCase(radarStatus)) {
Update(m_RadarStatusWME, radarStatus);
}
if (radarSwitch) {
if (m_RadarWME == null) {
m_RadarWME = agent.CreateIdWME(m_InputLink, Names.kRadarID);
generateNewRadar();
} else {
updateRadar(moved || rotated);
}
} else {
if (m_RadarWME != null) {
clearRadar();
DestroyWME(m_RadarWME);
m_RadarWME = null;
}
}
if (m_RadarDistanceWME.GetValue() != observedPower) {
Update(m_RadarDistanceWME, observedPower);
}
if (m_RadarSettingWME.GetValue() != radarPower) {
Update(m_RadarSettingWME, radarPower);
}
// random indicator
Update(m_RandomWME, random);
// rwaves sensor
if (!m_RWavesForwardWME.GetValue().equalsIgnoreCase(rwavesForward)) {
Update(m_RWavesForwardWME, rwavesForward);
}
if (!m_RWavesBackwardWME.GetValue().equalsIgnoreCase(rwavesBackward)) {
Update(m_RWavesBackwardWME, rwavesBackward);
}
if (!m_RWavesLeftWME.GetValue().equalsIgnoreCase(rwavesLeft)) {
Update(m_RWavesLeftWME, rwavesLeft);
}
if (!m_RWavesRightWME.GetValue().equalsIgnoreCase(rwavesRight)) {
Update(m_RWavesRightWME, rwavesRight);
}
}
m_Reset = false;
if (!agent.Commit()) {
Soar2D.control.severeError("Failed to commit input to Soar agent " + this.getName());
Soar2D.control.stopSimulation();
}
}
|
diff --git a/container/catalina/src/share/org/apache/catalina/valves/PersistentValve.java b/container/catalina/src/share/org/apache/catalina/valves/PersistentValve.java
index 4db5117d..d4e823f4 100644
--- a/container/catalina/src/share/org/apache/catalina/valves/PersistentValve.java
+++ b/container/catalina/src/share/org/apache/catalina/valves/PersistentValve.java
@@ -1,213 +1,215 @@
/*
* 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.catalina.valves;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;
import org.apache.catalina.Context;
import org.apache.catalina.Manager;
import org.apache.catalina.Session;
import org.apache.catalina.Store;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.session.PersistentManager;
import org.apache.catalina.util.StringManager;
/**
* Valve that implements per-request session persistence. It is intended to be
* used with non-sticky load-balancers.
* <p>
* <b>USAGE CONSTRAINT</b>: To work correctly it requires a PersistentManager.
* <p>
* <b>USAGE CONSTRAINT</b>: To work correctly it assumes only one request exists
* per session at any one time.
*
* @author Jean-Frederic Clere
* @version $Id$
*/
public class PersistentValve
extends ValveBase {
// ----------------------------------------------------- Instance Variables
/**
* The descriptive information related to this implementation.
*/
private static final String info =
"org.apache.catalina.valves.PersistentValve/1.0";
/**
* The string manager for this package.
*/
private static final StringManager sm =
StringManager.getManager(Constants.Package);
// ------------------------------------------------------------- Properties
/**
* Return descriptive information about this Valve implementation.
*/
public String getInfo() {
return (info);
}
// --------------------------------------------------------- Public Methods
/**
* Select the appropriate child Context to process this request,
* based on the specified request URI. If no matching Context can
* be found, return an appropriate HTTP error.
*
* @param request Request to be processed
* @param response Response to be produced
*
* @exception IOException if an input/output error occurred
* @exception ServletException if a servlet error occurred
*/
public void invoke(Request request, Response response)
throws IOException, ServletException {
// Select the Context to be used for this Request
Context context = request.getContext();
if (context == null) {
response.sendError
(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
sm.getString("standardHost.noContext"));
return;
}
// Bind the context CL to the current thread
Thread.currentThread().setContextClassLoader
(context.getLoader().getClassLoader());
// Update the session last access time for our session (if any)
String sessionId = request.getRequestedSessionId();
Manager manager = context.getManager();
if (sessionId != null && manager != null) {
if (manager instanceof PersistentManager) {
Store store = ((PersistentManager) manager).getStore();
if (store != null) {
Session session = null;
try {
session = store.load(sessionId);
} catch (Exception e) {
container.getLogger().error("deserializeError");
}
if (session != null) {
if (!session.isValid() ||
isSessionStale(session, System.currentTimeMillis())) {
if (container.getLogger().isDebugEnabled())
container.getLogger().debug("session swapped in is invalid or expired");
session.expire();
store.remove(sessionId);
} else {
session.setManager(manager);
// session.setId(sessionId); Only if new ???
manager.add(session);
// ((StandardSession)session).activate();
session.access();
session.endAccess();
}
}
}
}
}
if (container.getLogger().isDebugEnabled())
container.getLogger().debug("sessionId: " + sessionId);
// Ask the next valve to process the request.
getNext().invoke(request, response);
// Read the sessionid after the response.
// HttpSession hsess = hreq.getSession(false);
Session hsess;
try {
hsess = request.getSessionInternal();
} catch (Exception ex) {
hsess = null;
}
String newsessionId = null;
if (hsess!=null)
newsessionId = hsess.getIdInternal();
if (container.getLogger().isDebugEnabled())
container.getLogger().debug("newsessionId: " + newsessionId);
if (newsessionId!=null) {
/* store the session in the store and remove it from the manager */
if (manager instanceof PersistentManager) {
Session session = manager.findSession(newsessionId);
Store store = ((PersistentManager) manager).getStore();
if (store != null && session!=null &&
session.isValid() &&
!isSessionStale(session, System.currentTimeMillis())) {
// ((StandardSession)session).passivate();
store.save(session);
((PersistentManager) manager).removeSuper(session);
session.recycle();
} else {
if (container.getLogger().isDebugEnabled())
container.getLogger().debug("newsessionId store: " + store + " session: " +
- session + " valid: " + session.isValid() +
- " Staled: " +
- isSessionStale(session, System.currentTimeMillis()));
+ session +
+ (session == null ? "" :
+ " valid: " + session.isValid() +
+ " stale: " +
+ isSessionStale(session, System.currentTimeMillis())));
}
} else {
if (container.getLogger().isDebugEnabled())
container.getLogger().debug("newsessionId Manager: " + manager);
}
}
}
/**
* Indicate whether the session has been idle for longer
* than its expiration date as of the supplied time.
*
* FIXME: Probably belongs in the Session class.
*/
protected boolean isSessionStale(Session session, long timeNow) {
int maxInactiveInterval = session.getMaxInactiveInterval();
if (maxInactiveInterval >= 0) {
int timeIdle = // Truncate, do not round up
(int) ((timeNow - session.getLastAccessedTime()) / 1000L);
if (timeIdle >= maxInactiveInterval)
return true;
}
return false;
}
}
| true | true | public void invoke(Request request, Response response)
throws IOException, ServletException {
// Select the Context to be used for this Request
Context context = request.getContext();
if (context == null) {
response.sendError
(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
sm.getString("standardHost.noContext"));
return;
}
// Bind the context CL to the current thread
Thread.currentThread().setContextClassLoader
(context.getLoader().getClassLoader());
// Update the session last access time for our session (if any)
String sessionId = request.getRequestedSessionId();
Manager manager = context.getManager();
if (sessionId != null && manager != null) {
if (manager instanceof PersistentManager) {
Store store = ((PersistentManager) manager).getStore();
if (store != null) {
Session session = null;
try {
session = store.load(sessionId);
} catch (Exception e) {
container.getLogger().error("deserializeError");
}
if (session != null) {
if (!session.isValid() ||
isSessionStale(session, System.currentTimeMillis())) {
if (container.getLogger().isDebugEnabled())
container.getLogger().debug("session swapped in is invalid or expired");
session.expire();
store.remove(sessionId);
} else {
session.setManager(manager);
// session.setId(sessionId); Only if new ???
manager.add(session);
// ((StandardSession)session).activate();
session.access();
session.endAccess();
}
}
}
}
}
if (container.getLogger().isDebugEnabled())
container.getLogger().debug("sessionId: " + sessionId);
// Ask the next valve to process the request.
getNext().invoke(request, response);
// Read the sessionid after the response.
// HttpSession hsess = hreq.getSession(false);
Session hsess;
try {
hsess = request.getSessionInternal();
} catch (Exception ex) {
hsess = null;
}
String newsessionId = null;
if (hsess!=null)
newsessionId = hsess.getIdInternal();
if (container.getLogger().isDebugEnabled())
container.getLogger().debug("newsessionId: " + newsessionId);
if (newsessionId!=null) {
/* store the session in the store and remove it from the manager */
if (manager instanceof PersistentManager) {
Session session = manager.findSession(newsessionId);
Store store = ((PersistentManager) manager).getStore();
if (store != null && session!=null &&
session.isValid() &&
!isSessionStale(session, System.currentTimeMillis())) {
// ((StandardSession)session).passivate();
store.save(session);
((PersistentManager) manager).removeSuper(session);
session.recycle();
} else {
if (container.getLogger().isDebugEnabled())
container.getLogger().debug("newsessionId store: " + store + " session: " +
session + " valid: " + session.isValid() +
" Staled: " +
isSessionStale(session, System.currentTimeMillis()));
}
} else {
if (container.getLogger().isDebugEnabled())
container.getLogger().debug("newsessionId Manager: " + manager);
}
}
}
| public void invoke(Request request, Response response)
throws IOException, ServletException {
// Select the Context to be used for this Request
Context context = request.getContext();
if (context == null) {
response.sendError
(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
sm.getString("standardHost.noContext"));
return;
}
// Bind the context CL to the current thread
Thread.currentThread().setContextClassLoader
(context.getLoader().getClassLoader());
// Update the session last access time for our session (if any)
String sessionId = request.getRequestedSessionId();
Manager manager = context.getManager();
if (sessionId != null && manager != null) {
if (manager instanceof PersistentManager) {
Store store = ((PersistentManager) manager).getStore();
if (store != null) {
Session session = null;
try {
session = store.load(sessionId);
} catch (Exception e) {
container.getLogger().error("deserializeError");
}
if (session != null) {
if (!session.isValid() ||
isSessionStale(session, System.currentTimeMillis())) {
if (container.getLogger().isDebugEnabled())
container.getLogger().debug("session swapped in is invalid or expired");
session.expire();
store.remove(sessionId);
} else {
session.setManager(manager);
// session.setId(sessionId); Only if new ???
manager.add(session);
// ((StandardSession)session).activate();
session.access();
session.endAccess();
}
}
}
}
}
if (container.getLogger().isDebugEnabled())
container.getLogger().debug("sessionId: " + sessionId);
// Ask the next valve to process the request.
getNext().invoke(request, response);
// Read the sessionid after the response.
// HttpSession hsess = hreq.getSession(false);
Session hsess;
try {
hsess = request.getSessionInternal();
} catch (Exception ex) {
hsess = null;
}
String newsessionId = null;
if (hsess!=null)
newsessionId = hsess.getIdInternal();
if (container.getLogger().isDebugEnabled())
container.getLogger().debug("newsessionId: " + newsessionId);
if (newsessionId!=null) {
/* store the session in the store and remove it from the manager */
if (manager instanceof PersistentManager) {
Session session = manager.findSession(newsessionId);
Store store = ((PersistentManager) manager).getStore();
if (store != null && session!=null &&
session.isValid() &&
!isSessionStale(session, System.currentTimeMillis())) {
// ((StandardSession)session).passivate();
store.save(session);
((PersistentManager) manager).removeSuper(session);
session.recycle();
} else {
if (container.getLogger().isDebugEnabled())
container.getLogger().debug("newsessionId store: " + store + " session: " +
session +
(session == null ? "" :
" valid: " + session.isValid() +
" stale: " +
isSessionStale(session, System.currentTimeMillis())));
}
} else {
if (container.getLogger().isDebugEnabled())
container.getLogger().debug("newsessionId Manager: " + manager);
}
}
}
|
diff --git a/app/Global.java b/app/Global.java
index eba1cd1..c29decf 100644
--- a/app/Global.java
+++ b/app/Global.java
@@ -1,133 +1,133 @@
import java.lang.reflect.Method;
import java.util.Arrays;
import models.SecurityRole;
import com.feth.play.module.pa.PlayAuthenticate;
import com.feth.play.module.pa.PlayAuthenticate.Resolver;
import com.feth.play.module.pa.exceptions.AccessDeniedException;
import com.feth.play.module.pa.exceptions.AuthException;
import controllers.routes;
import models.SessionToken;
import play.Application;
import play.GlobalSettings;
import play.mvc.Action;
import play.mvc.Call;
import java.net.UnknownHostException;
import play.Logger;
import com.google.code.morphia.Morphia;
import com.mongodb.Mongo;
import controllers.MorphiaObject;
import play.mvc.Http.Request;
import play.mvc.Result;
import static play.mvc.Results.ok;
public class Global extends GlobalSettings {
public void onStart(Application app) {
super.beforeStart(app);
Logger.debug("** Starting Application **");
try {
- MorphiaObject.mongo = new Mongo("10.172.104.17", 27017);
- //MorphiaObject.mongo = new Mongo("127.0.0.1", 27017);
+ //MorphiaObject.mongo = new Mongo("10.172.104.17", 27017);
+ MorphiaObject.mongo = new Mongo("127.0.0.1", 27017);
} catch (UnknownHostException e) {
e.printStackTrace();
}
MorphiaObject.morphia = new Morphia();
MorphiaObject.datastore = MorphiaObject.morphia.createDatastore(MorphiaObject.mongo, "test");
MorphiaObject.datastore.ensureIndexes();
MorphiaObject.datastore.ensureCaps();
PlayAuthenticate.setResolver(new Resolver() {
@Override
public Call login() {
// Your login page
return routes.Application.index();//return routes.Templates.login();
}
@Override
public Call afterAuth() {
// The user will be redirected to this page after authentication
// if no original URL was saved
return routes.Application.index();
}
@Override
public Call afterLogout() {
return routes.Application.index();//routes.Templates.logout();
}
@Override
public Call auth(final String provider) {
// You can provide your own authentication implementation,
// however the default should be sufficient for most cases
return com.feth.play.module.pa.controllers.routes.Authenticate.authenticate(provider);
}
@Override
public Call askMerge() {
return routes.Account.askMerge();
}
@Override
public Call askLink() {
return routes.Account.askLink();
}
@Override
public Call onException(final AuthException e) {
if (e instanceof AccessDeniedException) {
return routes.Signup.oAuthDenied(((AccessDeniedException) e).getProviderKey());
}
// more custom problem handling here...
return super.onException(e);
}
});
initialData();
}
private void initialData() {
if (SecurityRole.all(SecurityRole.class).size() == 0) {
for (final String roleName : Arrays.asList(controllers.Application.USER_ROLE)) {
final SecurityRole role = new SecurityRole();
role.roleName = roleName;
role.save();
}
}
}
@Override
public Action onRequest(Request request, Method actionMethod) {
if (request.cookie("PLAY_SESSION") == null &&
!actionMethod.getName().equals("doLogin") &&
!actionMethod.getName().equals("doSignup")) {
if (request.getHeader("token") != null) {
return new Action.Simple() {
@Override
public Result call(play.mvc.Http.Context ctx) throws Throwable {
SessionToken st = SessionToken.findByToken(ctx.request().getHeader("token"));
if (st != null && !st.expired()) {
ctx.session().put(PlayAuthenticate.ORIGINAL_URL, ctx.request().uri());
ctx.session().put(PlayAuthenticate.USER_KEY, st.getUserId());
ctx.session().put(PlayAuthenticate.PROVIDER_KEY, st.getProviderId());
ctx.session().put(PlayAuthenticate.EXPIRES_KEY, Long.toString(st.getExpires().getTime()));
ctx.session().put(PlayAuthenticate.SESSION_ID_KEY, st.getToken());
return delegate.call(ctx);
}
return unauthorized("Unauthorized operation");
}
};
}
return new Action.Simple() {
@Override
public Result call(play.mvc.Http.Context ctx) throws Throwable {
return unauthorized("Unauthorized operation");
}
};
}
return super.onRequest(request, actionMethod);
}
}
| true | true | public void onStart(Application app) {
super.beforeStart(app);
Logger.debug("** Starting Application **");
try {
MorphiaObject.mongo = new Mongo("10.172.104.17", 27017);
//MorphiaObject.mongo = new Mongo("127.0.0.1", 27017);
} catch (UnknownHostException e) {
e.printStackTrace();
}
MorphiaObject.morphia = new Morphia();
MorphiaObject.datastore = MorphiaObject.morphia.createDatastore(MorphiaObject.mongo, "test");
MorphiaObject.datastore.ensureIndexes();
MorphiaObject.datastore.ensureCaps();
PlayAuthenticate.setResolver(new Resolver() {
@Override
public Call login() {
// Your login page
return routes.Application.index();//return routes.Templates.login();
}
@Override
public Call afterAuth() {
// The user will be redirected to this page after authentication
// if no original URL was saved
return routes.Application.index();
}
@Override
public Call afterLogout() {
return routes.Application.index();//routes.Templates.logout();
}
@Override
public Call auth(final String provider) {
// You can provide your own authentication implementation,
// however the default should be sufficient for most cases
return com.feth.play.module.pa.controllers.routes.Authenticate.authenticate(provider);
}
@Override
public Call askMerge() {
return routes.Account.askMerge();
}
@Override
public Call askLink() {
return routes.Account.askLink();
}
@Override
public Call onException(final AuthException e) {
if (e instanceof AccessDeniedException) {
return routes.Signup.oAuthDenied(((AccessDeniedException) e).getProviderKey());
}
// more custom problem handling here...
return super.onException(e);
}
});
initialData();
}
| public void onStart(Application app) {
super.beforeStart(app);
Logger.debug("** Starting Application **");
try {
//MorphiaObject.mongo = new Mongo("10.172.104.17", 27017);
MorphiaObject.mongo = new Mongo("127.0.0.1", 27017);
} catch (UnknownHostException e) {
e.printStackTrace();
}
MorphiaObject.morphia = new Morphia();
MorphiaObject.datastore = MorphiaObject.morphia.createDatastore(MorphiaObject.mongo, "test");
MorphiaObject.datastore.ensureIndexes();
MorphiaObject.datastore.ensureCaps();
PlayAuthenticate.setResolver(new Resolver() {
@Override
public Call login() {
// Your login page
return routes.Application.index();//return routes.Templates.login();
}
@Override
public Call afterAuth() {
// The user will be redirected to this page after authentication
// if no original URL was saved
return routes.Application.index();
}
@Override
public Call afterLogout() {
return routes.Application.index();//routes.Templates.logout();
}
@Override
public Call auth(final String provider) {
// You can provide your own authentication implementation,
// however the default should be sufficient for most cases
return com.feth.play.module.pa.controllers.routes.Authenticate.authenticate(provider);
}
@Override
public Call askMerge() {
return routes.Account.askMerge();
}
@Override
public Call askLink() {
return routes.Account.askLink();
}
@Override
public Call onException(final AuthException e) {
if (e instanceof AccessDeniedException) {
return routes.Signup.oAuthDenied(((AccessDeniedException) e).getProviderKey());
}
// more custom problem handling here...
return super.onException(e);
}
});
initialData();
}
|
diff --git a/app/models/Notification.java b/app/models/Notification.java
index 92933c0..68b03e0 100644
--- a/app/models/Notification.java
+++ b/app/models/Notification.java
@@ -1,196 +1,195 @@
package models;
import play.data.validation.MaxSize;
import play.data.validation.Required;
import play.db.jpa.JPA;
import play.db.jpa.Model;
import utils.Utils;
import javax.persistence.*;
import java.util.*;
/**
* Created by IntelliJ IDEA.
* User: sheldon
* Date: 7/6/12
* Time: 10:36 AM
* To change this template use File | Settings | File Templates.
*/
@Entity
@Table(name="notification")
public class Notification extends Model {
@Required
@MaxSize(500)
@Column(name = "message", nullable = false)
public String message;
@Required
@ManyToOne
@JoinColumn(name="recipient_id", nullable = false)
public User recipient;
@Temporal(TemporalType.TIMESTAMP)
@Column(name = "date_created", nullable = true)
public Date dateCreated;
@Column(name = "goto_url", nullable = true)
public String gotoUrl;
@Enumerated(EnumType.STRING)
@Column(name = "notification_type", nullable = false)
public NotificationType notificationType = null;
public Notification() {
dateCreated = new Date();
}
/**
* create notifications on list change
* @param notificationType
* @param toDoList
* @param initiator
* @param oldListNameOnRename
* @return
*/
public static List<Notification> createOnListAction(NotificationType notificationType,
ToDoList toDoList, User initiator, String oldListNameOnRename) {
// gets all the subscribers, except the user who initiate the notification action
List<User> users = null;
if (NotificationType.ADD_LIST.equals(notificationType)) {
users = JPA.em()
.createQuery("select p.user from Participation p where p.project=:project and p.user<>:user")
.setParameter("project", toDoList.project)
.setParameter("user", initiator)
.getResultList();
} else {
users = JPA.em()
.createQuery("select u from User u left join u.watchedToDoLists l where l=:toDoList and u<>:user")
.setParameter("toDoList", toDoList)
.setParameter("user", initiator)
.getResultList();
}
if (users != null && users.size() > 0) {
Map<String, String> messageMap = new HashMap<String, String>();
messageMap.put("s1", initiator.fullName);
messageMap.put("message", "notification_" + notificationType.name().toLowerCase());
- String message = Utils.mapToJson(messageMap);
switch (notificationType) {
case RENAME_LIST:
messageMap.put("s2", oldListNameOnRename);
messageMap.put("s3", toDoList.name);
- message = initiator.fullName + " renamed list \"" + oldListNameOnRename + "\" to \"" + toDoList.name + "\".";
break;
default:
messageMap.put("s2", toDoList.name);
messageMap.put("s3", toDoList.project.title);
break;
}
+ String message = Utils.mapToJson(messageMap);
return createNotifications(notificationType, users, message);
} else {
return null;
}
}
/**
* create notifications on task change
* @param notificationType
* @param toDo
* @param initiator
* @param oldToDoList
* @return
*/
public static List<Notification> createOnTaskAction(NotificationType notificationType,
ToDo toDo, User initiator, ToDoList oldToDoList) {
// gets all the subscribers, except the user who initiate the notification action
List<User> users = JPA.em()
.createQuery("select u from User u left join u.watchedToDoLists l where l=:toDoList and u<>:user")
.setParameter("toDoList", toDo.toDoList)
.setParameter("user", initiator)
.getResultList();
if (users != null && users.size() > 0) {
Map<String, String> messageMap = new HashMap<String, String>();
messageMap.put("s1", initiator.fullName);
messageMap.put("s2", toDo.title);
messageMap.put("s3", toDo.toDoList.name);
messageMap.put("message", "notification_" + notificationType.name().toLowerCase());
String message = Utils.mapToJson(messageMap);
return createNotifications(notificationType, users, message);
} else {
return null;
}
}
/**
* creates notification on join by invite
* @param invitee
* @param inviter
* @return
*/
public static List<Notification> createOnJoinByInvite(User invitee, User inviter) {
NotificationType notificationType = NotificationType.JOIN_BY_INVITE;
Map<String, String> messageMap = new HashMap<String, String>();
messageMap.put("s1", invitee.fullName);
messageMap.put("message", "notification_" + notificationType.name().toLowerCase());
String message = Utils.mapToJson(messageMap);
List<User> recipients = new ArrayList<User>();
recipients.add(inviter);
return createNotifications(notificationType, recipients, message);
}
/**
* creates notification on join by invite
* @param inviter
* @param project
* @return
*/
public static List<Notification> createOnInvite(User invitee, User inviter,
Project project, String activationUrl) {
NotificationType notificationType = NotificationType.INVITE_IN_PROJECT;
Map<String, String> messageMap = new HashMap<String, String>();
messageMap.put("s1", inviter.fullName);
messageMap.put("s2", project.title);
messageMap.put("message", "notification_" + notificationType.name().toLowerCase());
String message = Utils.mapToJson(messageMap);
List<User> recipients = new ArrayList<User>();
recipients.add(invitee);
return createNotifications(notificationType, recipients, message, activationUrl);
}
/**
* creates one type of notifications for a list of recipients
* @param notificationType
* @param recipients
* @param message
* @return
*/
private static List<Notification> createNotifications(NotificationType notificationType,
List<User> recipients, String message) {
return createNotifications(notificationType,recipients, message, null);
}
/**
* creates on type of notifications for a list of recipients
* @param notificationType
* @param recipients
* @param message
* @param gotoUrl
* @return
*/
private static List<Notification> createNotifications(NotificationType notificationType,
List<User> recipients, String message,
String gotoUrl) {
List<Notification> notifications = new ArrayList<Notification> ();
for (User recipient : recipients) {
Notification notification = new Notification();
notification.message = message;
notification.notificationType = notificationType;
notification.recipient = recipient;
notification.gotoUrl = gotoUrl;
notifications.add(notification);
}
return notifications;
}
}
| false | true | public static List<Notification> createOnListAction(NotificationType notificationType,
ToDoList toDoList, User initiator, String oldListNameOnRename) {
// gets all the subscribers, except the user who initiate the notification action
List<User> users = null;
if (NotificationType.ADD_LIST.equals(notificationType)) {
users = JPA.em()
.createQuery("select p.user from Participation p where p.project=:project and p.user<>:user")
.setParameter("project", toDoList.project)
.setParameter("user", initiator)
.getResultList();
} else {
users = JPA.em()
.createQuery("select u from User u left join u.watchedToDoLists l where l=:toDoList and u<>:user")
.setParameter("toDoList", toDoList)
.setParameter("user", initiator)
.getResultList();
}
if (users != null && users.size() > 0) {
Map<String, String> messageMap = new HashMap<String, String>();
messageMap.put("s1", initiator.fullName);
messageMap.put("message", "notification_" + notificationType.name().toLowerCase());
String message = Utils.mapToJson(messageMap);
switch (notificationType) {
case RENAME_LIST:
messageMap.put("s2", oldListNameOnRename);
messageMap.put("s3", toDoList.name);
message = initiator.fullName + " renamed list \"" + oldListNameOnRename + "\" to \"" + toDoList.name + "\".";
break;
default:
messageMap.put("s2", toDoList.name);
messageMap.put("s3", toDoList.project.title);
break;
}
return createNotifications(notificationType, users, message);
} else {
return null;
}
}
| public static List<Notification> createOnListAction(NotificationType notificationType,
ToDoList toDoList, User initiator, String oldListNameOnRename) {
// gets all the subscribers, except the user who initiate the notification action
List<User> users = null;
if (NotificationType.ADD_LIST.equals(notificationType)) {
users = JPA.em()
.createQuery("select p.user from Participation p where p.project=:project and p.user<>:user")
.setParameter("project", toDoList.project)
.setParameter("user", initiator)
.getResultList();
} else {
users = JPA.em()
.createQuery("select u from User u left join u.watchedToDoLists l where l=:toDoList and u<>:user")
.setParameter("toDoList", toDoList)
.setParameter("user", initiator)
.getResultList();
}
if (users != null && users.size() > 0) {
Map<String, String> messageMap = new HashMap<String, String>();
messageMap.put("s1", initiator.fullName);
messageMap.put("message", "notification_" + notificationType.name().toLowerCase());
switch (notificationType) {
case RENAME_LIST:
messageMap.put("s2", oldListNameOnRename);
messageMap.put("s3", toDoList.name);
break;
default:
messageMap.put("s2", toDoList.name);
messageMap.put("s3", toDoList.project.title);
break;
}
String message = Utils.mapToJson(messageMap);
return createNotifications(notificationType, users, message);
} else {
return null;
}
}
|
diff --git a/src/main/java/org/atlasapi/feeds/radioplayer/RadioPlayerHealthController.java b/src/main/java/org/atlasapi/feeds/radioplayer/RadioPlayerHealthController.java
index 550ba167..c7b2c7c2 100644
--- a/src/main/java/org/atlasapi/feeds/radioplayer/RadioPlayerHealthController.java
+++ b/src/main/java/org/atlasapi/feeds/radioplayer/RadioPlayerHealthController.java
@@ -1,82 +1,82 @@
package org.atlasapi.feeds.radioplayer;
import static com.google.common.base.Preconditions.checkNotNull;
import java.io.IOException;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import com.google.common.base.Function;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.common.collect.Iterables;
import com.metabroadcast.common.http.HttpStatusCode;
import com.metabroadcast.common.media.MimeType;
import com.metabroadcast.common.security.HttpBasicAuthChecker;
import com.metabroadcast.common.security.UsernameAndPassword;
import com.metabroadcast.common.webapp.health.HealthController;
@Controller
public class RadioPlayerHealthController {
private final HealthController main;
private final Map<String, Iterable<String>> slugs;
private final HttpBasicAuthChecker checker;
private final Iterable<String> serviceIds;
public RadioPlayerHealthController(HealthController main, Iterable<String> serviceIds, String password) {
if (!Strings.isNullOrEmpty(password)) {
this.checker = new HttpBasicAuthChecker(ImmutableList.of(new UsernameAndPassword("bbc", password)));
} else {
this.checker = null;
}
this.main = checkNotNull(main);
this.serviceIds = checkNotNull(serviceIds);
slugs = createSlugMap();
}
private Map<String, Iterable<String>> createSlugMap() {
Builder<String, Iterable<String>> slugMap = ImmutableMap.builder();
for (String serviceId : serviceIds) {
slugMap.put(serviceId, slugsFor(serviceId));
}
return slugMap.build();
}
private Iterable<String> slugsFor(final String serviceId) {
return Iterables.concat(ImmutableList.of("ukrp-connect-"+serviceId), Iterables.transform(RadioPlayerServices.services, new Function<RadioPlayerService, String>() {
@Override
public String apply(RadioPlayerService service) {
return String.format("ukrp-%s-%s", serviceId, service.getName());
}
}));
}
@RequestMapping("feeds/ukradioplayer/health/{serviceId}")
public String radioplayerHealth(HttpServletRequest request, HttpServletResponse response, @PathVariable("serviceId") String sid) throws IOException {
if (checker == null) {
response.setContentType(MimeType.TEXT_PLAIN.toString());
response.getOutputStream().print("No password set up, health page cannot be viewed");
return null;
}
boolean allowed = checker.check(request);
if (allowed) {
if(slugs.containsKey(sid)) {
- return main.showHealthPageForSlugs(response, slugs.get(sid));
+ return main.showHealthPageForSlugs(response, slugs.get(sid), false);
} else {
response.sendError(HttpStatusCode.NOT_FOUND.code());
}
}
HttpBasicAuthChecker.requestAuth(response, "Heath Page");
return null;
}
}
| true | true | public String radioplayerHealth(HttpServletRequest request, HttpServletResponse response, @PathVariable("serviceId") String sid) throws IOException {
if (checker == null) {
response.setContentType(MimeType.TEXT_PLAIN.toString());
response.getOutputStream().print("No password set up, health page cannot be viewed");
return null;
}
boolean allowed = checker.check(request);
if (allowed) {
if(slugs.containsKey(sid)) {
return main.showHealthPageForSlugs(response, slugs.get(sid));
} else {
response.sendError(HttpStatusCode.NOT_FOUND.code());
}
}
HttpBasicAuthChecker.requestAuth(response, "Heath Page");
return null;
}
| public String radioplayerHealth(HttpServletRequest request, HttpServletResponse response, @PathVariable("serviceId") String sid) throws IOException {
if (checker == null) {
response.setContentType(MimeType.TEXT_PLAIN.toString());
response.getOutputStream().print("No password set up, health page cannot be viewed");
return null;
}
boolean allowed = checker.check(request);
if (allowed) {
if(slugs.containsKey(sid)) {
return main.showHealthPageForSlugs(response, slugs.get(sid), false);
} else {
response.sendError(HttpStatusCode.NOT_FOUND.code());
}
}
HttpBasicAuthChecker.requestAuth(response, "Heath Page");
return null;
}
|
diff --git a/src/com/tw/thoughtblogs/BlogDetailActivity.java b/src/com/tw/thoughtblogs/BlogDetailActivity.java
index e4c5e37..95df6ce 100644
--- a/src/com/tw/thoughtblogs/BlogDetailActivity.java
+++ b/src/com/tw/thoughtblogs/BlogDetailActivity.java
@@ -1,38 +1,38 @@
package com.tw.thoughtblogs;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.webkit.WebView;
import com.tw.thoughtblogs.model.BlogData;
public class BlogDetailActivity extends Activity {
private BlogData blogData;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.blog_detail);
Intent launchingIntent = getIntent();
String blogID = launchingIntent.getData().toString();
String details = getBlogData().loadDescription(blogID);
details = details.replaceAll("<", "<");
details = details.replaceAll(">", ">");
details = details.replaceAll("#", "%23");
details = details.replaceAll("%", "%25");
details = details.replaceAll("\\?", "%27");
- details = "<html><body>" + details + "</body></html>";
+ details = "<html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-16le\"><body>" + details + "</body></html>";
WebView viewer = (WebView) findViewById(R.id.blogDetailView);
viewer.loadData(details, "text/html", "utf-8");
}
private BlogData getBlogData() {
if (blogData == null)
blogData = new BlogData(this);
return blogData;
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.blog_detail);
Intent launchingIntent = getIntent();
String blogID = launchingIntent.getData().toString();
String details = getBlogData().loadDescription(blogID);
details = details.replaceAll("<", "<");
details = details.replaceAll(">", ">");
details = details.replaceAll("#", "%23");
details = details.replaceAll("%", "%25");
details = details.replaceAll("\\?", "%27");
details = "<html><body>" + details + "</body></html>";
WebView viewer = (WebView) findViewById(R.id.blogDetailView);
viewer.loadData(details, "text/html", "utf-8");
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.blog_detail);
Intent launchingIntent = getIntent();
String blogID = launchingIntent.getData().toString();
String details = getBlogData().loadDescription(blogID);
details = details.replaceAll("<", "<");
details = details.replaceAll(">", ">");
details = details.replaceAll("#", "%23");
details = details.replaceAll("%", "%25");
details = details.replaceAll("\\?", "%27");
details = "<html><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-16le\"><body>" + details + "</body></html>";
WebView viewer = (WebView) findViewById(R.id.blogDetailView);
viewer.loadData(details, "text/html", "utf-8");
}
|
diff --git a/src/com/mattfeury/saucillator/dev/android/tabs/TimbreTab.java b/src/com/mattfeury/saucillator/dev/android/tabs/TimbreTab.java
index 40180ee..25d64da 100644
--- a/src/com/mattfeury/saucillator/dev/android/tabs/TimbreTab.java
+++ b/src/com/mattfeury/saucillator/dev/android/tabs/TimbreTab.java
@@ -1,210 +1,211 @@
package com.mattfeury.saucillator.dev.android.tabs;
import java.util.ArrayList;
import java.util.LinkedList;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import com.mattfeury.saucillator.dev.android.instruments.ComplexOsc;
import com.mattfeury.saucillator.dev.android.instruments.Oscillator;
import com.mattfeury.saucillator.dev.android.sound.AudioEngine;
import com.mattfeury.saucillator.dev.android.sound.OscillatorUpdater;
import com.mattfeury.saucillator.dev.android.templates.Button;
import com.mattfeury.saucillator.dev.android.templates.ButtonBuilder;
import com.mattfeury.saucillator.dev.android.templates.Handler;
import com.mattfeury.saucillator.dev.android.templates.KnobButton;
import com.mattfeury.saucillator.dev.android.templates.PickerButton;
import com.mattfeury.saucillator.dev.android.templates.RectButton;
import com.mattfeury.saucillator.dev.android.templates.RowPanel;
import com.mattfeury.saucillator.dev.android.templates.Table;
import com.mattfeury.saucillator.dev.android.utilities.Utilities;
import com.mattfeury.saucillator.dev.android.services.InstrumentService;
import com.mattfeury.saucillator.dev.android.services.VibratorService;
import com.mattfeury.saucillator.dev.android.services.ViewService;
public class TimbreTab extends Tab {
private static final int BORDER_SIZE = 5, MARGIN_SIZE = 8, TEXT_SIZE = 18;
private TimbreTable timbreTable;
private static final float HARMONIC_MIN = 1, HARMONIC_MAX = 5, PHASE_MIN = 0, PHASE_MAX = 360;
private Paint textPaint = new Paint();
public TimbreTab(final AudioEngine engine) {
super("Timbre", engine);
textPaint.setARGB(255, 255, 120, 120);
textPaint.setTextSize(24);
textPaint.setFakeBoldText(true);
textPaint.setTextAlign(Align.CENTER);
final RectButton toggleButton = new RectButton("Add") {
@Override
public void handle(Object o) {
super.handle(o);
VibratorService.vibrate();
}
};
//toggleButton.setBorder(BORDER_SIZE);
//toggleButton.setMargin(MARGIN_SIZE);
toggleButton.setTextSize(TEXT_SIZE);
toggleButton.setClear(false);
toggleButton.addHandler(new Handler<Object>() {
public void handle(Object data) {
engine.updateOscillatorProperty(new OscillatorUpdater() {
public void update(ComplexOsc osc) {
Oscillator newTimbre = InstrumentService.getOscillatorForTimbre("Sine");
osc.fill(newTimbre);
}
});
timbreTable.fill(AudioEngine.currentOscillator);
}
});
timbreTable = new TimbreTable();
timbreTable.setRowspan(8);
timbreTable.setBorder(0);
timbreTable.setClear(true);
timbreTable.fill(AudioEngine.getCurrentOscillator());
panel.addChild(
toggleButton,
timbreTable
);
}
public TimbreRow makeTimbreRowFor(Oscillator timbre, int index, String[] disallowedTypes) {
TimbreRow row = new TimbreRow(timbre, index, disallowedTypes);
return row;
}
public class TimbreTable extends Table {
public TimbreTable() {
super("Timbre");
}
public void fill(ComplexOsc osc) {
this.removeChildren();
LinkedList<Oscillator> timbres = osc.getComponents();
// TODO should this check to see if it's basic or internal? SingingSaw is internal but not basic...
String[] disallowed = osc.isInternal() ? new String[0] : new String[]{ osc.getName() };
int i = 0;
for (Oscillator timbre : timbres) {
TimbreRow row = makeTimbreRowFor(timbre, i++, disallowed);
if (i == 1) {
row.setClear(false);
}
this.addChild(row);
}
}
}
private class TimbreRow extends Table {
public TimbreRow(final Oscillator timbre, final int timbreIndex, String[] disallowedTypes) {
super("timbre-row-" + timbre.getName());
this.setClear(true);
this.setBorder(0);
ArrayList<String> timbres = InstrumentService.getAllInstrumentNames();
for (String disallowedType : disallowedTypes) {
int index = timbres.lastIndexOf(disallowedType);
if (index > -1)
timbres.remove(index);
}
/**
* We can't just update properties on this Oscillator object because it likely comes from AudioEngine's currentOscillator
* which is an oscillator that is never heard, but is an in-memory version of the current oscillator. It is used for creating
* new oscillators at runtime. Because of this, we use AudioEngine's updateOscillatorProperty which will update the
* currentOscillator but also update any existing (currently playing) oscillators.
*/
String name = timbre.getName();
PickerButton<String> typePicker = new PickerButton<String>(name, timbres.toArray(new String[timbres.size()]), name);
typePicker.setColspan(2);
typePicker.addHandler(new Handler<String>() {
public void handle(final String type) {
engine.updateOscillatorProperty(new OscillatorUpdater() {
public void update(ComplexOsc osc) {
+ Oscillator timbre = osc.getComponent(timbreIndex);
Oscillator newTimbre = InstrumentService.getOscillatorForTimbre(type);
newTimbre.setAmplitude(timbre.getAmplitude());
newTimbre.setHarmonic(timbre.getHarmonic());
newTimbre.setPhase(timbre.getPhase());
osc.removeComponent(timbreIndex);
osc.insertComponent(timbreIndex, newTimbre);
}
});
}
});
float harmonic = Utilities.unscale(timbre.getHarmonic(), HARMONIC_MIN, HARMONIC_MAX);
KnobButton harmonicKnob = new KnobButton("Harmonic", harmonic);
harmonicKnob.addHandler(new Handler<Float>() {
public void handle(final Float progress) {
engine.updateOscillatorProperty(new OscillatorUpdater() {
public void update(ComplexOsc osc) {
Oscillator timbre = osc.getComponent(timbreIndex);
timbre.setHarmonic(Utilities.scale(progress, (int)HARMONIC_MIN, (int)HARMONIC_MAX));
}
});
}
});
KnobButton amplitudeKnob = new KnobButton("Amplitude", timbre.getAmplitude());
amplitudeKnob.addHandler(new Handler<Float>() {
public void handle(final Float progress) {
engine.updateOscillatorProperty(new OscillatorUpdater() {
public void update(ComplexOsc osc) {
Oscillator timbre = osc.getComponent(timbreIndex);
timbre.setAmplitude(progress);
}
});
}
});
float phase = Utilities.unscale(timbre.getPhase(), PHASE_MIN, PHASE_MAX);
KnobButton phaseKnob = new KnobButton("Phase", phase);
phaseKnob.addHandler(new Handler<Float>() {
public void handle(final Float progress) {
engine.updateOscillatorProperty(new OscillatorUpdater() {
public void update(ComplexOsc osc) {
Oscillator timbre = osc.getComponent(timbreIndex);
timbre.setPhase(Utilities.scale(progress, (int)PHASE_MIN, (int)PHASE_MAX));
}
});
}
});
RectButton delete = new RectButton("X");
delete.setTextPaint(textPaint);
delete.addHandler(new Handler<Object>() {
public void handle(Object o) {
VibratorService.vibrate();
engine.updateOscillatorProperty(new OscillatorUpdater() {
public void update(ComplexOsc osc) {
osc.removeComponent(timbreIndex);
}
});
// Do we have to refill here? We could potentially decrement the row indexes above this one
timbreTable.fill(AudioEngine.currentOscillator);
}
});
delete.setMargin(30);
this.addChild(typePicker, harmonicKnob, amplitudeKnob, phaseKnob, delete);
}
}
}
| true | true | public TimbreRow(final Oscillator timbre, final int timbreIndex, String[] disallowedTypes) {
super("timbre-row-" + timbre.getName());
this.setClear(true);
this.setBorder(0);
ArrayList<String> timbres = InstrumentService.getAllInstrumentNames();
for (String disallowedType : disallowedTypes) {
int index = timbres.lastIndexOf(disallowedType);
if (index > -1)
timbres.remove(index);
}
/**
* We can't just update properties on this Oscillator object because it likely comes from AudioEngine's currentOscillator
* which is an oscillator that is never heard, but is an in-memory version of the current oscillator. It is used for creating
* new oscillators at runtime. Because of this, we use AudioEngine's updateOscillatorProperty which will update the
* currentOscillator but also update any existing (currently playing) oscillators.
*/
String name = timbre.getName();
PickerButton<String> typePicker = new PickerButton<String>(name, timbres.toArray(new String[timbres.size()]), name);
typePicker.setColspan(2);
typePicker.addHandler(new Handler<String>() {
public void handle(final String type) {
engine.updateOscillatorProperty(new OscillatorUpdater() {
public void update(ComplexOsc osc) {
Oscillator newTimbre = InstrumentService.getOscillatorForTimbre(type);
newTimbre.setAmplitude(timbre.getAmplitude());
newTimbre.setHarmonic(timbre.getHarmonic());
newTimbre.setPhase(timbre.getPhase());
osc.removeComponent(timbreIndex);
osc.insertComponent(timbreIndex, newTimbre);
}
});
}
});
float harmonic = Utilities.unscale(timbre.getHarmonic(), HARMONIC_MIN, HARMONIC_MAX);
KnobButton harmonicKnob = new KnobButton("Harmonic", harmonic);
harmonicKnob.addHandler(new Handler<Float>() {
public void handle(final Float progress) {
engine.updateOscillatorProperty(new OscillatorUpdater() {
public void update(ComplexOsc osc) {
Oscillator timbre = osc.getComponent(timbreIndex);
timbre.setHarmonic(Utilities.scale(progress, (int)HARMONIC_MIN, (int)HARMONIC_MAX));
}
});
}
});
KnobButton amplitudeKnob = new KnobButton("Amplitude", timbre.getAmplitude());
amplitudeKnob.addHandler(new Handler<Float>() {
public void handle(final Float progress) {
engine.updateOscillatorProperty(new OscillatorUpdater() {
public void update(ComplexOsc osc) {
Oscillator timbre = osc.getComponent(timbreIndex);
timbre.setAmplitude(progress);
}
});
}
});
float phase = Utilities.unscale(timbre.getPhase(), PHASE_MIN, PHASE_MAX);
KnobButton phaseKnob = new KnobButton("Phase", phase);
phaseKnob.addHandler(new Handler<Float>() {
public void handle(final Float progress) {
engine.updateOscillatorProperty(new OscillatorUpdater() {
public void update(ComplexOsc osc) {
Oscillator timbre = osc.getComponent(timbreIndex);
timbre.setPhase(Utilities.scale(progress, (int)PHASE_MIN, (int)PHASE_MAX));
}
});
}
});
RectButton delete = new RectButton("X");
delete.setTextPaint(textPaint);
delete.addHandler(new Handler<Object>() {
public void handle(Object o) {
VibratorService.vibrate();
engine.updateOscillatorProperty(new OscillatorUpdater() {
public void update(ComplexOsc osc) {
osc.removeComponent(timbreIndex);
}
});
// Do we have to refill here? We could potentially decrement the row indexes above this one
timbreTable.fill(AudioEngine.currentOscillator);
}
});
delete.setMargin(30);
this.addChild(typePicker, harmonicKnob, amplitudeKnob, phaseKnob, delete);
}
| public TimbreRow(final Oscillator timbre, final int timbreIndex, String[] disallowedTypes) {
super("timbre-row-" + timbre.getName());
this.setClear(true);
this.setBorder(0);
ArrayList<String> timbres = InstrumentService.getAllInstrumentNames();
for (String disallowedType : disallowedTypes) {
int index = timbres.lastIndexOf(disallowedType);
if (index > -1)
timbres.remove(index);
}
/**
* We can't just update properties on this Oscillator object because it likely comes from AudioEngine's currentOscillator
* which is an oscillator that is never heard, but is an in-memory version of the current oscillator. It is used for creating
* new oscillators at runtime. Because of this, we use AudioEngine's updateOscillatorProperty which will update the
* currentOscillator but also update any existing (currently playing) oscillators.
*/
String name = timbre.getName();
PickerButton<String> typePicker = new PickerButton<String>(name, timbres.toArray(new String[timbres.size()]), name);
typePicker.setColspan(2);
typePicker.addHandler(new Handler<String>() {
public void handle(final String type) {
engine.updateOscillatorProperty(new OscillatorUpdater() {
public void update(ComplexOsc osc) {
Oscillator timbre = osc.getComponent(timbreIndex);
Oscillator newTimbre = InstrumentService.getOscillatorForTimbre(type);
newTimbre.setAmplitude(timbre.getAmplitude());
newTimbre.setHarmonic(timbre.getHarmonic());
newTimbre.setPhase(timbre.getPhase());
osc.removeComponent(timbreIndex);
osc.insertComponent(timbreIndex, newTimbre);
}
});
}
});
float harmonic = Utilities.unscale(timbre.getHarmonic(), HARMONIC_MIN, HARMONIC_MAX);
KnobButton harmonicKnob = new KnobButton("Harmonic", harmonic);
harmonicKnob.addHandler(new Handler<Float>() {
public void handle(final Float progress) {
engine.updateOscillatorProperty(new OscillatorUpdater() {
public void update(ComplexOsc osc) {
Oscillator timbre = osc.getComponent(timbreIndex);
timbre.setHarmonic(Utilities.scale(progress, (int)HARMONIC_MIN, (int)HARMONIC_MAX));
}
});
}
});
KnobButton amplitudeKnob = new KnobButton("Amplitude", timbre.getAmplitude());
amplitudeKnob.addHandler(new Handler<Float>() {
public void handle(final Float progress) {
engine.updateOscillatorProperty(new OscillatorUpdater() {
public void update(ComplexOsc osc) {
Oscillator timbre = osc.getComponent(timbreIndex);
timbre.setAmplitude(progress);
}
});
}
});
float phase = Utilities.unscale(timbre.getPhase(), PHASE_MIN, PHASE_MAX);
KnobButton phaseKnob = new KnobButton("Phase", phase);
phaseKnob.addHandler(new Handler<Float>() {
public void handle(final Float progress) {
engine.updateOscillatorProperty(new OscillatorUpdater() {
public void update(ComplexOsc osc) {
Oscillator timbre = osc.getComponent(timbreIndex);
timbre.setPhase(Utilities.scale(progress, (int)PHASE_MIN, (int)PHASE_MAX));
}
});
}
});
RectButton delete = new RectButton("X");
delete.setTextPaint(textPaint);
delete.addHandler(new Handler<Object>() {
public void handle(Object o) {
VibratorService.vibrate();
engine.updateOscillatorProperty(new OscillatorUpdater() {
public void update(ComplexOsc osc) {
osc.removeComponent(timbreIndex);
}
});
// Do we have to refill here? We could potentially decrement the row indexes above this one
timbreTable.fill(AudioEngine.currentOscillator);
}
});
delete.setMargin(30);
this.addChild(typePicker, harmonicKnob, amplitudeKnob, phaseKnob, delete);
}
|
diff --git a/src/main/java/br/com/six2six/xstreamdsl/unmarshal/BetterUnmarshal.java b/src/main/java/br/com/six2six/xstreamdsl/unmarshal/BetterUnmarshal.java
index 3922e46..0d04cbe 100644
--- a/src/main/java/br/com/six2six/xstreamdsl/unmarshal/BetterUnmarshal.java
+++ b/src/main/java/br/com/six2six/xstreamdsl/unmarshal/BetterUnmarshal.java
@@ -1,106 +1,107 @@
package br.com.six2six.xstreamdsl.unmarshal;
import static br.com.six2six.xstreamdsl.util.ReflectionUtils.genericTypeFromField;
import static br.com.six2six.xstreamdsl.util.ReflectionUtils.invokeRecursiveSetter;
import static br.com.six2six.xstreamdsl.util.ReflectionUtils.invokeRecursiveType;
import static br.com.six2six.xstreamdsl.util.ReflectionUtils.newInstance;
import static br.com.six2six.xstreamdsl.util.ReflectionUtils.newInstanceCollection;
import static org.apache.commons.lang.ClassUtils.isAssignable;
import static org.apache.commons.lang.ClassUtils.primitiveToWrapper;
import java.util.Collection;
import br.com.six2six.xstreamdsl.unmarshal.transform.EnumTransformer;
import br.com.six2six.xstreamdsl.unmarshal.transform.NumberTransformer;
import br.com.six2six.xstreamdsl.unmarshal.transform.Transformer;
import com.thoughtworks.xstream.converters.UnmarshallingContext;
import com.thoughtworks.xstream.io.HierarchicalStreamReader;
public class BetterUnmarshal<T> {
private T bean;
private final HierarchicalStreamReader reader;
private final UnmarshallingContext context;
private BetterUnmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
this.reader = reader;
this.context = context;
}
public static <T> BetterUnmarshal<T> build(HierarchicalStreamReader reader, UnmarshallingContext context) {
return new BetterUnmarshal<T>(reader, context);
}
@SuppressWarnings("unchecked")
public BetterUnmarshal<T> to(Class<?> clazz) {
bean = (T) newInstance(clazz);
return this;
}
public BetterUnmarshal<T> node(String property) {
invokeRecursiveSetter(bean, property, transform(property, getValue()));
return this;
}
public BetterUnmarshal<T> node(String property, Transformer transformer) {
invokeRecursiveSetter(bean, property, transform(property, getValue(), transformer));
return this;
}
public BetterUnmarshal<T> delegate(String property) {
Class<?> type = invokeRecursiveType(bean, property);
reader.moveDown();
invokeRecursiveSetter(bean, property, context.convertAnother(bean, type));
reader.moveUp();
return this;
}
public BetterUnmarshal<T> collection(String property) {
Class<?> type = invokeRecursiveType(bean, property);
Collection<Object> collection = newInstanceCollection(type);
reader.moveDown();
while (reader.hasMoreChildren()) {
- // FIME converter entry collection
+ reader.moveDown();
collection.add(context.convertAnother(bean, genericTypeFromField(bean, property)));
+ reader.moveUp();
}
reader.moveUp();
invokeRecursiveSetter(bean, property, collection);
return this;
}
public T get() {
return bean;
}
private String getValue() {
if (!reader.hasMoreChildren()) return null;
reader.moveDown();
String value = reader.getValue();
reader.moveUp();
return value;
}
private Object transform(String property, String value) {
Class<?> type = primitiveToWrapper(invokeRecursiveType(bean, property));
if (isAssignable(type, Number.class)) {
return new NumberTransformer().transform(value, type);
} else if (isAssignable(type, Enum.class)) {
return new EnumTransformer().transform(value, type);
}
return value;
}
private Object transform(String property, String value, Transformer tranformer) {
Class<?> type = primitiveToWrapper(invokeRecursiveType(bean, property));
return tranformer.transform(value, type);
}
}
| false | true | public BetterUnmarshal<T> collection(String property) {
Class<?> type = invokeRecursiveType(bean, property);
Collection<Object> collection = newInstanceCollection(type);
reader.moveDown();
while (reader.hasMoreChildren()) {
// FIME converter entry collection
collection.add(context.convertAnother(bean, genericTypeFromField(bean, property)));
}
reader.moveUp();
invokeRecursiveSetter(bean, property, collection);
return this;
}
| public BetterUnmarshal<T> collection(String property) {
Class<?> type = invokeRecursiveType(bean, property);
Collection<Object> collection = newInstanceCollection(type);
reader.moveDown();
while (reader.hasMoreChildren()) {
reader.moveDown();
collection.add(context.convertAnother(bean, genericTypeFromField(bean, property)));
reader.moveUp();
}
reader.moveUp();
invokeRecursiveSetter(bean, property, collection);
return this;
}
|
diff --git a/uk.ac.gda.pydev.extension/src/uk/ac/gda/pydev/ScriptProjectCreator.java b/uk.ac.gda.pydev.extension/src/uk/ac/gda/pydev/ScriptProjectCreator.java
index 9a1d06e6c..c472c5afd 100644
--- a/uk.ac.gda.pydev.extension/src/uk/ac/gda/pydev/ScriptProjectCreator.java
+++ b/uk.ac.gda.pydev.extension/src/uk/ac/gda/pydev/ScriptProjectCreator.java
@@ -1,407 +1,406 @@
/*-
* Copyright © 2009 Diamond Light Source Ltd.
*
* This file is part of GDA.
*
* GDA is free software: you can redistribute it and/or modify it under the
* terms of the GNU General Public License version 3 as published by the Free
* Software Foundation.
*
* GDA 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 GDA. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.ac.gda.pydev;
import gda.configuration.properties.LocalProperties;
import gda.jython.JythonServerFacade;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.ui.IEditorReference;
import org.eclipse.ui.IPerspectiveDescriptor;
import org.eclipse.ui.IPerspectiveListener;
import org.eclipse.ui.IStartup;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkingSet;
import org.eclipse.ui.IWorkingSetManager;
import org.eclipse.ui.PlatformUI;
import org.python.copiedfromeclipsesrc.JavaVmLocationFinder;
import org.python.pydev.core.IInterpreterInfo;
import org.python.pydev.core.IPythonNature;
import org.python.pydev.core.MisconfigurationException;
import org.python.pydev.core.REF;
import org.python.pydev.core.Tuple;
import org.python.pydev.editor.codecompletion.revisited.ModulesManagerWithBuild;
import org.python.pydev.plugin.PydevPlugin;
import org.python.pydev.plugin.nature.PythonNature;
import org.python.pydev.runners.SimpleJythonRunner;
import org.python.pydev.ui.interpreters.JythonInterpreterManager;
import org.python.pydev.ui.pythonpathconf.InterpreterInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import uk.ac.gda.ClientManager;
import uk.ac.gda.jython.PydevConstants;
import uk.ac.gda.pydev.extension.Activator;
import uk.ac.gda.pydev.extension.builder.ConfigurationXMLNature;
import uk.ac.gda.pydev.extension.builder.ExtendedSyntaxNature;
import uk.ac.gda.pydev.extension.ui.perspective.JythonPerspective;
import uk.ac.gda.pydev.ui.preferences.PreferenceConstants;
import uk.ac.gda.ui.utils.ProjectUtils;
/**
* Class creates a project for the scripts if it does not exist.
*/
public class ScriptProjectCreator implements IStartup {
private static final Logger logger = LoggerFactory.getLogger(ScriptProjectCreator.class);
private static Map<String, IProject> pathProjectMap = new HashMap<String, IProject>();
/**
* Important configuration of pydev. The other place which this is done is when the Jython interpreter is set from
* the client plugin before the workbench is started.
*/
@Override
public void earlyStartup() {
if (!ClientManager.isClient())
return;
PlatformUI.getWorkbench().getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
// Attempt to refresh the pydev package explorer.
createPerspectiveListener();
}
});
}
public static String getProjectNameXMLConfig() {
return getProjectName("gda.scripts.user.xml.project.name", "XML - Config");
}
private static String getProjectName(final String property, final String defaultValue) {
String projectName = LocalProperties.get(property);
if (projectName == null)
projectName = defaultValue;
return projectName;
}
static public void handleShowXMLConfig(IProgressMonitor monitor) throws CoreException {
final IPreferenceStore store = Activator.getDefault().getPreferenceStore();
if (store.getBoolean(PreferenceConstants.SHOW_XML_CONFIG)) {
ProjectUtils.createImportProjectAndFolder(getProjectNameXMLConfig(), "src",
LocalProperties.get(LocalProperties.GDA_CONFIG) + "/xml", ConfigurationXMLNature.ID, null, monitor);
} else {
final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
final IProject project = root.getProject(getProjectNameXMLConfig());
if (project.exists()) {
// exists so delete
project.delete(false, true, monitor);
}
}
}
/**
* We programmatically create a Jython Interpreter so that the user does not have to.
*
* @throws CoreException
*/
static void createInterpreter(IProgressMonitor monitor) throws CoreException {
if (System.getProperty("gda.client.jython.automatic.interpreter") != null)
return;
final IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
// Horrible Hack warning: This code is copied from parts of Pydev to set up the interpreter and save it.
monitor.subTask("Checking if interpreter already exists");
if (!isInterpreter(monitor)) {
// Code copies from Pydev when the user chooses a Jython interpreter - these are the defaults.
final String interpreterPath = LocalProperties.getInstallationWorkspaceDir()
+ "plugins/uk.ac.gda.libs/jython2.5.1/";
final String executable = interpreterPath + "jython.jar";
final File script = PydevPlugin.getScriptWithinPySrc("interpreterInfo.py");
if (!script.exists()) {
throw new RuntimeException("The file specified does not exist: " + script);
}
monitor.subTask("Creating interpreter");
// gets the info for the python side
Tuple<String, String> outTup = new SimpleJythonRunner().runAndGetOutputWithJar(
REF.getFileAbsolutePath(script), executable, null, null, null, monitor);
InterpreterInfo info = null;
try {
// HACK Otherwise Pydev shows a dialog to the user.
ModulesManagerWithBuild.IN_TESTS = true;
info = InterpreterInfo.fromString(outTup.o1, false);
} catch (Exception e) {
- logger.error(
- "gda.root is defined incorrectly. It should be the plugins folder not the top level of GDA.", e);
+ logger.error("Something went wrong creating the InterpreterInfo.", e);
} finally {
ModulesManagerWithBuild.IN_TESTS = false;
}
if (info == null) {
// cancelled
return;
}
// the executable is the jar itself
info.executableOrJar = executable;
// we have to find the jars before we restore the compiled libs
if (preferenceStore.getBoolean(PreferenceConstants.GDA_PYDEV_ADD_DEFAULT_JAVA_JARS)) {
List<File> jars = JavaVmLocationFinder.findDefaultJavaJars();
for (File jar : jars) {
info.libs.add(REF.getFileAbsolutePath(jar));
}
}
// Defines all third party libs that can be used in scripts.
if (preferenceStore.getBoolean(PreferenceConstants.GDA_PYDEV_ADD_GDA_LIBS_JARS)) {
final List<String> gdaJars = LibsLocationFinder.findGdaLibs();
info.libs.addAll(gdaJars);
}
// Defines gda classes which can be used in scripts.
final String gdaInterfacePath = LibsLocationFinder.findGdaInterface();
if (gdaInterfacePath != null) {
info.libs.add(gdaInterfacePath);
}
List<String> allScriptProjectFolders = JythonServerFacade.getInstance().getAllScriptProjectFolders();
for (String s : allScriptProjectFolders) {
info.libs.add(s);
}
// java, java.lang, etc should be found now
info.restoreCompiledLibs(monitor);
info.setName(PydevConstants.INTERPRETER_NAME);
final JythonInterpreterManager man = (JythonInterpreterManager) PydevPlugin.getJythonInterpreterManager();
HashSet<String> set = new HashSet<String>();
set.add(PydevConstants.INTERPRETER_NAME);
man.setInfos(new IInterpreterInfo[] { info }, set, monitor);
logger.info("Jython interpreter registered: " + PydevConstants.INTERPRETER_NAME);
}
}
static public void createProjects(IProgressMonitor monitor) throws CoreException {
monitor.subTask("Checking existence of projects");
final IPreferenceStore store = Activator.getDefault().getPreferenceStore();
boolean chkGDASyntax = store.getBoolean(PreferenceConstants.CHECK_SCRIPT_SYNTAX);
if (chkGDASyntax)
createInterpreter(monitor);
List<IAdaptable> scriptProjects = new ArrayList<IAdaptable>();
for (String path : JythonServerFacade.getInstance().getAllScriptProjectFolders()) {
String projectName = JythonServerFacade.getInstance().getProjectNameForPath(path);
boolean shouldHideProject = shouldHideProject(path, store);
if (!shouldHideProject) {
final IProject newProject = createJythonProject(projectName, path, chkGDASyntax, monitor);
scriptProjects.add(newProject);
pathProjectMap.put(path, newProject);
} else {
final IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
final IProject project = root.getProject(projectName);
if (project.exists()) {
// exists so delete rather than hide for efficiency reasons
try {
project.delete(false, true, monitor);
} catch (CoreException e) {
// TODO Auto-generated catch block
logger.warn("Error deleting project " + projectName, e);
}
}
}
}
IWorkingSetManager workingSetManager = PlatformUI.getWorkbench().getWorkingSetManager();
IWorkingSet workingSet = workingSetManager.getWorkingSet("Scripts");
if (workingSet == null) {
monitor.subTask("Adding Scripts working set");
workingSetManager.addWorkingSet(workingSetManager.createWorkingSet("Scripts",
scriptProjects.toArray(new IAdaptable[] {})));
} else {
for (IAdaptable element : scriptProjects) {
workingSetManager.addToWorkingSets(element, new IWorkingSet[] { workingSet });
}
}
}
public static boolean shouldHideProject(String path, IPreferenceStore store) throws RuntimeException {
if (JythonServerFacade.getInstance().projectIsUserType(path)) {
return false;
}
if (JythonServerFacade.getInstance().projectIsConfigType(path)) {
return !store.getBoolean(PreferenceConstants.SHOW_CONFIG_SCRIPTS);
}
if (JythonServerFacade.getInstance().projectIsCoreType(path)) {
return !store.getBoolean(PreferenceConstants.SHOW_GDA_SCRIPTS);
}
throw new RuntimeException("Unknown type of Jython Script Project: " + path + " = "
+ JythonServerFacade.getInstance().getProjectNameForPath(path));
}
private void createPerspectiveListener() {
PlatformUI.getWorkbench().getWorkbenchWindows()[0].addPerspectiveListener(new IPerspectiveListener() {
@Override
public void perspectiveChanged(IWorkbenchPage page, IPerspectiveDescriptor perspective, String changeId) {
}
@Override
public void perspectiveActivated(IWorkbenchPage page, IPerspectiveDescriptor perspective) {
if (perspective.getId().equals(JythonPerspective.ID)) {
closeRichBeanEditors(page);
}
}
});
}
protected void closeRichBeanEditors(final IWorkbenchPage page) {
if (!Activator.getDefault().getPreferenceStore().getBoolean(PreferenceConstants.CLOSE_RICH_BEAN_EDITORS))
return;
final IEditorReference[] refs = page.getEditorReferences();
final List<IEditorReference> toClose = new ArrayList<IEditorReference>(3);
for (int i = 0; i < refs.length; i++) {
if (refs[i].getPartProperty("RichBeanEditorPart") != null) {
toClose.add(refs[i]);
}
}
if (!toClose.isEmpty())
page.closeEditors(toClose.toArray(new IEditorReference[toClose.size()]), false);
}
/**
* @param projectName
* @param importFolder
* @param chkGDASyntax
* @param monitor
* @return IProject created
* @throws CoreException
*/
static private IProject createJythonProject(final String projectName, final String importFolder,
final boolean chkGDASyntax, IProgressMonitor monitor) throws CoreException {
IProject project2 = ProjectUtils.createImportProjectAndFolder(projectName, "src", importFolder, null, null,
monitor);
ProjectUtils.addRemoveNature(project2, monitor, chkGDASyntax, ExtendedSyntaxNature.ID);
boolean hasPythonNature = PythonNature.getPythonNature(project2) != null;
if (chkGDASyntax) {
if (!hasPythonNature) {
// Assumes that the interpreter named PydevConstants.INTERPRETER_NAME has been created.
PythonNature.addNature(project2, monitor, IPythonNature.JYTHON_VERSION_2_5,
// NOTE Very important to start the name with a '/'
// or pydev creates the wrong kind of nature.
"/" + project2.getName() + "/src", null, PydevConstants.INTERPRETER_NAME, null);
}
} else {
if (hasPythonNature) {
// This should do the same as removing the Pydev config but neither
// prevent it being added when a python file is edited.
PythonNature.removeNature(project2, monitor);
}
}
return project2;
}
public static IProject projectForPath(String path) {
return pathProjectMap.get(path);
}
/**
* The method PydevPlugin.getJythonInterpreterManager().getInterpreterInfo(...) can never return in some
* circumstances because of a bug in pydev.
*
* @return true if new interpreter required
*/
static boolean isInterpreter(final IProgressMonitor monitor) {
final InterpreterThread checkInterpreter = new InterpreterThread(monitor);
checkInterpreter.start();
int totalTimeWaited = 0;
while (!checkInterpreter.isFinishedChecking()) {
try {
if (totalTimeWaited > 4000) {
logger.error("Unable to call getInterpreterInfo() method on pydev, assuming interpreter is already created.");
return true;
}
Thread.sleep(100);
totalTimeWaited += 100;
} catch (InterruptedException ne) {
break;
}
}
if (checkInterpreter.isInterpreter())
return true;
return false;
}
}
class InterpreterThread extends Thread {
private static final Logger logger = LoggerFactory.getLogger(InterpreterThread.class);
private IInterpreterInfo info = null;
private IProgressMonitor monitor;
private boolean finishedCheck = false;
InterpreterThread(final IProgressMonitor monitor) {
super("Interpreter Info");
setDaemon(true);// This is not that important
this.monitor = monitor;
}
@Override
public void run() {
// Might never return...
try {
info = PydevPlugin.getJythonInterpreterManager().getInterpreterInfo(PydevConstants.INTERPRETER_NAME,
monitor);
} catch (MisconfigurationException e) {
logger.error("Jython is not configured properly", e);
}
finishedCheck = true;
}
public boolean isInterpreter() {
return info != null;
}
public boolean isFinishedChecking() {
return finishedCheck;
}
}
| true | true | static void createInterpreter(IProgressMonitor monitor) throws CoreException {
if (System.getProperty("gda.client.jython.automatic.interpreter") != null)
return;
final IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
// Horrible Hack warning: This code is copied from parts of Pydev to set up the interpreter and save it.
monitor.subTask("Checking if interpreter already exists");
if (!isInterpreter(monitor)) {
// Code copies from Pydev when the user chooses a Jython interpreter - these are the defaults.
final String interpreterPath = LocalProperties.getInstallationWorkspaceDir()
+ "plugins/uk.ac.gda.libs/jython2.5.1/";
final String executable = interpreterPath + "jython.jar";
final File script = PydevPlugin.getScriptWithinPySrc("interpreterInfo.py");
if (!script.exists()) {
throw new RuntimeException("The file specified does not exist: " + script);
}
monitor.subTask("Creating interpreter");
// gets the info for the python side
Tuple<String, String> outTup = new SimpleJythonRunner().runAndGetOutputWithJar(
REF.getFileAbsolutePath(script), executable, null, null, null, monitor);
InterpreterInfo info = null;
try {
// HACK Otherwise Pydev shows a dialog to the user.
ModulesManagerWithBuild.IN_TESTS = true;
info = InterpreterInfo.fromString(outTup.o1, false);
} catch (Exception e) {
logger.error(
"gda.root is defined incorrectly. It should be the plugins folder not the top level of GDA.", e);
} finally {
ModulesManagerWithBuild.IN_TESTS = false;
}
if (info == null) {
// cancelled
return;
}
// the executable is the jar itself
info.executableOrJar = executable;
// we have to find the jars before we restore the compiled libs
if (preferenceStore.getBoolean(PreferenceConstants.GDA_PYDEV_ADD_DEFAULT_JAVA_JARS)) {
List<File> jars = JavaVmLocationFinder.findDefaultJavaJars();
for (File jar : jars) {
info.libs.add(REF.getFileAbsolutePath(jar));
}
}
// Defines all third party libs that can be used in scripts.
if (preferenceStore.getBoolean(PreferenceConstants.GDA_PYDEV_ADD_GDA_LIBS_JARS)) {
final List<String> gdaJars = LibsLocationFinder.findGdaLibs();
info.libs.addAll(gdaJars);
}
// Defines gda classes which can be used in scripts.
final String gdaInterfacePath = LibsLocationFinder.findGdaInterface();
if (gdaInterfacePath != null) {
info.libs.add(gdaInterfacePath);
}
List<String> allScriptProjectFolders = JythonServerFacade.getInstance().getAllScriptProjectFolders();
for (String s : allScriptProjectFolders) {
info.libs.add(s);
}
// java, java.lang, etc should be found now
info.restoreCompiledLibs(monitor);
info.setName(PydevConstants.INTERPRETER_NAME);
final JythonInterpreterManager man = (JythonInterpreterManager) PydevPlugin.getJythonInterpreterManager();
HashSet<String> set = new HashSet<String>();
set.add(PydevConstants.INTERPRETER_NAME);
man.setInfos(new IInterpreterInfo[] { info }, set, monitor);
logger.info("Jython interpreter registered: " + PydevConstants.INTERPRETER_NAME);
}
}
| static void createInterpreter(IProgressMonitor monitor) throws CoreException {
if (System.getProperty("gda.client.jython.automatic.interpreter") != null)
return;
final IPreferenceStore preferenceStore = Activator.getDefault().getPreferenceStore();
// Horrible Hack warning: This code is copied from parts of Pydev to set up the interpreter and save it.
monitor.subTask("Checking if interpreter already exists");
if (!isInterpreter(monitor)) {
// Code copies from Pydev when the user chooses a Jython interpreter - these are the defaults.
final String interpreterPath = LocalProperties.getInstallationWorkspaceDir()
+ "plugins/uk.ac.gda.libs/jython2.5.1/";
final String executable = interpreterPath + "jython.jar";
final File script = PydevPlugin.getScriptWithinPySrc("interpreterInfo.py");
if (!script.exists()) {
throw new RuntimeException("The file specified does not exist: " + script);
}
monitor.subTask("Creating interpreter");
// gets the info for the python side
Tuple<String, String> outTup = new SimpleJythonRunner().runAndGetOutputWithJar(
REF.getFileAbsolutePath(script), executable, null, null, null, monitor);
InterpreterInfo info = null;
try {
// HACK Otherwise Pydev shows a dialog to the user.
ModulesManagerWithBuild.IN_TESTS = true;
info = InterpreterInfo.fromString(outTup.o1, false);
} catch (Exception e) {
logger.error("Something went wrong creating the InterpreterInfo.", e);
} finally {
ModulesManagerWithBuild.IN_TESTS = false;
}
if (info == null) {
// cancelled
return;
}
// the executable is the jar itself
info.executableOrJar = executable;
// we have to find the jars before we restore the compiled libs
if (preferenceStore.getBoolean(PreferenceConstants.GDA_PYDEV_ADD_DEFAULT_JAVA_JARS)) {
List<File> jars = JavaVmLocationFinder.findDefaultJavaJars();
for (File jar : jars) {
info.libs.add(REF.getFileAbsolutePath(jar));
}
}
// Defines all third party libs that can be used in scripts.
if (preferenceStore.getBoolean(PreferenceConstants.GDA_PYDEV_ADD_GDA_LIBS_JARS)) {
final List<String> gdaJars = LibsLocationFinder.findGdaLibs();
info.libs.addAll(gdaJars);
}
// Defines gda classes which can be used in scripts.
final String gdaInterfacePath = LibsLocationFinder.findGdaInterface();
if (gdaInterfacePath != null) {
info.libs.add(gdaInterfacePath);
}
List<String> allScriptProjectFolders = JythonServerFacade.getInstance().getAllScriptProjectFolders();
for (String s : allScriptProjectFolders) {
info.libs.add(s);
}
// java, java.lang, etc should be found now
info.restoreCompiledLibs(monitor);
info.setName(PydevConstants.INTERPRETER_NAME);
final JythonInterpreterManager man = (JythonInterpreterManager) PydevPlugin.getJythonInterpreterManager();
HashSet<String> set = new HashSet<String>();
set.add(PydevConstants.INTERPRETER_NAME);
man.setInfos(new IInterpreterInfo[] { info }, set, monitor);
logger.info("Jython interpreter registered: " + PydevConstants.INTERPRETER_NAME);
}
}
|
diff --git a/src/edu/jas/ps/UnivPowerSeriesRing.java b/src/edu/jas/ps/UnivPowerSeriesRing.java
index ba40c68d..010852e2 100644
--- a/src/edu/jas/ps/UnivPowerSeriesRing.java
+++ b/src/edu/jas/ps/UnivPowerSeriesRing.java
@@ -1,477 +1,477 @@
/*
* $Id$
*/
package edu.jas.ps;
import java.io.Reader;
import java.util.Random;
import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;
import edu.jas.structure.RingElem;
import edu.jas.structure.RingFactory;
import edu.jas.structure.BinaryFunctor;
import edu.jas.structure.UnaryFunctor;
import edu.jas.structure.Selector;
import edu.jas.poly.GenPolynomial;
import edu.jas.poly.Monomial;
/**
* Univariate power series ring implementation.
* Uses lazy evaluated generating function for coefficients.
* @param <C> ring element type
* @author Heinz Kredel
*/
public class UnivPowerSeriesRing<C extends RingElem<C>>
implements RingFactory< UnivPowerSeries<C> > {
/**
* A default random sequence generator.
*/
protected final static Random random = new Random();
/**
* Default truncate.
*/
public final static int DEFAULT_TRUNCATE = 11;
/**
* Truncate.
*/
int truncate;
/**
* Default variable name.
*/
public final static String DEFAULT_NAME = "x";
/**
* Variable name.
*/
String var;
/**
* Coefficient ring factory.
*/
public final RingFactory<C> coFac;
/**
* The constant power series 1 for this ring.
*/
public final UnivPowerSeries<C> ONE;
/**
* The constant power series 0 for this ring.
*/
public final UnivPowerSeries<C> ZERO;
/**
* No argument constructor.
*/
private UnivPowerSeriesRing() {
throw new RuntimeException("do not use no-argument constructor");
//coFac = null;
//ONE = null;
//ZERO = null;
}
/**
* Constructor.
* @param coFac coefficient ring factory.
*/
public UnivPowerSeriesRing(RingFactory<C> coFac) {
this( coFac, DEFAULT_TRUNCATE, DEFAULT_NAME );
}
/**
* Constructor.
* @param coFac coefficient ring factory.
* @param truncate index of truncation.
*/
public UnivPowerSeriesRing(RingFactory<C> coFac, int truncate) {
this( coFac, truncate, DEFAULT_NAME );
}
/**
* Constructor.
* @param coFac coefficient ring factory.
* @param name of the variable.
*/
public UnivPowerSeriesRing(RingFactory<C> coFac, String name) {
this( coFac, DEFAULT_TRUNCATE, name );
}
/**
* Constructor.
* @param cofac coefficient ring factory.
* @param truncate index of truncation.
* @param name of the variable.
*/
public UnivPowerSeriesRing(RingFactory<C> cofac, int truncate, String name) {
this.coFac = cofac;
this.truncate = truncate;
this.var = name;
this.ONE = new UnivPowerSeries<C>(this,
new Coefficients<C>() {
public C generate(int i) {
if ( i == 0 ) {
return coFac.getONE();
} else {
return coFac.getZERO();
}
}
}
);
this.ZERO = new UnivPowerSeries<C>(this,
new Coefficients<C>() {
public C generate(int i) {
return coFac.getZERO();
}
}
);
}
/**
* Fixed point construction.
* @param map a mapping of power series.
* @return fix point wrt map.
*/
// Cannot be a static method because a power series ring is required.
public UnivPowerSeries<C> fixPoint(PowerSeriesMap<C> map) {
UnivPowerSeries<C> ps1 = new UnivPowerSeries<C>(this);
UnivPowerSeries<C> ps2 = map.map(ps1);
ps1.lazyCoeffs = ps2.lazyCoeffs;
return ps2;
}
/**
* To String.
* @return string representation of this.
*/
public String toString() {
StringBuffer sb = new StringBuffer();
String scf = coFac.getClass().getSimpleName();
sb.append(scf + "((" + var + "))");
return sb.toString();
}
/** Comparison with any other object.
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
@SuppressWarnings("unchecked")
public boolean equals( Object B ) {
if ( ! ( B instanceof UnivPowerSeriesRing ) ) {
return false;
}
UnivPowerSeriesRing<C> a = null;
try {
a = (UnivPowerSeriesRing<C>) B;
} catch (ClassCastException ignored) {
}
if ( var.equals( a.var ) ) {
return true;
}
return false;
}
/** Hash code for this .
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
int h = 0;
h = ( var.hashCode() << 27 );
h += truncate;
return h;
}
/** Get the zero element.
* @return 0 as UnivPowerSeries<C>.
*/
public UnivPowerSeries<C> getZERO() {
return ZERO;
}
/** Get the one element.
* @return 1 as UnivPowerSeries<C>.
*/
public UnivPowerSeries<C> getONE() {
return ONE;
}
/** Get the power series of the exponential function.
* @return exp(x) as UnivPowerSeries<C>.
*/
public UnivPowerSeries<C> getEXP() {
return fixPoint(
new PowerSeriesMap<C>() {
public UnivPowerSeries<C> map(UnivPowerSeries<C> e) {
return e.integrate( coFac.getONE() );
}
}
);
}
/** Get the power series of the sinus function.
* @return sin(x) as UnivPowerSeries<C>.
*/
public UnivPowerSeries<C> getSIN() {
return fixPoint(
new PowerSeriesMap<C>() {
public UnivPowerSeries<C> map(UnivPowerSeries<C> s) {
return s.negate().integrate( coFac.getONE() ).integrate( coFac.getZERO() );
}
}
);
}
/** Get the power series of the cosinus function.
* @return cos(x) as UnivPowerSeries<C>.
*/
public UnivPowerSeries<C> getCOS() {
return fixPoint(
new PowerSeriesMap<C>() {
public UnivPowerSeries<C> map(UnivPowerSeries<C> c) {
return c.negate().integrate( coFac.getZERO() ).integrate( coFac.getONE() );
}
}
);
}
/** Get the power series of the tangens function.
* @return tan(x) as UnivPowerSeries<C>.
*/
public UnivPowerSeries<C> getTAN() {
return fixPoint(
new PowerSeriesMap<C>() {
public UnivPowerSeries<C> map(UnivPowerSeries<C> t) {
return t.multiply(t).sum( getONE() ).integrate( coFac.getZERO() );
}
}
);
}
/**
* Is commuative.
* @return true, if this ring is commutative, else false.
*/
public boolean isCommutative() {
return coFac.isCommutative();
}
/**
* Query if this ring is associative.
* @return true if this ring is associative, else false.
*/
public boolean isAssociative() {
return coFac.isAssociative();
}
/**
* Query if this ring is a field.
* @return false.
*/
public boolean isField() {
return false;
}
/**
* Characteristic of this ring.
* @return characteristic of this ring.
*/
public java.math.BigInteger characteristic() {
return coFac.characteristic();
}
/** Get a (constant) UnivPowerSeries<C> from a long value.
* @param a long.
* @return a UnivPowerSeries<C>.
*/
public UnivPowerSeries<C> fromInteger(long a) {
return ONE.multiply( coFac.fromInteger(a) );
}
/** Get a (constant) UnivPowerSeries<C> from a java.math.BigInteger.
* @param a BigInteger.
* @return a UnivPowerSeries<C>.
*/
public UnivPowerSeries<C> fromInteger(java.math.BigInteger a) {
return ONE.multiply( coFac.fromInteger(a) );
}
/** Get a UnivPowerSeries<C> from a GenPolynomial<C>.
* @param a GenPolynomial<C>.
* @return a UnivPowerSeries<C>.
*/
public UnivPowerSeries<C> fromPolynomial(GenPolynomial<C> a) {
if ( a == null || a.isZERO() ) {
return ZERO;
}
if ( a.isONE() ) {
return ONE;
}
if ( a.ring.nvar != 1 ) {
throw new RuntimeException("only for univariate polynomials");
}
HashMap<Integer,C> cache = new HashMap<Integer,C>( a.length() );
//Iterator<Monomial<C>> it = a.monomialIterator();
- for ( Monomial<BigInteger> m : a ) {
+ for ( Monomial<C> m : a ) {
//while ( it.hasNext() ) {
//Monomial<C> m = it.next();
long e = m.exponent().getVal(0);
cache.put( (int)e, m.coefficient() );
}
return new UnivPowerSeries<C>(this,
new Coefficients<C>(cache) {
public C generate(int i) {
// cached coefficients returned by get
return coFac.getZERO();
}
}
);
}
/**
* Generate a random power series with
* k = 5,
* d = 0.7.
* @return a random power series.
*/
public UnivPowerSeries<C> random() {
return random(5,0.7f,random);
}
/**
* Generate a random power series with
* d = 0.7.
* @param k bitsize of random coefficients.
* @return a random power series.
*/
public UnivPowerSeries<C> random(int k) {
return random(k,0.7f,random);
}
/**
* Generate a random power series with
* d = 0.7.
* @param k bitsize of random coefficients.
* @param rnd is a source for random bits.
* @return a random power series.
*/
public UnivPowerSeries<C> random(int k, Random rnd) {
return random(k,0.7f,rnd);
}
/**
* Generate a random power series.
* @param k bitsize of random coefficients.
* @param d density of non-zero coefficients.
* @return a random power series.
*/
public UnivPowerSeries<C> random(int k, float d) {
return random(k,d,random);
}
/**
* Generate a random power series.
* @param k bitsize of random coefficients.
* @param d density of non-zero coefficients.
* @param rnd is a source for random bits.
* @return a random power series.
*/
public UnivPowerSeries<C> random(final int k, final float d, final Random rnd) {
return new UnivPowerSeries<C>(this,
new Coefficients<C>() {
public C generate(int i) {
// cached coefficients returned by get
C c;
float f = rnd.nextFloat();
if ( f < d ) {
c = coFac.random(k,rnd);
} else {
c = coFac.getZERO();
}
return c;
}
}
);
}
/**
* Copy power series.
* @param c a power series.
* @return a copy of c.
*/
public UnivPowerSeries<C> copy(UnivPowerSeries<C> c) {
return new UnivPowerSeries<C>( this, c.lazyCoeffs );
}
/**
* Parse a power series.
* <b>Note:</b> not implemented.
* @param s String.
* @return power series from s.
*/
public UnivPowerSeries<C> parse(String s) {
throw new RuntimeException("parse for power series not implemented");
}
/**
* Parse a power series.
* <b>Note:</b> not implemented.
* @param r Reader.
* @return next power series from r.
*/
public UnivPowerSeries<C> parse(Reader r) {
throw new RuntimeException("parse for power series not implemented");
}
}
| true | true | public UnivPowerSeries<C> fromPolynomial(GenPolynomial<C> a) {
if ( a == null || a.isZERO() ) {
return ZERO;
}
if ( a.isONE() ) {
return ONE;
}
if ( a.ring.nvar != 1 ) {
throw new RuntimeException("only for univariate polynomials");
}
HashMap<Integer,C> cache = new HashMap<Integer,C>( a.length() );
//Iterator<Monomial<C>> it = a.monomialIterator();
for ( Monomial<BigInteger> m : a ) {
//while ( it.hasNext() ) {
//Monomial<C> m = it.next();
long e = m.exponent().getVal(0);
cache.put( (int)e, m.coefficient() );
}
return new UnivPowerSeries<C>(this,
new Coefficients<C>(cache) {
public C generate(int i) {
// cached coefficients returned by get
return coFac.getZERO();
}
}
);
}
| public UnivPowerSeries<C> fromPolynomial(GenPolynomial<C> a) {
if ( a == null || a.isZERO() ) {
return ZERO;
}
if ( a.isONE() ) {
return ONE;
}
if ( a.ring.nvar != 1 ) {
throw new RuntimeException("only for univariate polynomials");
}
HashMap<Integer,C> cache = new HashMap<Integer,C>( a.length() );
//Iterator<Monomial<C>> it = a.monomialIterator();
for ( Monomial<C> m : a ) {
//while ( it.hasNext() ) {
//Monomial<C> m = it.next();
long e = m.exponent().getVal(0);
cache.put( (int)e, m.coefficient() );
}
return new UnivPowerSeries<C>(this,
new Coefficients<C>(cache) {
public C generate(int i) {
// cached coefficients returned by get
return coFac.getZERO();
}
}
);
}
|
diff --git a/fap/app/controllers/fap/LoggerController.java b/fap/app/controllers/fap/LoggerController.java
index 5e1d9597..55eaa5df 100644
--- a/fap/app/controllers/fap/LoggerController.java
+++ b/fap/app/controllers/fap/LoggerController.java
@@ -1,276 +1,276 @@
package controllers.fap;
import play.*;
import play.mvc.*;
import properties.FapProperties;
import controllers.fap.*;
import tags.ReflectionUtils;
import validation.*;
import models.*;
import java.text.SimpleDateFormat;
import java.util.*;
import messages.Messages;
import messages.Messages.MessageType;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.lang.reflect.Field;
import org.apache.log4j.Appender;
import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.config.PropertyGetter.PropertyCallback;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import emails.Mails;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
public class LoggerController extends GenericController {
private static Logger log = Logger.getLogger("Paginas");
public static void index(){
log.info("Visitando página: fap/Admin/logs.html");
renderTemplate("fap/Admin/logs.html");
}
public static void logs(long fecha1, long fecha2) throws IOException{
Date date1 = new Date(fecha1);
Date date2 = new Date(fecha2);
int logsD=0, logsA=0;
ArrayList<String> borrarDaily = new ArrayList<String>();
ArrayList<String> borrarAuditable = new ArrayList<String>();
Gson gson = new Gson();
ArrayList<BufferedReader> brDaily = new ArrayList<BufferedReader>();
ArrayList<BufferedReader> brAuditable = new ArrayList<BufferedReader>();
ArrayList<FileReader> ficherosACerrar = new ArrayList<FileReader>();
boolean seguirLeyendo=true, error;
Date date = date1;
String fileName, dirName = null;
org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("app");
File rutaLogs = null;
for (Enumeration<Appender> e = logger.getAllAppenders(); e.hasMoreElements();){
Appender appender = e.nextElement();
if (appender instanceof DailyRollingFileAppender){
fileName = ((DailyRollingFileAppender)appender).getFile();
int indexBackup = fileName.lastIndexOf("/");
if (indexBackup == -1) {
rutaLogs = Play.applicationPath;
}
else {
dirName = fileName.substring(0, indexBackup);
if ((dirName.matches("^[a-zA-Z]:")) || (dirName.startsWith("/"))) {
rutaLogs = new File(dirName);
} else {
rutaLogs = new File(Play.applicationPath.getAbsolutePath() + "/" + dirName);
}
}
}
}
while (seguirLeyendo){
try {
String ficheroLogs = nombreFichero(date, "Daily");
String nameLogs = null;
if (ficheroLogs != null){
int indexBackup = ficheroLogs.lastIndexOf("/");
if (indexBackup == -1) {
nameLogs = ficheroLogs;
}
else {
nameLogs = ficheroLogs.substring(indexBackup+1);
}
error = false;
String rutaFichero = rutaLogs + "/" + nameLogs;
// Si el fichero no es del día actual, lo recuperamos de los backups, descomprimiendolo
if (!esHoy(date)){
if (utils.ZipUtils.descomprimirEnZip(rutaLogs+"/backups/Daily/"+nameLogs+".zip", rutaFichero)){
// Lo anotamos para despues borrarlo, y no dejar basura
borrarDaily.add(rutaFichero);
} else{
error = true;
play.Logger.error("Descompresión de '" + rutaLogs + "/backups/Daily/"+nameLogs+".zip' fallida o no existe el fichero");
}
}
if (!error){
if ((new File(rutaFichero)).exists()){
FileReader ficheroDaily = new FileReader(rutaFichero);
brDaily.add(new BufferedReader(ficheroDaily));
ficherosACerrar.add(ficheroDaily);
} else {
play.Logger.error("Fichero '"+ rutaFichero +"' no existe. Imposible mostrarlo en la tabla de Logs");
}
}
}
} catch (FileNotFoundException e) {
play.Logger.error(e,"Fichero de log del Daily no encontrado");
}
try {
String ficheroLogs = nombreFichero(date, "Auditable");
String nameLogs = null;
if (ficheroLogs != null){
int indexBackup = ficheroLogs.lastIndexOf("/");
if (indexBackup == -1) {
nameLogs = ficheroLogs;
}
else {
- nameLogs = ficheroLogs.substring(indexBackup, ficheroLogs.length());
+ nameLogs = ficheroLogs.substring(indexBackup+1);
}
error = false;
String rutaFichero = rutaLogs + "/" + nameLogs;
// Si el fichero no es del día actual, lo recuperamos de los backups, descomprimiendolo
if (!esHoy(date)){
if (utils.ZipUtils.descomprimirEnZip(rutaLogs+"/backups/Auditable/"+nameLogs+".zip", rutaFichero)){
// Lo anotamos para despues borrarlo, y no dejar basura
borrarAuditable.add(rutaFichero);
} else{
error = true;
play.Logger.error("Descompresión de '" + rutaLogs +"/backups/Auditable/"+nameLogs+".zip' fallida o no existe el fichero");
}
}
if (!error){
if ((new File(rutaFichero)).exists()){
FileReader ficheroAuditable = new FileReader(rutaFichero);
brAuditable.add(new BufferedReader(ficheroAuditable));
ficherosACerrar.add(ficheroAuditable);
} else {
play.Logger.error("Fichero '"+ rutaFichero +"' no existe. Imposible mostrarlo en la tabla de Logs");
}
}
}
} catch (FileNotFoundException e) {
play.Logger.error(e,"Fichero de log Auditable no encontrado");
}
if (diaSiguiente(date).before(date2)){
date = diaSiguiente(date);
} else {
seguirLeyendo=false;
}
}
java.util.List<Log> rows = new ArrayList<Log>();
for (int i=0; i<brDaily.size(); i++){
String linea;
try {
while ((linea = brDaily.get(i).readLine()) != null) {
rows.add(gson.fromJson(linea, Log.class));
logsD++;
}
} catch (JsonSyntaxException e) {
play.Logger.error(e,"Error de formato en el fichero de log Daily");
} catch (IOException e) {
play.Logger.error(e,"Error al leer el fichero de log Daily");
}
}
for (int i=0; i<brAuditable.size(); i++){
String linea;
try {
while ((linea = brAuditable.get(i).readLine()) != null) {
rows.add(gson.fromJson(linea, Log.class));
logsA++;
}
} catch (JsonSyntaxException e) {
play.Logger.error(e,"Error de formato en el fichero de log Auditable");
} catch (IOException e) {
play.Logger.error(e,"Error al leer el fichero de log Auditable");
}
}
List<Log> rowsFiltered = rows; //Tabla sin permisos, no filtra
tables.TableRenderNoPermisos<Log> response = new tables.TableRenderNoPermisos<Log>(rowsFiltered);
flexjson.JSONSerializer flex = new flexjson.JSONSerializer().include("rows.level", "rows.time", "rows.class_", "rows.user", "rows.message", "rows.trace").transform(new serializer.DateTimeTransformer(), org.joda.time.DateTime.class).exclude("*");
String serialize = flex.serialize(response);
// Antes de renderizar la página, eliminamos los ficheros descomprimidos, para no dejar basura, si los hay.
for(int i=0; i<ficherosACerrar.size(); i++){
ficherosACerrar.get(i).close();
}
for(int i=0; i<borrarDaily.size(); i++){
File borrado = new File(borrarDaily.get(i));
borrado.delete();
}
for(int i=0; i<borrarAuditable.size(); i++){
File borrado = new File(borrarAuditable.get(i));
borrado.delete();
}
renderJSON(serialize);
}
@Util
@SuppressWarnings("deprecation")
private static boolean esHoy(Date date) {
Date hoy = new Date();
if ((hoy.getDate() == date.getDate()) && (hoy.getMonth() == date.getMonth()) && (hoy.getYear() == date.getYear()))
return true;
return false;
}
@Util
private static String nombreFichero(Date date, String loggerName) {
String fileName = null;
org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("app");
// busca entre los appenders dos que sean de tipo DailyRollingFile,
// preferentemente aquel cuyo nombre es "Daily" o "Auditable", que son los configurados inicialmente en
// los ficheros de configuracion
for (Enumeration<Appender> e = logger.getAllAppenders(); e.hasMoreElements();){
Appender appender = e.nextElement();
if (appender instanceof DailyRollingFileAppender){
fileName = ((DailyRollingFileAppender)appender).getFile();
if (((DailyRollingFileAppender)appender).getName().equals(loggerName)){
break;
}
}
}
if (fileName == null){
return fileName;
}
if (!esHoy(date)) {
fileName += "."+(date.getYear()+1900)+"-";
if (date.getMonth() < 9)
fileName += "0";
fileName += (date.getMonth()+1)+"-";
if (date.getDate() < 10)
fileName += "0";
fileName += date.getDate();
}
return fileName;
}
@SuppressWarnings("deprecation")
public static Date diaSiguiente (Date date){
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.DATE, 1);
return cal.getTime();
}
}
| true | true | public static void logs(long fecha1, long fecha2) throws IOException{
Date date1 = new Date(fecha1);
Date date2 = new Date(fecha2);
int logsD=0, logsA=0;
ArrayList<String> borrarDaily = new ArrayList<String>();
ArrayList<String> borrarAuditable = new ArrayList<String>();
Gson gson = new Gson();
ArrayList<BufferedReader> brDaily = new ArrayList<BufferedReader>();
ArrayList<BufferedReader> brAuditable = new ArrayList<BufferedReader>();
ArrayList<FileReader> ficherosACerrar = new ArrayList<FileReader>();
boolean seguirLeyendo=true, error;
Date date = date1;
String fileName, dirName = null;
org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("app");
File rutaLogs = null;
for (Enumeration<Appender> e = logger.getAllAppenders(); e.hasMoreElements();){
Appender appender = e.nextElement();
if (appender instanceof DailyRollingFileAppender){
fileName = ((DailyRollingFileAppender)appender).getFile();
int indexBackup = fileName.lastIndexOf("/");
if (indexBackup == -1) {
rutaLogs = Play.applicationPath;
}
else {
dirName = fileName.substring(0, indexBackup);
if ((dirName.matches("^[a-zA-Z]:")) || (dirName.startsWith("/"))) {
rutaLogs = new File(dirName);
} else {
rutaLogs = new File(Play.applicationPath.getAbsolutePath() + "/" + dirName);
}
}
}
}
while (seguirLeyendo){
try {
String ficheroLogs = nombreFichero(date, "Daily");
String nameLogs = null;
if (ficheroLogs != null){
int indexBackup = ficheroLogs.lastIndexOf("/");
if (indexBackup == -1) {
nameLogs = ficheroLogs;
}
else {
nameLogs = ficheroLogs.substring(indexBackup+1);
}
error = false;
String rutaFichero = rutaLogs + "/" + nameLogs;
// Si el fichero no es del día actual, lo recuperamos de los backups, descomprimiendolo
if (!esHoy(date)){
if (utils.ZipUtils.descomprimirEnZip(rutaLogs+"/backups/Daily/"+nameLogs+".zip", rutaFichero)){
// Lo anotamos para despues borrarlo, y no dejar basura
borrarDaily.add(rutaFichero);
} else{
error = true;
play.Logger.error("Descompresión de '" + rutaLogs + "/backups/Daily/"+nameLogs+".zip' fallida o no existe el fichero");
}
}
if (!error){
if ((new File(rutaFichero)).exists()){
FileReader ficheroDaily = new FileReader(rutaFichero);
brDaily.add(new BufferedReader(ficheroDaily));
ficherosACerrar.add(ficheroDaily);
} else {
play.Logger.error("Fichero '"+ rutaFichero +"' no existe. Imposible mostrarlo en la tabla de Logs");
}
}
}
} catch (FileNotFoundException e) {
play.Logger.error(e,"Fichero de log del Daily no encontrado");
}
try {
String ficheroLogs = nombreFichero(date, "Auditable");
String nameLogs = null;
if (ficheroLogs != null){
int indexBackup = ficheroLogs.lastIndexOf("/");
if (indexBackup == -1) {
nameLogs = ficheroLogs;
}
else {
nameLogs = ficheroLogs.substring(indexBackup, ficheroLogs.length());
}
error = false;
String rutaFichero = rutaLogs + "/" + nameLogs;
// Si el fichero no es del día actual, lo recuperamos de los backups, descomprimiendolo
if (!esHoy(date)){
if (utils.ZipUtils.descomprimirEnZip(rutaLogs+"/backups/Auditable/"+nameLogs+".zip", rutaFichero)){
// Lo anotamos para despues borrarlo, y no dejar basura
borrarAuditable.add(rutaFichero);
} else{
error = true;
play.Logger.error("Descompresión de '" + rutaLogs +"/backups/Auditable/"+nameLogs+".zip' fallida o no existe el fichero");
}
}
if (!error){
if ((new File(rutaFichero)).exists()){
FileReader ficheroAuditable = new FileReader(rutaFichero);
brAuditable.add(new BufferedReader(ficheroAuditable));
ficherosACerrar.add(ficheroAuditable);
} else {
play.Logger.error("Fichero '"+ rutaFichero +"' no existe. Imposible mostrarlo en la tabla de Logs");
}
}
}
} catch (FileNotFoundException e) {
play.Logger.error(e,"Fichero de log Auditable no encontrado");
}
if (diaSiguiente(date).before(date2)){
date = diaSiguiente(date);
} else {
seguirLeyendo=false;
}
}
java.util.List<Log> rows = new ArrayList<Log>();
for (int i=0; i<brDaily.size(); i++){
String linea;
try {
while ((linea = brDaily.get(i).readLine()) != null) {
rows.add(gson.fromJson(linea, Log.class));
logsD++;
}
} catch (JsonSyntaxException e) {
play.Logger.error(e,"Error de formato en el fichero de log Daily");
} catch (IOException e) {
play.Logger.error(e,"Error al leer el fichero de log Daily");
}
}
for (int i=0; i<brAuditable.size(); i++){
String linea;
try {
while ((linea = brAuditable.get(i).readLine()) != null) {
rows.add(gson.fromJson(linea, Log.class));
logsA++;
}
} catch (JsonSyntaxException e) {
play.Logger.error(e,"Error de formato en el fichero de log Auditable");
} catch (IOException e) {
play.Logger.error(e,"Error al leer el fichero de log Auditable");
}
}
List<Log> rowsFiltered = rows; //Tabla sin permisos, no filtra
tables.TableRenderNoPermisos<Log> response = new tables.TableRenderNoPermisos<Log>(rowsFiltered);
flexjson.JSONSerializer flex = new flexjson.JSONSerializer().include("rows.level", "rows.time", "rows.class_", "rows.user", "rows.message", "rows.trace").transform(new serializer.DateTimeTransformer(), org.joda.time.DateTime.class).exclude("*");
String serialize = flex.serialize(response);
// Antes de renderizar la página, eliminamos los ficheros descomprimidos, para no dejar basura, si los hay.
for(int i=0; i<ficherosACerrar.size(); i++){
ficherosACerrar.get(i).close();
}
for(int i=0; i<borrarDaily.size(); i++){
File borrado = new File(borrarDaily.get(i));
borrado.delete();
}
for(int i=0; i<borrarAuditable.size(); i++){
File borrado = new File(borrarAuditable.get(i));
borrado.delete();
}
renderJSON(serialize);
}
| public static void logs(long fecha1, long fecha2) throws IOException{
Date date1 = new Date(fecha1);
Date date2 = new Date(fecha2);
int logsD=0, logsA=0;
ArrayList<String> borrarDaily = new ArrayList<String>();
ArrayList<String> borrarAuditable = new ArrayList<String>();
Gson gson = new Gson();
ArrayList<BufferedReader> brDaily = new ArrayList<BufferedReader>();
ArrayList<BufferedReader> brAuditable = new ArrayList<BufferedReader>();
ArrayList<FileReader> ficherosACerrar = new ArrayList<FileReader>();
boolean seguirLeyendo=true, error;
Date date = date1;
String fileName, dirName = null;
org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger("app");
File rutaLogs = null;
for (Enumeration<Appender> e = logger.getAllAppenders(); e.hasMoreElements();){
Appender appender = e.nextElement();
if (appender instanceof DailyRollingFileAppender){
fileName = ((DailyRollingFileAppender)appender).getFile();
int indexBackup = fileName.lastIndexOf("/");
if (indexBackup == -1) {
rutaLogs = Play.applicationPath;
}
else {
dirName = fileName.substring(0, indexBackup);
if ((dirName.matches("^[a-zA-Z]:")) || (dirName.startsWith("/"))) {
rutaLogs = new File(dirName);
} else {
rutaLogs = new File(Play.applicationPath.getAbsolutePath() + "/" + dirName);
}
}
}
}
while (seguirLeyendo){
try {
String ficheroLogs = nombreFichero(date, "Daily");
String nameLogs = null;
if (ficheroLogs != null){
int indexBackup = ficheroLogs.lastIndexOf("/");
if (indexBackup == -1) {
nameLogs = ficheroLogs;
}
else {
nameLogs = ficheroLogs.substring(indexBackup+1);
}
error = false;
String rutaFichero = rutaLogs + "/" + nameLogs;
// Si el fichero no es del día actual, lo recuperamos de los backups, descomprimiendolo
if (!esHoy(date)){
if (utils.ZipUtils.descomprimirEnZip(rutaLogs+"/backups/Daily/"+nameLogs+".zip", rutaFichero)){
// Lo anotamos para despues borrarlo, y no dejar basura
borrarDaily.add(rutaFichero);
} else{
error = true;
play.Logger.error("Descompresión de '" + rutaLogs + "/backups/Daily/"+nameLogs+".zip' fallida o no existe el fichero");
}
}
if (!error){
if ((new File(rutaFichero)).exists()){
FileReader ficheroDaily = new FileReader(rutaFichero);
brDaily.add(new BufferedReader(ficheroDaily));
ficherosACerrar.add(ficheroDaily);
} else {
play.Logger.error("Fichero '"+ rutaFichero +"' no existe. Imposible mostrarlo en la tabla de Logs");
}
}
}
} catch (FileNotFoundException e) {
play.Logger.error(e,"Fichero de log del Daily no encontrado");
}
try {
String ficheroLogs = nombreFichero(date, "Auditable");
String nameLogs = null;
if (ficheroLogs != null){
int indexBackup = ficheroLogs.lastIndexOf("/");
if (indexBackup == -1) {
nameLogs = ficheroLogs;
}
else {
nameLogs = ficheroLogs.substring(indexBackup+1);
}
error = false;
String rutaFichero = rutaLogs + "/" + nameLogs;
// Si el fichero no es del día actual, lo recuperamos de los backups, descomprimiendolo
if (!esHoy(date)){
if (utils.ZipUtils.descomprimirEnZip(rutaLogs+"/backups/Auditable/"+nameLogs+".zip", rutaFichero)){
// Lo anotamos para despues borrarlo, y no dejar basura
borrarAuditable.add(rutaFichero);
} else{
error = true;
play.Logger.error("Descompresión de '" + rutaLogs +"/backups/Auditable/"+nameLogs+".zip' fallida o no existe el fichero");
}
}
if (!error){
if ((new File(rutaFichero)).exists()){
FileReader ficheroAuditable = new FileReader(rutaFichero);
brAuditable.add(new BufferedReader(ficheroAuditable));
ficherosACerrar.add(ficheroAuditable);
} else {
play.Logger.error("Fichero '"+ rutaFichero +"' no existe. Imposible mostrarlo en la tabla de Logs");
}
}
}
} catch (FileNotFoundException e) {
play.Logger.error(e,"Fichero de log Auditable no encontrado");
}
if (diaSiguiente(date).before(date2)){
date = diaSiguiente(date);
} else {
seguirLeyendo=false;
}
}
java.util.List<Log> rows = new ArrayList<Log>();
for (int i=0; i<brDaily.size(); i++){
String linea;
try {
while ((linea = brDaily.get(i).readLine()) != null) {
rows.add(gson.fromJson(linea, Log.class));
logsD++;
}
} catch (JsonSyntaxException e) {
play.Logger.error(e,"Error de formato en el fichero de log Daily");
} catch (IOException e) {
play.Logger.error(e,"Error al leer el fichero de log Daily");
}
}
for (int i=0; i<brAuditable.size(); i++){
String linea;
try {
while ((linea = brAuditable.get(i).readLine()) != null) {
rows.add(gson.fromJson(linea, Log.class));
logsA++;
}
} catch (JsonSyntaxException e) {
play.Logger.error(e,"Error de formato en el fichero de log Auditable");
} catch (IOException e) {
play.Logger.error(e,"Error al leer el fichero de log Auditable");
}
}
List<Log> rowsFiltered = rows; //Tabla sin permisos, no filtra
tables.TableRenderNoPermisos<Log> response = new tables.TableRenderNoPermisos<Log>(rowsFiltered);
flexjson.JSONSerializer flex = new flexjson.JSONSerializer().include("rows.level", "rows.time", "rows.class_", "rows.user", "rows.message", "rows.trace").transform(new serializer.DateTimeTransformer(), org.joda.time.DateTime.class).exclude("*");
String serialize = flex.serialize(response);
// Antes de renderizar la página, eliminamos los ficheros descomprimidos, para no dejar basura, si los hay.
for(int i=0; i<ficherosACerrar.size(); i++){
ficherosACerrar.get(i).close();
}
for(int i=0; i<borrarDaily.size(); i++){
File borrado = new File(borrarDaily.get(i));
borrado.delete();
}
for(int i=0; i<borrarAuditable.size(); i++){
File borrado = new File(borrarAuditable.get(i));
borrado.delete();
}
renderJSON(serialize);
}
|
diff --git a/src/com/android/mms/data/Contact.java b/src/com/android/mms/data/Contact.java
index 42f9037..d7290e4 100644
--- a/src/com/android/mms/data/Contact.java
+++ b/src/com/android/mms/data/Contact.java
@@ -1,489 +1,491 @@
package com.android.mms.data;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import android.content.ContentUris;
import android.content.Context;
import android.database.ContentObserver;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Handler;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Presence;
import android.provider.Telephony.Mms;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;
import android.util.Log;
import com.android.mms.ui.MessageUtils;
import com.android.mms.util.ContactInfoCache;
import com.android.mms.util.TaskStack;
import com.android.mms.LogTag;
public class Contact {
private static final String TAG = "Contact";
private static final boolean V = false;
private static final TaskStack sTaskStack = new TaskStack();
// private static final ContentObserver sContactsObserver = new ContentObserver(new Handler()) {
// @Override
// public void onChange(boolean selfUpdate) {
// if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
// log("contact changed, invalidate cache");
// }
// invalidateCache();
// }
// };
private static final ContentObserver sPresenceObserver = new ContentObserver(new Handler()) {
@Override
public void onChange(boolean selfUpdate) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("presence changed, invalidate cache");
}
invalidateCache();
}
};
private final HashSet<UpdateListener> mListeners = new HashSet<UpdateListener>();
private String mNumber;
private String mName;
private String mNameAndNumber; // for display, e.g. Fred Flintstone <670-782-1123>
private boolean mNumberIsModified; // true if the number is modified
private long mRecipientId; // used to find the Recipient cache entry
private String mLabel;
private long mPersonId;
private int mPresenceResId; // TODO: make this a state instead of a res ID
private String mPresenceText;
private BitmapDrawable mAvatar;
private boolean mIsStale;
@Override
public synchronized String toString() {
return String.format("{ number=%s, name=%s, nameAndNumber=%s, label=%s, person_id=%d }",
mNumber, mName, mNameAndNumber, mLabel, mPersonId);
}
public interface UpdateListener {
public void onUpdate(Contact updated);
}
private Contact(String number) {
mName = "";
setNumber(number);
mNumberIsModified = false;
mLabel = "";
mPersonId = 0;
mPresenceResId = 0;
mIsStale = true;
}
private static void logWithTrace(String msg, Object... format) {
Thread current = Thread.currentThread();
StackTraceElement[] stack = current.getStackTrace();
StringBuilder sb = new StringBuilder();
sb.append("[");
sb.append(current.getId());
sb.append("] ");
sb.append(String.format(msg, format));
sb.append(" <- ");
int stop = stack.length > 7 ? 7 : stack.length;
for (int i = 3; i < stop; i++) {
String methodName = stack[i].getMethodName();
sb.append(methodName);
if ((i+1) != stop) {
sb.append(" <- ");
}
}
Log.d(TAG, sb.toString());
}
public static Contact get(String number, boolean canBlock) {
if (V) logWithTrace("get(%s, %s)", number, canBlock);
if (TextUtils.isEmpty(number)) {
throw new IllegalArgumentException("Contact.get called with null or empty number");
}
Contact contact = Cache.get(number);
if (contact == null) {
contact = new Contact(number);
Cache.put(contact);
}
if (contact.mIsStale) {
asyncUpdateContact(contact, canBlock);
}
return contact;
}
public static void invalidateCache() {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("invalidateCache");
}
// force invalidate the contact info cache, so we will query for fresh info again.
// This is so we can get fresh presence info again on the screen, since the presence
// info changes pretty quickly, and we can't get change notifications when presence is
// updated in the ContactsProvider.
ContactInfoCache.getInstance().invalidateCache();
// While invalidating our local Cache doesn't remove the contacts, it will mark them
// stale so the next time we're asked for a particular contact, we'll return that
// stale contact and at the same time, fire off an asyncUpdateContact to update
// that contact's info in the background. UI elements using the contact typically
// call addListener() so they immediately get notified when the contact has been
// updated with the latest info. They redraw themselves when we call the
// listener's onUpdate().
Cache.invalidate();
}
private static String emptyIfNull(String s) {
return (s != null ? s : "");
}
private static boolean contactChanged(Contact orig, ContactInfoCache.CacheEntry newEntry) {
// The phone number should never change, so don't bother checking.
// TODO: Maybe update it if it has gotten longer, i.e. 650-234-5678 -> +16502345678?
String oldName = emptyIfNull(orig.mName);
String newName = emptyIfNull(newEntry.name);
if (!oldName.equals(newName)) {
if (V) Log.d(TAG, String.format("name changed: %s -> %s", oldName, newName));
return true;
}
String oldLabel = emptyIfNull(orig.mLabel);
String newLabel = emptyIfNull(newEntry.phoneLabel);
if (!oldLabel.equals(newLabel)) {
if (V) Log.d(TAG, String.format("label changed: %s -> %s", oldLabel, newLabel));
return true;
}
if (orig.mPersonId != newEntry.person_id) {
if (V) Log.d(TAG, "person id changed");
return true;
}
if (orig.mPresenceResId != newEntry.presenceResId) {
if (V) Log.d(TAG, "presence changed");
return true;
}
return false;
}
/**
* Handles the special case where the local ("Me") number is being looked up.
* Updates the contact with the "me" name and returns true if it is the
* local number, no-ops and returns false if it is not.
*/
private static boolean handleLocalNumber(Contact c) {
if (MessageUtils.isLocalNumber(c.mNumber)) {
c.mName = Cache.getContext().getString(com.android.internal.R.string.me);
c.updateNameAndNumber();
return true;
}
return false;
}
private static void asyncUpdateContact(final Contact c, boolean canBlock) {
if (c == null) {
return;
}
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("asyncUpdateContact for " + c.toString() + " canBlock: " + canBlock +
" isStale: " + c.mIsStale);
}
Runnable r = new Runnable() {
public void run() {
updateContact(c);
}
};
if (canBlock) {
r.run();
} else {
sTaskStack.push(r);
}
}
private static void updateContact(final Contact c) {
if (c == null) {
return;
}
// Check to see if this is the local ("me") number.
if (handleLocalNumber(c)) {
return;
}
ContactInfoCache cache = ContactInfoCache.getInstance();
ContactInfoCache.CacheEntry entry = cache.getContactInfo(c.mNumber);
synchronized (Cache.getInstance()) {
if (contactChanged(c, entry)) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("updateContact: contact changed for " + entry.name);
}
//c.mNumber = entry.phoneNumber;
c.mName = entry.name;
c.updateNameAndNumber();
c.mLabel = entry.phoneLabel;
c.mPersonId = entry.person_id;
c.mPresenceResId = entry.presenceResId;
c.mPresenceText = entry.presenceText;
c.mAvatar = entry.mAvatar;
c.mIsStale = false;
for (UpdateListener l : c.mListeners) {
if (V) Log.d(TAG, "updating " + l);
l.onUpdate(c);
}
+ } else {
+ c.mIsStale = false;
}
}
}
public static String formatNameAndNumber(String name, String number) {
// Format like this: Mike Cleron <(650) 555-1234>
// Erick Tseng <(650) 555-1212>
// Tutankhamun <[email protected]>
// (408) 555-1289
String formattedNumber = number;
if (!Mms.isEmailAddress(number)) {
formattedNumber = PhoneNumberUtils.formatNumber(number);
}
if (!TextUtils.isEmpty(name) && !name.equals(number)) {
return name + " <" + formattedNumber + ">";
} else {
return formattedNumber;
}
}
public synchronized String getNumber() {
return mNumber;
}
public synchronized void setNumber(String number) {
mNumber = number;
updateNameAndNumber();
mNumberIsModified = true;
}
public boolean isNumberModified() {
return mNumberIsModified;
}
public void setIsNumberModified(boolean flag) {
mNumberIsModified = flag;
}
public synchronized String getName() {
if (TextUtils.isEmpty(mName)) {
return mNumber;
} else {
return mName;
}
}
public synchronized String getNameAndNumber() {
return mNameAndNumber;
}
private void updateNameAndNumber() {
mNameAndNumber = formatNameAndNumber(mName, mNumber);
}
public synchronized long getRecipientId() {
return mRecipientId;
}
public synchronized void setRecipientId(long id) {
mRecipientId = id;
}
public synchronized String getLabel() {
return mLabel;
}
public synchronized Uri getUri() {
return ContentUris.withAppendedId(Contacts.CONTENT_URI, mPersonId);
}
public long getPersonId() {
return mPersonId;
}
public synchronized int getPresenceResId() {
return mPresenceResId;
}
public synchronized boolean existsInDatabase() {
return (mPersonId > 0);
}
public synchronized void addListener(UpdateListener l) {
boolean added = mListeners.add(l);
if (V && added) dumpListeners();
}
public synchronized void removeListener(UpdateListener l) {
boolean removed = mListeners.remove(l);
if (V && removed) dumpListeners();
}
public synchronized void dumpListeners() {
int i=0;
Log.i(TAG, "[Contact] dumpListeners(" + mNumber + ") size=" + mListeners.size());
for (UpdateListener listener : mListeners) {
Log.i(TAG, "["+ (i++) + "]" + listener);
}
}
public synchronized boolean isEmail() {
return Mms.isEmailAddress(mNumber);
}
public String getPresenceText() {
return mPresenceText;
}
public Drawable getAvatar(Drawable defaultValue) {
return mAvatar != null ? mAvatar : defaultValue;
}
public static void init(final Context context) {
Cache.init(context);
RecipientIdCache.init(context);
// it maybe too aggressive to listen for *any* contact changes, and rebuild MMS contact
// cache each time that occurs. Unless we can get targeted updates for the contacts we
// care about(which probably won't happen for a long time), we probably should just
// invalidate cache peoridically, or surgically.
/*
context.getContentResolver().registerContentObserver(
Contacts.CONTENT_URI, true, sContactsObserver);
*/
}
public static void dump() {
Cache.dump();
}
public static void startPresenceObserver() {
Cache.getContext().getContentResolver().registerContentObserver(
Presence.CONTENT_URI, true, sPresenceObserver);
}
public static void stopPresenceObserver() {
Cache.getContext().getContentResolver().unregisterContentObserver(sPresenceObserver);
}
private static class Cache {
private static Cache sInstance;
static Cache getInstance() { return sInstance; }
private final List<Contact> mCache;
private final Context mContext;
private Cache(Context context) {
mCache = new ArrayList<Contact>();
mContext = context;
}
static void init(Context context) {
sInstance = new Cache(context);
}
static Context getContext() {
return sInstance.mContext;
}
static void dump() {
synchronized (sInstance) {
Log.d(TAG, "**** Contact cache dump ****");
for (Contact c : sInstance.mCache) {
Log.d(TAG, c.toString());
}
}
}
private static Contact getEmail(String number) {
synchronized (sInstance) {
for (Contact c : sInstance.mCache) {
if (number.equalsIgnoreCase(c.mNumber)) {
return c;
}
}
return null;
}
}
static Contact get(String number) {
if (Mms.isEmailAddress(number))
return getEmail(number);
synchronized (sInstance) {
for (Contact c : sInstance.mCache) {
// if the numbers are an exact match (i.e. Google SMS), or if the phone
// number comparison returns a match, return the contact.
if (number.equals(c.mNumber) || PhoneNumberUtils.compare(number, c.mNumber)) {
return c;
}
}
return null;
}
}
static void put(Contact c) {
synchronized (sInstance) {
// We update cache entries in place so people with long-
// held references get updated.
if (get(c.mNumber) != null) {
throw new IllegalStateException("cache already contains " + c);
}
sInstance.mCache.add(c);
}
}
static String[] getNumbers() {
synchronized (sInstance) {
String[] numbers = new String[sInstance.mCache.size()];
int i = 0;
for (Contact c : sInstance.mCache) {
numbers[i++] = c.getNumber();
}
return numbers;
}
}
static List<Contact> getContacts() {
synchronized (sInstance) {
return new ArrayList<Contact>(sInstance.mCache);
}
}
static void invalidate() {
// Don't remove the contacts. Just mark them stale so we'll update their
// info, particularly their presence.
synchronized (sInstance) {
for (Contact c : sInstance.mCache) {
c.mIsStale = true;
}
}
}
}
private static void log(String msg) {
Log.d(TAG, msg);
}
}
| true | true | private static void updateContact(final Contact c) {
if (c == null) {
return;
}
// Check to see if this is the local ("me") number.
if (handleLocalNumber(c)) {
return;
}
ContactInfoCache cache = ContactInfoCache.getInstance();
ContactInfoCache.CacheEntry entry = cache.getContactInfo(c.mNumber);
synchronized (Cache.getInstance()) {
if (contactChanged(c, entry)) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("updateContact: contact changed for " + entry.name);
}
//c.mNumber = entry.phoneNumber;
c.mName = entry.name;
c.updateNameAndNumber();
c.mLabel = entry.phoneLabel;
c.mPersonId = entry.person_id;
c.mPresenceResId = entry.presenceResId;
c.mPresenceText = entry.presenceText;
c.mAvatar = entry.mAvatar;
c.mIsStale = false;
for (UpdateListener l : c.mListeners) {
if (V) Log.d(TAG, "updating " + l);
l.onUpdate(c);
}
}
}
}
| private static void updateContact(final Contact c) {
if (c == null) {
return;
}
// Check to see if this is the local ("me") number.
if (handleLocalNumber(c)) {
return;
}
ContactInfoCache cache = ContactInfoCache.getInstance();
ContactInfoCache.CacheEntry entry = cache.getContactInfo(c.mNumber);
synchronized (Cache.getInstance()) {
if (contactChanged(c, entry)) {
if (Log.isLoggable(LogTag.APP, Log.VERBOSE)) {
log("updateContact: contact changed for " + entry.name);
}
//c.mNumber = entry.phoneNumber;
c.mName = entry.name;
c.updateNameAndNumber();
c.mLabel = entry.phoneLabel;
c.mPersonId = entry.person_id;
c.mPresenceResId = entry.presenceResId;
c.mPresenceText = entry.presenceText;
c.mAvatar = entry.mAvatar;
c.mIsStale = false;
for (UpdateListener l : c.mListeners) {
if (V) Log.d(TAG, "updating " + l);
l.onUpdate(c);
}
} else {
c.mIsStale = false;
}
}
}
|
diff --git a/src/xmlvm2objc/compat-lib/java/org/xmlvm/iphone/NSObject.java b/src/xmlvm2objc/compat-lib/java/org/xmlvm/iphone/NSObject.java
index aa3b3a0d..16840449 100644
--- a/src/xmlvm2objc/compat-lib/java/org/xmlvm/iphone/NSObject.java
+++ b/src/xmlvm2objc/compat-lib/java/org/xmlvm/iphone/NSObject.java
@@ -1,71 +1,76 @@
/*
* Copyright (c) 2004-2009 XMLVM --- An XML-based Programming Language
*
* 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., 675 Mass
* Ave, Cambridge, MA 02139, USA.
*
* For more information, visit the XMLVM Home Page at http://www.xmlvm.org
*/
package org.xmlvm.iphone;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import javax.swing.SwingUtilities;
public class NSObject {
public static void performSelectorOnMainThread(final Object target, final String method,
final Object arg, boolean waitUntilDone) {
Runnable runnable = new Runnable() {
@Override
public void run() {
Class<?>[] paramTypes = { Object.class };
Object[] params = { arg };
Class<?> targetClass = target.getClass();
Method m = null;
try {
m = targetClass.getMethod(method, paramTypes);
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
try {
m.invoke(target, params);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
};
try {
- if (waitUntilDone) {
- SwingUtilities.invokeAndWait(runnable);
+ if (SwingUtilities.isEventDispatchThread()) {
+ // TODO should run this runnable in a thread if waitUntilDone == false
+ runnable.run();
} else {
- SwingUtilities.invokeLater(runnable);
+ if (waitUntilDone) {
+ SwingUtilities.invokeAndWait(runnable);
+ } else {
+ SwingUtilities.invokeLater(runnable);
+ }
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
| false | true | public static void performSelectorOnMainThread(final Object target, final String method,
final Object arg, boolean waitUntilDone) {
Runnable runnable = new Runnable() {
@Override
public void run() {
Class<?>[] paramTypes = { Object.class };
Object[] params = { arg };
Class<?> targetClass = target.getClass();
Method m = null;
try {
m = targetClass.getMethod(method, paramTypes);
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
try {
m.invoke(target, params);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
};
try {
if (waitUntilDone) {
SwingUtilities.invokeAndWait(runnable);
} else {
SwingUtilities.invokeLater(runnable);
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
| public static void performSelectorOnMainThread(final Object target, final String method,
final Object arg, boolean waitUntilDone) {
Runnable runnable = new Runnable() {
@Override
public void run() {
Class<?>[] paramTypes = { Object.class };
Object[] params = { arg };
Class<?> targetClass = target.getClass();
Method m = null;
try {
m = targetClass.getMethod(method, paramTypes);
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
try {
m.invoke(target, params);
} catch (IllegalArgumentException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
};
try {
if (SwingUtilities.isEventDispatchThread()) {
// TODO should run this runnable in a thread if waitUntilDone == false
runnable.run();
} else {
if (waitUntilDone) {
SwingUtilities.invokeAndWait(runnable);
} else {
SwingUtilities.invokeLater(runnable);
}
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
|
diff --git a/DbstarLauncher/src/com/dbstar/app/GDHDMovieActivity.java b/DbstarLauncher/src/com/dbstar/app/GDHDMovieActivity.java
index a9c3f0ec..d64daaff 100644
--- a/DbstarLauncher/src/com/dbstar/app/GDHDMovieActivity.java
+++ b/DbstarLauncher/src/com/dbstar/app/GDHDMovieActivity.java
@@ -1,549 +1,552 @@
package com.dbstar.app;
import java.util.LinkedList;
import java.util.List;
import com.dbstar.R;
import com.dbstar.app.media.GDPlayerUtil;
import com.dbstar.model.ContentData;
import com.dbstar.model.EventData;
import com.dbstar.model.GDCommon;
import com.dbstar.service.GDDataProviderService;
import com.dbstar.model.Movie;
import com.dbstar.model.GDDVBDataContract.Content;
import com.dbstar.widget.GDAdapterView;
import com.dbstar.widget.GDGridView;
import com.dbstar.widget.GDAdapterView.OnItemSelectedListener;
import com.dbstar.widget.GDScrollBar;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class GDHDMovieActivity extends GDBaseActivity {
private static final String TAG = "GDHDMovieActivity";
private static final int COLUMN_ITEMS = 6;
private static final int PAGE_ITEMS = 12;
private static final int PageSize = PAGE_ITEMS;
int mPageNumber = 0;
int mPageCount = 0;
int mTotalCount = 0;
String mColumnId;
List<Movie[]> mPageDatas;
GDGridView mSmallThumbnailView;
MovieAdapter mAdapter;
int mSeletedItemIndex = 0;
GDScrollBar mScrollBar = null;
View mSelectedView = null;
boolean mReachPageEnd = false;
TextView mPageNumberView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hdmovie_view);
Intent intent = getIntent();
mColumnId = intent.getStringExtra(Content.COLUMN_ID);
mMenuPath = intent.getStringExtra(INTENT_KEY_MENUPATH);
Log.d(TAG, "column id = " + mColumnId);
Log.d(TAG, "menu path = " + mMenuPath);
mPageDatas = new LinkedList<Movie[]>();
initializeView();
}
protected void initializeView() {
super.initializeView();
mPageNumberView = (TextView) findViewById(R.id.pageNumberView);
mScrollBar = (GDScrollBar) findViewById(R.id.scrollbar);
mSmallThumbnailView = (GDGridView) findViewById(R.id.gridview);
mSmallThumbnailView
.setOnItemSelectedListener(mThumbnailSelectedListener);
mAdapter = new MovieAdapter(this);
mSmallThumbnailView.setAdapter(mAdapter);
mSmallThumbnailView.setOnKeyListener(mThumbnailOnKeyListener);
mSmallThumbnailView.requestFocus();
mPageNumberView.setText(formPageText(0, 0));
}
public void onStart() {
super.onStart();
if (mAdapter.getCount() > 0) {
mSmallThumbnailView.setSelection(mSeletedItemIndex);
}
showMenuPath(mMenuPath.split(MENU_STRING_DELIMITER));
}
public void onDestroy() {
super.onDestroy();
for (int i = 0; mPageDatas != null && i < mPageDatas.size(); i++) {
Movie[] movies = mPageDatas.get(i);
for (int j = 0; j < movies.length; j++) {
if (movies[j].Thumbnail != null) {
movies[j].Thumbnail.recycle();
}
}
}
}
public void onServiceStart() {
super.onServiceStart();
mService.getPublications(this, mColumnId);
}
private void loadPrevPage() {
if (mPageNumber > 0) {
Log.d(TAG, "loadPrevPage");
mPageNumber--;
mPageNumberView.setText(formPageText(mPageNumber + 1, mPageCount));
Movie[] movies = mPageDatas.get(mPageNumber);
mAdapter.setDataSet(movies);
mSmallThumbnailView.setSelection(movies.length - 1);
mAdapter.notifyDataSetChanged();
mScrollBar.setPosition(mPageNumber);
}
}
private void loadNextPage() {
Log.d(TAG, "loadNextPage");
if ((mPageNumber + 1) < mPageDatas.size()) {
mPageNumber++;
mPageNumberView.setText(formPageText(mPageNumber + 1, mPageCount));
Movie[] movies = mPageDatas.get(mPageNumber);
mAdapter.setDataSet(movies);
mSmallThumbnailView.setSelection(0);
mAdapter.notifyDataSetChanged();
mScrollBar.setPosition(mPageNumber);
}
}
private Movie getSelectedMovie() {
int currentItem = mSmallThumbnailView.getSelectedItemPosition();
Movie[] movies = mPageDatas.get(mPageNumber);
return movies[currentItem];
}
private void playMovie() {
Log.d(TAG, "playMovie");
Movie movie = getSelectedMovie();
String file = mService.getMediaFile(movie.Content);
String drmFile = mService.getDRMFile(movie.Content);
if (file == null || file.isEmpty()) {
alertFileNotExist();
return;
}
if (drmFile != null && !drmFile.isEmpty() && !isSmartcardReady()) {
alertSmartcardInfo();
return;
}
GDPlayerUtil.playVideo(this, null, movie.Content, file, drmFile);
}
public void updateData(int type, Object key, Object data) {
if (type == GDDataProviderService.REQUESTTYPE_GETPUBLICATION) {
ContentData[] contents = (ContentData[]) data;
Log.d(TAG, "update ");
if (contents != null && contents.length > 0) {
Log.d(TAG, "update " + contents.length);
mTotalCount = contents.length;
mPageCount = mTotalCount / PageSize;
int index = 0;
for (int i = 0; i < mPageCount; i++) {
Movie[] movies = new Movie[PageSize];
for (int j = 0; j < PageSize; j++, index++) {
movies[j] = new Movie();
movies[j].Content = contents[index];
}
mPageDatas.add(i, movies);
}
int remain = mTotalCount % PageSize;
if (remain > 0) {
mPageCount += 1;
Movie[] movies = new Movie[remain];
for (int i = 0; i < remain; i++, index++) {
movies[i] = new Movie();
movies[i].Content = contents[index];
}
mPageDatas.add(movies);
}
mPageNumber = 0;
// update views
updateViews(mPageDatas.get(mPageNumber));
Log.d(TAG, "update mPageCount " + mPageCount);
mRequestPageIndex = 0;
requestPageData(mRequestPageIndex);
}
}
}
int mRequestPageIndex = -1;
int mRequestCount = 0;
void requestPageData(int pageNumber) {
Movie[] movies = mPageDatas.get(pageNumber);
mRequestCount = movies.length;
for (int j = 0; j < movies.length; j++) {
mService.getDetailsData(this, pageNumber, j, movies[j].Content);
}
}
public void updateData(int type, int param1, int param2, Object data) {
if (type == GDDataProviderService.REQUESTTYPE_GETDETAILSDATA) {
int pageNumber = param1;
int index = param2;
Log.d(TAG, "updateData page number = " + pageNumber + " index = "
+ index);
mService.getImage(this, pageNumber, index, (ContentData) data);
mRequestCount--;
if (mRequestCount == 0) {
mRequestPageIndex++;
if (mRequestPageIndex < mPageCount) {
requestPageData(mRequestPageIndex);
}
}
} else if (type == GDDataProviderService.REQUESTTYPE_GETIMAGE) {
int pageNumber = param1;
int index = param2;
Log.d(TAG, "updateData page number = " + pageNumber + " index = "
+ index);
Movie[] movies = mPageDatas.get(pageNumber);
movies[index].Thumbnail = (Bitmap) data;
if (pageNumber == mPageNumber)
mAdapter.notifyDataSetChanged();
}
}
@Override
public void notifyEvent(int type, Object event) {
super.notifyEvent(type, event);
if (type == EventData.EVENT_DELETE) {
EventData.DeleteEvent deleteEvent = (EventData.DeleteEvent) event;
String publicationId = deleteEvent.PublicationId;
Movie[] movies = mPageDatas.get(mPageNumber);
int i = 0;
boolean found = false;
for (i = 0; i < movies.length; i++) {
ContentData content = movies[i].Content;
if (content.Id.equals(publicationId)) {
found = true;
break;
}
}
if (found) {
movePageItems(mPageNumber, i);
}
mPageCount = mPageDatas.size();
if (mPageCount > 0) {
// delete last page
if (mPageNumber == mPageCount) {
mPageNumber = mPageCount - 1;
}
movies = mPageDatas.get(mPageNumber);
} else {
movies = null;
}
updateViews(movies);
} else if (type == EventData.EVENT_UPDATE_PROPERTY) {
EventData.UpdatePropertyEvent updateEvent = (EventData.UpdatePropertyEvent) event;
String publicationId = updateEvent.PublicationId;
Movie[] movies = mPageDatas.get(mPageNumber);
int i = 0;
boolean found = false;
for (i = 0; i < movies.length; i++) {
ContentData content = movies[i].Content;
if (content.Id.equals(publicationId)) {
found = true;
break;
}
}
if (found) {
ContentData content = movies[i].Content;
updatePropery(content, updateEvent.PropertyName,
updateEvent.PropertyValue);
}
}
}
private void updatePropery(ContentData content, String propery, Object value) {
if (propery.equals(GDCommon.KeyBookmark)) {
content.BookMark = (Integer)value;
}
}
private void movePageItems(int pageNumber, int start) {
Movie[] movies = mPageDatas.get(pageNumber);
if (start == movies.length - 1 && start == 0) {
// the deleted item is the last one
// there is only one item in this page
mPageDatas.remove(pageNumber);
}
for (int i = start; i < movies.length - 1; i++) {
movies[i] = movies[i + 1];
movies[i + 1] = null;
}
if (pageNumber < mPageCount - 1) {
Movie[] nextMovies = mPageDatas.get(pageNumber + 1);
movies[movies.length - 1] = nextMovies[0];
movePageItems(pageNumber + 1, 0);
} else {
// this is the last page, remove the last null item
Movie[] newMovies = new Movie[movies.length - 1];
for (int i = 0; i < newMovies.length; i++) {
newMovies[i] = movies[i];
}
mPageDatas.set(pageNumber, newMovies);
}
}
private void updateViews(Movie[] movies) {
mPageNumberView.setText(formPageText(mPageNumber + 1, mPageCount));
mScrollBar.setRange(mPageCount);
mScrollBar.setPosition(mPageNumber);
mAdapter.setDataSet(movies);
mSmallThumbnailView.setSelection(0);
mAdapter.notifyDataSetChanged();
}
private class MovieAdapter extends BaseAdapter {
private Movie[] mDataSet = null;
public class ViewHolder {
// TextView titleView;
ImageView thumbnailView;
}
public MovieAdapter(Context context) {
}
public void setDataSet(Movie[] dataSet) {
mDataSet = dataSet;
}
@Override
public int getCount() {
int count = 0;
if (mDataSet != null) {
count = mDataSet.length;
}
return count;
}
@Override
public Object getItem(int position) {
return null;
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = new ViewHolder();
if (mSmallThumbnailView.getSelectedItemPosition() == position) {
if (mSelectedView == null) {
LayoutInflater inflater = getLayoutInflater();
mSelectedView = inflater.inflate(
R.layout.small_thumbnail_item_focused, parent,
false);
// holder.titleView = (TextView) mSelectedView
// .findViewById(R.id.item_text);
holder.thumbnailView = (ImageView) mSelectedView
.findViewById(R.id.thumbnail);
mSelectedView.setTag(holder);
}
if (convertView != mSelectedView) {
convertView = mSelectedView;
}
} else {
if (convertView == mSelectedView) {
convertView = null;
}
}
if (null == convertView) {
LayoutInflater inflater = getLayoutInflater();
convertView = inflater.inflate(
R.layout.small_thumbnail_item_normal, parent, false);
// holder.titleView = (TextView) convertView
// .findViewById(R.id.item_text);
holder.thumbnailView = (ImageView) convertView
.findViewById(R.id.thumbnail);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
Bitmap thumbnail = mDataSet[position].Thumbnail;
holder.thumbnailView.setImageBitmap(thumbnail);
// holder.titleView.setText(mDataSet[position].Content.Name);
return convertView;
}
}
OnItemSelectedListener mThumbnailSelectedListener = new OnItemSelectedListener() {
@Override
public void onItemSelected(GDAdapterView<?> parent, View view,
int position, long id) {
Log.d(TAG, "mSmallThumbnailView selected = " + position);
mSeletedItemIndex = position;
}
@Override
public void onNothingSelected(GDAdapterView<?> parent) {
}
};
View.OnKeyListener mThumbnailOnKeyListener = new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
Log.d(TAG, "onKey " + keyCode);
boolean ret = false;
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT: {
int currentItem = mSmallThumbnailView
.getSelectedItemPosition();
if (currentItem == PAGE_ITEMS / 2) {
mSmallThumbnailView.setSelection(currentItem - 1);
ret = true;
} else if (currentItem == 0) {
// mSmallThumbnailView
// .setSelection(mAdapter.getCount() - 1);
loadPrevPage();
ret = true;
} else {
}
break;
}
case KeyEvent.KEYCODE_DPAD_RIGHT: {
int currentItem = mSmallThumbnailView
.getSelectedItemPosition();
if (currentItem == (PAGE_ITEMS / 2 - 1)) {
if (currentItem < (mAdapter.getCount() - 1)) {
mSmallThumbnailView.setSelection(currentItem + 1);
ret = true;
}
} else if (currentItem == (mAdapter.getCount() - 1)) {
- // mSmallThumbnailView.setSelection(0);
- loadNextPage();
+ if (currentItem == (PageSize - 1)) {
+ loadNextPage();
+ } else {
+ mSmallThumbnailView.setSelection(0);
+ }
ret = true;
} else {
}
break;
}
case KeyEvent.KEYCODE_DPAD_UP: {
int currentItem = mSmallThumbnailView
.getSelectedItemPosition();
if (currentItem < COLUMN_ITEMS) {
loadPrevPage();
ret = true;
}
break;
}
case KeyEvent.KEYCODE_DPAD_DOWN: {
int currentItem = mSmallThumbnailView
.getSelectedItemPosition();
if (currentItem >= (PAGE_ITEMS - COLUMN_ITEMS)) {
loadNextPage();
ret = true;
}
break;
}
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER: {
playMovie();
ret = true;
break;
}
default:
break;
}
}
return ret;
}
};
}
| true | true | public boolean onKey(View v, int keyCode, KeyEvent event) {
Log.d(TAG, "onKey " + keyCode);
boolean ret = false;
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT: {
int currentItem = mSmallThumbnailView
.getSelectedItemPosition();
if (currentItem == PAGE_ITEMS / 2) {
mSmallThumbnailView.setSelection(currentItem - 1);
ret = true;
} else if (currentItem == 0) {
// mSmallThumbnailView
// .setSelection(mAdapter.getCount() - 1);
loadPrevPage();
ret = true;
} else {
}
break;
}
case KeyEvent.KEYCODE_DPAD_RIGHT: {
int currentItem = mSmallThumbnailView
.getSelectedItemPosition();
if (currentItem == (PAGE_ITEMS / 2 - 1)) {
if (currentItem < (mAdapter.getCount() - 1)) {
mSmallThumbnailView.setSelection(currentItem + 1);
ret = true;
}
} else if (currentItem == (mAdapter.getCount() - 1)) {
// mSmallThumbnailView.setSelection(0);
loadNextPage();
ret = true;
} else {
}
break;
}
case KeyEvent.KEYCODE_DPAD_UP: {
int currentItem = mSmallThumbnailView
.getSelectedItemPosition();
if (currentItem < COLUMN_ITEMS) {
loadPrevPage();
ret = true;
}
break;
}
case KeyEvent.KEYCODE_DPAD_DOWN: {
int currentItem = mSmallThumbnailView
.getSelectedItemPosition();
if (currentItem >= (PAGE_ITEMS - COLUMN_ITEMS)) {
loadNextPage();
ret = true;
}
break;
}
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER: {
playMovie();
ret = true;
break;
}
default:
break;
}
}
return ret;
}
| public boolean onKey(View v, int keyCode, KeyEvent event) {
Log.d(TAG, "onKey " + keyCode);
boolean ret = false;
int action = event.getAction();
if (action == KeyEvent.ACTION_DOWN) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_LEFT: {
int currentItem = mSmallThumbnailView
.getSelectedItemPosition();
if (currentItem == PAGE_ITEMS / 2) {
mSmallThumbnailView.setSelection(currentItem - 1);
ret = true;
} else if (currentItem == 0) {
// mSmallThumbnailView
// .setSelection(mAdapter.getCount() - 1);
loadPrevPage();
ret = true;
} else {
}
break;
}
case KeyEvent.KEYCODE_DPAD_RIGHT: {
int currentItem = mSmallThumbnailView
.getSelectedItemPosition();
if (currentItem == (PAGE_ITEMS / 2 - 1)) {
if (currentItem < (mAdapter.getCount() - 1)) {
mSmallThumbnailView.setSelection(currentItem + 1);
ret = true;
}
} else if (currentItem == (mAdapter.getCount() - 1)) {
if (currentItem == (PageSize - 1)) {
loadNextPage();
} else {
mSmallThumbnailView.setSelection(0);
}
ret = true;
} else {
}
break;
}
case KeyEvent.KEYCODE_DPAD_UP: {
int currentItem = mSmallThumbnailView
.getSelectedItemPosition();
if (currentItem < COLUMN_ITEMS) {
loadPrevPage();
ret = true;
}
break;
}
case KeyEvent.KEYCODE_DPAD_DOWN: {
int currentItem = mSmallThumbnailView
.getSelectedItemPosition();
if (currentItem >= (PAGE_ITEMS - COLUMN_ITEMS)) {
loadNextPage();
ret = true;
}
break;
}
case KeyEvent.KEYCODE_DPAD_CENTER:
case KeyEvent.KEYCODE_ENTER: {
playMovie();
ret = true;
break;
}
default:
break;
}
}
return ret;
}
|
diff --git a/src/com/menny/android/anysoftkeyboard/CandidateView.java b/src/com/menny/android/anysoftkeyboard/CandidateView.java
index 1130a642..562377e3 100644
--- a/src/com/menny/android/anysoftkeyboard/CandidateView.java
+++ b/src/com/menny/android/anysoftkeyboard/CandidateView.java
@@ -1,556 +1,556 @@
/*
* Copyright (C) 2008-2009 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.menny.android.anysoftkeyboard;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.PopupWindow;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.menny.android.anysoftkeyboard.R;
public class CandidateView extends View {
private static final boolean ms_requiresRtlWorkaround;
static
{
//Determine whether this device has the fix for RTL in the suggestions list
ms_requiresRtlWorkaround = !android.os.Build.MODEL.toLowerCase().contains("galaxy");
}
private static final int OUT_OF_BOUNDS = -1;
private static final List<CharSequence> EMPTY_LIST = new ArrayList<CharSequence>();
private AnySoftKeyboard mService;
private List<CharSequence> mSuggestions = EMPTY_LIST;
private boolean mShowingCompletions;
private CharSequence mSelectedString;
private int mSelectedIndex;
private int mTouchX = OUT_OF_BOUNDS;
private Drawable mSelectionHighlight;
private boolean mTypedWordValid;
private boolean mHaveMinimalSuggestion;
private Rect mBgPadding;
private TextView mPreviewText;
private PopupWindow mPreviewPopup;
private int mCurrentWordIndex;
private Drawable mDivider;
private static final int MAX_SUGGESTIONS = 32;
private static final int SCROLL_PIXELS = 20;
private static final int MSG_REMOVE_PREVIEW = 1;
private static final int MSG_REMOVE_THROUGH_PREVIEW = 2;
private int[] mWordWidth = new int[MAX_SUGGESTIONS];
private int[] mWordX = new int[MAX_SUGGESTIONS];
private int mPopupPreviewX;
private int mPopupPreviewY;
private static final int X_GAP = 10;
private int mColorNormal;
private int mColorRecommended;
private int mColorOther;
private Paint mPaint;
private int mDescent;
//will be used to determine if we are scrolling or selecting.
private boolean mScrolling;
//will tell us what is the target scroll X, so we know to stop
private int mTargetScrollX;
private int mTotalWidth;
private GestureDetector mGestureDetector;
Handler mHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MSG_REMOVE_PREVIEW:
mPreviewText.setVisibility(GONE);
break;
case MSG_REMOVE_THROUGH_PREVIEW:
mPreviewText.setVisibility(GONE);
if (mTouchX != OUT_OF_BOUNDS) {
removeHighlight();
}
break;
}
}
};
private int mScrollX;
/**
* Construct a CandidateView for showing suggested words for completion.
* @param context
* @param attrs
*/
public CandidateView(Context context, AttributeSet attrs) {
super(context, attrs);
mSelectionHighlight = context.getResources().getDrawable(
R.drawable.highlight_pressed);
LayoutInflater inflate =
(LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mPreviewPopup = new PopupWindow(context);
mPreviewText = (TextView) inflate.inflate(R.layout.candidate_preview, null);
mPreviewPopup.setWindowLayoutMode(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
mPreviewPopup.setContentView(mPreviewText);
mPreviewPopup.setBackgroundDrawable(null);
mColorNormal = context.getResources().getColor(R.color.candidate_normal);
mColorRecommended = context.getResources().getColor(R.color.candidate_recommended);
mColorOther = context.getResources().getColor(R.color.candidate_other);
mDivider = context.getResources().getDrawable(R.drawable.keyboard_suggest_strip_divider);
mPaint = new Paint();
mPaint.setColor(mColorNormal);
mPaint.setAntiAlias(true);//it is just MUCH better looking
mPaint.setTextSize(mPreviewText.getTextSize());
mPaint.setStrokeWidth(0);
mDescent = (int) mPaint.descent();
mGestureDetector = new GestureDetector(new GestureDetector.SimpleOnGestureListener() {
@Override
public void onLongPress(MotionEvent me) {
if (mSuggestions.size() > 0) {
if (me.getX() + mScrollX < mWordWidth[0] && mScrollX < 10) {
longPressFirstWord();
}
}
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
final int width = getWidth();
mScrolling = true;
mScrollX += (int) distanceX;
if (mScrollX < 0) {
mScrollX = 0;
}
if (distanceX > 0 && mScrollX + width > mTotalWidth) {
mScrollX -= (int) distanceX;
}
//fixing the touchX too
mTouchX += mScrollX;
//it is at the target
mTargetScrollX = mScrollX;
hidePreview();
invalidate();
return true;
}
});
setHorizontalFadingEdgeEnabled(true);
setWillNotDraw(false);
//I'm doing my own scroll icons.
setHorizontalScrollBarEnabled(false);
setVerticalScrollBarEnabled(false);
mScrollX = 0;
}
/**
* A connection back to the service to communicate with the text field
* @param listener
*/
public void setService(AnySoftKeyboard listener) {
mService = listener;
}
@Override
public int computeHorizontalScrollRange() {
return mTotalWidth;
}
/**
* If the canvas is null, then only touch calculations are performed to pick the target
* candidate.
*/
@Override
protected void onDraw(Canvas canvas) {
if (canvas != null) {
super.onDraw(canvas);
}
mTotalWidth = 0;
if (mSuggestions == null) return;
final int height = getHeight();
if (mBgPadding == null) {
mBgPadding = new Rect(0, 0, 0, 0);
if (getBackground() != null) {
getBackground().getPadding(mBgPadding);
}
mDivider.setBounds(0, mBgPadding.top, mDivider.getIntrinsicWidth(),
mDivider.getIntrinsicHeight());
}
final int count = mSuggestions.size();
//final int width = getWidth();
final Rect bgPadding = mBgPadding;
final Paint paint = mPaint;
final int touchX = mTouchX;
final int scrollX = mScrollX;
int x = 0-scrollX;
- //final boolean scrolled = mScrolling;
+ final boolean scrolling = mScrolling;
final boolean typedWordValid = mTypedWordValid;
final int y = (int) (height + mPaint.getTextSize() - mDescent) / 2;
for (int i = 0; i < count; i++) {
CharSequence suggestion = mSuggestions.get(i);
if ((suggestion == null) || (suggestion.length() == 0)) continue;
paint.setColor(mColorNormal);
//the typed word is the first.
//the valid word is either the first, or the second.
//So, the following if will set the valid word as bold and mColorRecommended
if (mHaveMinimalSuggestion && ((i == 1 && !typedWordValid) || (i == 0 && typedWordValid))) {
paint.setTypeface(Typeface.DEFAULT_BOLD);
paint.setColor(mColorRecommended);
} else if (i != 0) {
//not valid
paint.setTypeface(Typeface.DEFAULT);
paint.setColor(mColorOther);
}
final int wordWidth;
if (mWordWidth[i] != 0) {
//already computed
wordWidth = mWordWidth[i];
} else {
//first time we see the word in the GUI, lets see how long it is
float textWidth = paint.measureText(suggestion, 0, suggestion.length());
wordWidth = (int) (textWidth + (X_GAP * 1.8));
mWordWidth[i] = wordWidth;
}
//x is the incremental X position
mWordX[i] = x;
- //this handles the touched word
- //
- if ((touchX != OUT_OF_BOUNDS) && (touchX >= x) && (touchX < (x + wordWidth))) /*!scrolled &&*/
+ //this handles the touched word popup and highlight.
+ //We want to do those only if we are not scrolling (by finger, e.g.)
+ if ((touchX != OUT_OF_BOUNDS) && (!scrolling) && (touchX >= x) && (touchX < (x + wordWidth)))
{
if (canvas != null) {
canvas.translate(x, 0);
mSelectionHighlight.setBounds(0, bgPadding.top, wordWidth, height);
mSelectionHighlight.draw(canvas);
canvas.translate(-x, 0);
showPreview(i, null);
}
mSelectedString = suggestion;
mSelectedIndex = i;
}
if (canvas != null) {
//Hebrew letters are to be drawn in the other direction. This will be probably be removed in Donut.
//Also, this is not valid for Galaxy (Israel's Cellcom Android)
CharSequence directionCorrectedSuggestion = ms_requiresRtlWorkaround?
workaroundCorrectStringDirection(suggestion) : suggestion;
canvas.drawText(directionCorrectedSuggestion, 0, directionCorrectedSuggestion.length(), x + X_GAP, y, paint);
paint.setColor(mColorOther);
canvas.translate(x + wordWidth, 0);
mDivider.draw(canvas);
canvas.translate(-x - wordWidth, 0);
}
paint.setTypeface(Typeface.DEFAULT);
x += wordWidth;
}
mTotalWidth = x + mScrollX;//with the fixed size
if (mTargetScrollX != mScrollX) {
scrollToTarget();
}
}
private CharSequence workaroundCorrectStringDirection(CharSequence suggestion)
{
//this function is a workaround! In the official 1.5 firmware, there is a RTL bug.
final byte direction = Character.getDirectionality(suggestion.charAt(0));
//Log.d("AnySoftKeyboard", "CandidateView: correctStringDirection: direction:"+direction+" char:"+suggestion.charAt(0));
switch(direction)
{
case Character.DIRECTIONALITY_RIGHT_TO_LEFT:
case Character.DIRECTIONALITY_RIGHT_TO_LEFT_ARABIC:
case Character.DIRECTIONALITY_RIGHT_TO_LEFT_EMBEDDING:
case Character.DIRECTIONALITY_RIGHT_TO_LEFT_OVERRIDE:
String reveresed = "";
for(int charIndex = suggestion.length() - 1; charIndex>=0; charIndex--)
{
reveresed = reveresed + suggestion.charAt(charIndex);
}
//Log.d("AnySoftKeyboard", "CandidateView: correctStringDirection: reversed "+suggestion+" to "+reveresed);
return reveresed;
}
return suggestion;
}
private void scrollToTarget() {
if (mTargetScrollX > mScrollX) {
mScrollX += SCROLL_PIXELS;
if (mScrollX >= mTargetScrollX) {
mScrollX = mTargetScrollX;
requestLayout();
}
} else {
mScrollX -= SCROLL_PIXELS;
if (mScrollX <= mTargetScrollX) {
mScrollX = mTargetScrollX;
requestLayout();
}
}
invalidate();
}
public void setSuggestions(List<CharSequence> suggestions, boolean completions,
boolean typedWordValid, boolean haveMinimalSuggestion) {
clear();
if (suggestions != null) {
mSuggestions = new ArrayList<CharSequence>(suggestions);
}
mShowingCompletions = completions;
mTypedWordValid = typedWordValid;
mScrollX = 0;
mTargetScrollX = 0;
mHaveMinimalSuggestion = haveMinimalSuggestion;
// Compute the total width
onDraw(null);
invalidate();
requestLayout();
}
public void scrollPrev() {
// int i = 0;
// final int count = mSuggestions.size();
// int firstItem = 0; // Actually just before the first item, if at the boundary
// while (i < count) {
// if (mWordX[i] < mScrollX
// && mWordX[i] + mWordWidth[i] >= mScrollX - 1) {
// firstItem = i;
// break;
// }
// i++;
// }
// int leftEdge = mWordX[firstItem] + mWordWidth[firstItem] - getWidth();
// if (leftEdge < 0) leftEdge = 0;
// updateScrollPosition(leftEdge);
//going 3/4 left
updateScrollPosition(mScrollX - (int)(0.75 * getWidth()));
}
public void scrollNext() {
// int i = 0;
// int targetX = mScrollX;
// final int count = mSuggestions.size();
// int rightEdge = mScrollX + getWidth();
// while (i < count)
// {
// if ((mWordX[i] <= rightEdge) && ((mWordX[i] + mWordWidth[i]) >= rightEdge))
// {
// targetX = Math.min(mWordX[i], mTotalWidth - getWidth());
// break;
// }
// i++;
// }
// updateScrollPosition(targetX);
//going 3/4 right
updateScrollPosition(mScrollX + (int)(0.75 * getWidth()));
}
private void updateScrollPosition(int targetX) {
if (targetX < 0)
targetX = 0;
if (targetX > (mTotalWidth - 50))
targetX = (mTotalWidth - 50);
if (targetX != mScrollX) {
// TODO: Animate
mTargetScrollX = targetX;
requestLayout();
invalidate();
mScrolling = true;
}
}
public void clear() {
mSuggestions = EMPTY_LIST;
mTouchX = OUT_OF_BOUNDS;
mSelectedString = null;
mSelectedIndex = -1;
invalidate();
Arrays.fill(mWordWidth, 0);
Arrays.fill(mWordX, 0);
if (mPreviewPopup.isShowing()) {
mPreviewPopup.dismiss();
}
}
@Override
public boolean onTouchEvent(MotionEvent me) {
if (mGestureDetector.onTouchEvent(me)) {
return true;
}
int action = me.getAction();
int x = (int) me.getX();
int y = (int) me.getY();
mTouchX = x;
switch (action) {
case MotionEvent.ACTION_DOWN:
mScrolling = false;
invalidate();
break;
case MotionEvent.ACTION_MOVE:
if (y <= 0) {
// Fling up!?
if (mSelectedString != null) {
if (!mShowingCompletions) {
TextEntryState.acceptedSuggestion(mSuggestions.get(0),
mSelectedString);
}
mService.pickSuggestionManually(mSelectedIndex, mSelectedString);
mSelectedString = null;
mSelectedIndex = -1;
}
}
invalidate();
break;
case MotionEvent.ACTION_UP:
if (!mScrolling) {
if (mSelectedString != null) {
if (!mShowingCompletions) {
TextEntryState.acceptedSuggestion(mSuggestions.get(0),
mSelectedString);
}
mService.pickSuggestionManually(mSelectedIndex, mSelectedString);
}
}
mSelectedString = null;
mSelectedIndex = -1;
removeHighlight();
hidePreview();
requestLayout();
//I picked up the finger... No more scrolling, right?
mScrolling = false;
break;
}
return true;
}
/**
* For flick through from keyboard, call this method with the x coordinate of the flick
* gesture.
* @param x
*/
public void takeSuggestionAt(float x) {
mTouchX = (int) x;
// To detect candidate
onDraw(null);
if (mSelectedString != null) {
if (!mShowingCompletions) {
TextEntryState.acceptedSuggestion(mSuggestions.get(0), mSelectedString);
}
mService.pickSuggestionManually(mSelectedIndex, mSelectedString);
}
invalidate();
mHandler.sendMessageDelayed(mHandler.obtainMessage(MSG_REMOVE_THROUGH_PREVIEW), 200);
}
private void hidePreview() {
mCurrentWordIndex = OUT_OF_BOUNDS;
if (mPreviewPopup.isShowing()) {
mHandler.sendMessageDelayed(mHandler
.obtainMessage(MSG_REMOVE_PREVIEW), 60);
}
}
private void showPreview(int wordIndex, String altText) {
int oldWordIndex = mCurrentWordIndex;
mCurrentWordIndex = wordIndex;
// If index changed or changing text
if (oldWordIndex != mCurrentWordIndex || altText != null) {
if (wordIndex == OUT_OF_BOUNDS) {
hidePreview();
} else {
CharSequence word = altText != null? altText : mSuggestions.get(wordIndex);
mPreviewText.setText(word);
mPreviewText.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED),
MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int wordWidth = (int) (mPaint.measureText(word, 0, word.length()) + X_GAP * 2);
final int popupWidth = wordWidth
+ mPreviewText.getPaddingLeft() + mPreviewText.getPaddingRight();
final int popupHeight = mPreviewText.getMeasuredHeight();
//mPreviewText.setVisibility(INVISIBLE);
mPopupPreviewX = mWordX[wordIndex] - mPreviewText.getPaddingLeft() - mScrollX;
mPopupPreviewY = - popupHeight;
mHandler.removeMessages(MSG_REMOVE_PREVIEW);
int [] offsetInWindow = new int[2];
getLocationInWindow(offsetInWindow);
if (mPreviewPopup.isShowing()) {
mPreviewPopup.update(mPopupPreviewX, mPopupPreviewY + offsetInWindow[1],
popupWidth, popupHeight);
} else {
mPreviewPopup.setWidth(popupWidth);
mPreviewPopup.setHeight(popupHeight);
mPreviewPopup.showAtLocation(this, Gravity.NO_GRAVITY, mPopupPreviewX,
mPopupPreviewY + offsetInWindow[1]);
}
mPreviewText.setVisibility(VISIBLE);
}
}
}
private void removeHighlight() {
mTouchX = OUT_OF_BOUNDS;
invalidate();
}
private void longPressFirstWord() {
CharSequence word = mSuggestions.get(0);
if (mService.addWordToDictionary(word.toString())) {
showPreview(0, getContext().getResources().getString(R.string.added_word, word));
}
}
@Override
public void onDetachedFromWindow() {
super.onDetachedFromWindow();
hidePreview();
}
public int getmScrollX() {
return mScrollX;
}
}
| false | true | protected void onDraw(Canvas canvas) {
if (canvas != null) {
super.onDraw(canvas);
}
mTotalWidth = 0;
if (mSuggestions == null) return;
final int height = getHeight();
if (mBgPadding == null) {
mBgPadding = new Rect(0, 0, 0, 0);
if (getBackground() != null) {
getBackground().getPadding(mBgPadding);
}
mDivider.setBounds(0, mBgPadding.top, mDivider.getIntrinsicWidth(),
mDivider.getIntrinsicHeight());
}
final int count = mSuggestions.size();
//final int width = getWidth();
final Rect bgPadding = mBgPadding;
final Paint paint = mPaint;
final int touchX = mTouchX;
final int scrollX = mScrollX;
int x = 0-scrollX;
//final boolean scrolled = mScrolling;
final boolean typedWordValid = mTypedWordValid;
final int y = (int) (height + mPaint.getTextSize() - mDescent) / 2;
for (int i = 0; i < count; i++) {
CharSequence suggestion = mSuggestions.get(i);
if ((suggestion == null) || (suggestion.length() == 0)) continue;
paint.setColor(mColorNormal);
//the typed word is the first.
//the valid word is either the first, or the second.
//So, the following if will set the valid word as bold and mColorRecommended
if (mHaveMinimalSuggestion && ((i == 1 && !typedWordValid) || (i == 0 && typedWordValid))) {
paint.setTypeface(Typeface.DEFAULT_BOLD);
paint.setColor(mColorRecommended);
} else if (i != 0) {
//not valid
paint.setTypeface(Typeface.DEFAULT);
paint.setColor(mColorOther);
}
final int wordWidth;
if (mWordWidth[i] != 0) {
//already computed
wordWidth = mWordWidth[i];
} else {
//first time we see the word in the GUI, lets see how long it is
float textWidth = paint.measureText(suggestion, 0, suggestion.length());
wordWidth = (int) (textWidth + (X_GAP * 1.8));
mWordWidth[i] = wordWidth;
}
//x is the incremental X position
mWordX[i] = x;
//this handles the touched word
//
if ((touchX != OUT_OF_BOUNDS) && (touchX >= x) && (touchX < (x + wordWidth))) /*!scrolled &&*/
{
if (canvas != null) {
canvas.translate(x, 0);
mSelectionHighlight.setBounds(0, bgPadding.top, wordWidth, height);
mSelectionHighlight.draw(canvas);
canvas.translate(-x, 0);
showPreview(i, null);
}
mSelectedString = suggestion;
mSelectedIndex = i;
}
if (canvas != null) {
//Hebrew letters are to be drawn in the other direction. This will be probably be removed in Donut.
//Also, this is not valid for Galaxy (Israel's Cellcom Android)
CharSequence directionCorrectedSuggestion = ms_requiresRtlWorkaround?
workaroundCorrectStringDirection(suggestion) : suggestion;
canvas.drawText(directionCorrectedSuggestion, 0, directionCorrectedSuggestion.length(), x + X_GAP, y, paint);
paint.setColor(mColorOther);
canvas.translate(x + wordWidth, 0);
mDivider.draw(canvas);
canvas.translate(-x - wordWidth, 0);
}
paint.setTypeface(Typeface.DEFAULT);
x += wordWidth;
}
mTotalWidth = x + mScrollX;//with the fixed size
if (mTargetScrollX != mScrollX) {
scrollToTarget();
}
}
| protected void onDraw(Canvas canvas) {
if (canvas != null) {
super.onDraw(canvas);
}
mTotalWidth = 0;
if (mSuggestions == null) return;
final int height = getHeight();
if (mBgPadding == null) {
mBgPadding = new Rect(0, 0, 0, 0);
if (getBackground() != null) {
getBackground().getPadding(mBgPadding);
}
mDivider.setBounds(0, mBgPadding.top, mDivider.getIntrinsicWidth(),
mDivider.getIntrinsicHeight());
}
final int count = mSuggestions.size();
//final int width = getWidth();
final Rect bgPadding = mBgPadding;
final Paint paint = mPaint;
final int touchX = mTouchX;
final int scrollX = mScrollX;
int x = 0-scrollX;
final boolean scrolling = mScrolling;
final boolean typedWordValid = mTypedWordValid;
final int y = (int) (height + mPaint.getTextSize() - mDescent) / 2;
for (int i = 0; i < count; i++) {
CharSequence suggestion = mSuggestions.get(i);
if ((suggestion == null) || (suggestion.length() == 0)) continue;
paint.setColor(mColorNormal);
//the typed word is the first.
//the valid word is either the first, or the second.
//So, the following if will set the valid word as bold and mColorRecommended
if (mHaveMinimalSuggestion && ((i == 1 && !typedWordValid) || (i == 0 && typedWordValid))) {
paint.setTypeface(Typeface.DEFAULT_BOLD);
paint.setColor(mColorRecommended);
} else if (i != 0) {
//not valid
paint.setTypeface(Typeface.DEFAULT);
paint.setColor(mColorOther);
}
final int wordWidth;
if (mWordWidth[i] != 0) {
//already computed
wordWidth = mWordWidth[i];
} else {
//first time we see the word in the GUI, lets see how long it is
float textWidth = paint.measureText(suggestion, 0, suggestion.length());
wordWidth = (int) (textWidth + (X_GAP * 1.8));
mWordWidth[i] = wordWidth;
}
//x is the incremental X position
mWordX[i] = x;
//this handles the touched word popup and highlight.
//We want to do those only if we are not scrolling (by finger, e.g.)
if ((touchX != OUT_OF_BOUNDS) && (!scrolling) && (touchX >= x) && (touchX < (x + wordWidth)))
{
if (canvas != null) {
canvas.translate(x, 0);
mSelectionHighlight.setBounds(0, bgPadding.top, wordWidth, height);
mSelectionHighlight.draw(canvas);
canvas.translate(-x, 0);
showPreview(i, null);
}
mSelectedString = suggestion;
mSelectedIndex = i;
}
if (canvas != null) {
//Hebrew letters are to be drawn in the other direction. This will be probably be removed in Donut.
//Also, this is not valid for Galaxy (Israel's Cellcom Android)
CharSequence directionCorrectedSuggestion = ms_requiresRtlWorkaround?
workaroundCorrectStringDirection(suggestion) : suggestion;
canvas.drawText(directionCorrectedSuggestion, 0, directionCorrectedSuggestion.length(), x + X_GAP, y, paint);
paint.setColor(mColorOther);
canvas.translate(x + wordWidth, 0);
mDivider.draw(canvas);
canvas.translate(-x - wordWidth, 0);
}
paint.setTypeface(Typeface.DEFAULT);
x += wordWidth;
}
mTotalWidth = x + mScrollX;//with the fixed size
if (mTargetScrollX != mScrollX) {
scrollToTarget();
}
}
|
diff --git a/src/testapp/java/nextapp/echo2/extras/testapp/testscreen/TransitionPaneTest.java b/src/testapp/java/nextapp/echo2/extras/testapp/testscreen/TransitionPaneTest.java
index 03202b2..4c16b31 100644
--- a/src/testapp/java/nextapp/echo2/extras/testapp/testscreen/TransitionPaneTest.java
+++ b/src/testapp/java/nextapp/echo2/extras/testapp/testscreen/TransitionPaneTest.java
@@ -1,151 +1,156 @@
/*
* This file is part of the Echo2 Extras Project.
* Copyright (C) 2005-2006 NextApp, Inc.
*
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*/
package nextapp.echo2.extras.testapp.testscreen;
import nextapp.echo2.app.ContentPane;
import nextapp.echo2.app.Label;
import nextapp.echo2.app.event.ActionEvent;
import nextapp.echo2.app.event.ActionListener;
import nextapp.echo2.extras.app.TransitionPane;
import nextapp.echo2.extras.testapp.AbstractTest;
import nextapp.echo2.extras.testapp.StyleUtil;
import nextapp.echo2.extras.testapp.Styles;
import nextapp.echo2.extras.testapp.TestControlPane;
public class TransitionPaneTest extends AbstractTest {
private int childNumber = 0;
public TransitionPaneTest() {
super("TransitionPane", Styles.ICON_16_TRANSITION_PANE);
final TransitionPane transitionPane = new TransitionPane();
add(transitionPane);
setTestComponent(this, transitionPane);
// Add/Remove Content
testControlsPane.addButton(TestControlPane.CATEGORY_CONTENT, "Set Content Label", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.removeAll();
Label label = new Label("Label Pane #" + childNumber);
label.setBackground(StyleUtil.randomBrightColor());
transitionPane.add(label);
++childNumber;
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_CONTENT, "Set Content ContentPane", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.removeAll();
ContentPane contentPane = new ContentPane();
contentPane.setBackground(StyleUtil.randomBrightColor());
Label label = new Label("Content Pane #" + childNumber);
contentPane.add(label);
transitionPane.add(contentPane);
++childNumber;
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_CONTENT, "Set Content TransitionPaneTest", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.removeAll();
transitionPane.add(new TransitionPaneTest());
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_CONTENT, "Set Content ColorSelectTest", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.removeAll();
transitionPane.add(new ColorSelectTest());
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_CONTENT, "Set Content TabPaneTest", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.removeAll();
transitionPane.add(new TabPaneTest());
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_CONTENT, "Remove Content", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.removeAll();
}
});
// Properties
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES, "Trans = Null", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.setProperty(TransitionPane.PROPERTY_TYPE, null);
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES, "Trans = Immediate", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.setType(TransitionPane.TYPE_IMMEDIATE_REPLACE);
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES, "Trans = CameraPan/Left", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.setType(TransitionPane.TYPE_CAMERA_PAN_LEFT);
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES, "Trans = CameraPan/Right", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.setType(TransitionPane.TYPE_CAMERA_PAN_RIGHT);
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES, "Trans = Blind/Black/In", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.setType(TransitionPane.TYPE_BLIND_BLACK_IN);
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES, "Trans = Blind/Black/Out", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.setType(TransitionPane.TYPE_BLIND_BLACK_OUT);
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES, "Trans = Fade/Black", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.setType(TransitionPane.TYPE_FADE_TO_BLACK);
}
});
+ testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES, "Trans = Fade/White", new ActionListener() {
+ public void actionPerformed(ActionEvent e) {
+ transitionPane.setType(TransitionPane.TYPE_FADE_TO_WHITE);
+ }
+ });
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES,
TransitionPane.PROPERTY_DURATION + ": null", new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
transitionPane.setProperty(TransitionPane.PROPERTY_DURATION, null);
}
});
addIntegerPropertyTests(TestControlPane.CATEGORY_PROPERTIES, TransitionPane.PROPERTY_DURATION,
new int[]{0, 50, 100, 350, 700, 1000, 2000, 5000});
}
}
| true | true | public TransitionPaneTest() {
super("TransitionPane", Styles.ICON_16_TRANSITION_PANE);
final TransitionPane transitionPane = new TransitionPane();
add(transitionPane);
setTestComponent(this, transitionPane);
// Add/Remove Content
testControlsPane.addButton(TestControlPane.CATEGORY_CONTENT, "Set Content Label", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.removeAll();
Label label = new Label("Label Pane #" + childNumber);
label.setBackground(StyleUtil.randomBrightColor());
transitionPane.add(label);
++childNumber;
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_CONTENT, "Set Content ContentPane", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.removeAll();
ContentPane contentPane = new ContentPane();
contentPane.setBackground(StyleUtil.randomBrightColor());
Label label = new Label("Content Pane #" + childNumber);
contentPane.add(label);
transitionPane.add(contentPane);
++childNumber;
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_CONTENT, "Set Content TransitionPaneTest", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.removeAll();
transitionPane.add(new TransitionPaneTest());
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_CONTENT, "Set Content ColorSelectTest", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.removeAll();
transitionPane.add(new ColorSelectTest());
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_CONTENT, "Set Content TabPaneTest", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.removeAll();
transitionPane.add(new TabPaneTest());
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_CONTENT, "Remove Content", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.removeAll();
}
});
// Properties
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES, "Trans = Null", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.setProperty(TransitionPane.PROPERTY_TYPE, null);
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES, "Trans = Immediate", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.setType(TransitionPane.TYPE_IMMEDIATE_REPLACE);
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES, "Trans = CameraPan/Left", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.setType(TransitionPane.TYPE_CAMERA_PAN_LEFT);
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES, "Trans = CameraPan/Right", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.setType(TransitionPane.TYPE_CAMERA_PAN_RIGHT);
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES, "Trans = Blind/Black/In", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.setType(TransitionPane.TYPE_BLIND_BLACK_IN);
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES, "Trans = Blind/Black/Out", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.setType(TransitionPane.TYPE_BLIND_BLACK_OUT);
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES, "Trans = Fade/Black", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.setType(TransitionPane.TYPE_FADE_TO_BLACK);
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES,
TransitionPane.PROPERTY_DURATION + ": null", new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
transitionPane.setProperty(TransitionPane.PROPERTY_DURATION, null);
}
});
addIntegerPropertyTests(TestControlPane.CATEGORY_PROPERTIES, TransitionPane.PROPERTY_DURATION,
new int[]{0, 50, 100, 350, 700, 1000, 2000, 5000});
}
| public TransitionPaneTest() {
super("TransitionPane", Styles.ICON_16_TRANSITION_PANE);
final TransitionPane transitionPane = new TransitionPane();
add(transitionPane);
setTestComponent(this, transitionPane);
// Add/Remove Content
testControlsPane.addButton(TestControlPane.CATEGORY_CONTENT, "Set Content Label", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.removeAll();
Label label = new Label("Label Pane #" + childNumber);
label.setBackground(StyleUtil.randomBrightColor());
transitionPane.add(label);
++childNumber;
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_CONTENT, "Set Content ContentPane", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.removeAll();
ContentPane contentPane = new ContentPane();
contentPane.setBackground(StyleUtil.randomBrightColor());
Label label = new Label("Content Pane #" + childNumber);
contentPane.add(label);
transitionPane.add(contentPane);
++childNumber;
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_CONTENT, "Set Content TransitionPaneTest", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.removeAll();
transitionPane.add(new TransitionPaneTest());
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_CONTENT, "Set Content ColorSelectTest", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.removeAll();
transitionPane.add(new ColorSelectTest());
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_CONTENT, "Set Content TabPaneTest", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.removeAll();
transitionPane.add(new TabPaneTest());
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_CONTENT, "Remove Content", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.removeAll();
}
});
// Properties
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES, "Trans = Null", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.setProperty(TransitionPane.PROPERTY_TYPE, null);
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES, "Trans = Immediate", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.setType(TransitionPane.TYPE_IMMEDIATE_REPLACE);
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES, "Trans = CameraPan/Left", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.setType(TransitionPane.TYPE_CAMERA_PAN_LEFT);
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES, "Trans = CameraPan/Right", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.setType(TransitionPane.TYPE_CAMERA_PAN_RIGHT);
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES, "Trans = Blind/Black/In", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.setType(TransitionPane.TYPE_BLIND_BLACK_IN);
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES, "Trans = Blind/Black/Out", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.setType(TransitionPane.TYPE_BLIND_BLACK_OUT);
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES, "Trans = Fade/Black", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.setType(TransitionPane.TYPE_FADE_TO_BLACK);
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES, "Trans = Fade/White", new ActionListener() {
public void actionPerformed(ActionEvent e) {
transitionPane.setType(TransitionPane.TYPE_FADE_TO_WHITE);
}
});
testControlsPane.addButton(TestControlPane.CATEGORY_PROPERTIES,
TransitionPane.PROPERTY_DURATION + ": null", new ActionListener(){
public void actionPerformed(ActionEvent arg0) {
transitionPane.setProperty(TransitionPane.PROPERTY_DURATION, null);
}
});
addIntegerPropertyTests(TestControlPane.CATEGORY_PROPERTIES, TransitionPane.PROPERTY_DURATION,
new int[]{0, 50, 100, 350, 700, 1000, 2000, 5000});
}
|
diff --git a/src/net/somethingdreadful/MAL/FirstTimeInit.java b/src/net/somethingdreadful/MAL/FirstTimeInit.java
index 5eee0183..fcb2f9b1 100644
--- a/src/net/somethingdreadful/MAL/FirstTimeInit.java
+++ b/src/net/somethingdreadful/MAL/FirstTimeInit.java
@@ -1,128 +1,128 @@
package net.somethingdreadful.MAL;
import net.somethingdreadful.MAL.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class FirstTimeInit extends Activity {
static EditText malUser;
static EditText malPass;
static String testMalUser;
static String testMalPass;
static Button connectButton;
static ProgressDialog pd;
static Thread netThread;
static Context context;
static private Handler messenger;
static PrefManager prefManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firstrun);
malUser = (EditText) findViewById(R.id.edittext_malUser);
malPass = (EditText) findViewById(R.id.edittext_malPass);
Button connectButton = (Button) findViewById(R.id.button_connectToMal);
Button registerButton = (Button) findViewById(R.id.registerButton);
context = getApplicationContext();
prefManager = new PrefManager(context);
connectButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
- testMalUser = malUser.getText().toString();
+ testMalUser = malUser.getText().toString().replace(" ", "");
testMalPass = malPass.getText().toString();
tryConnection();
}
});
registerButton.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://myanimelist.net/register.php"));
startActivity(browserIntent);
}
});
messenger = new Handler() {
public void handleMessage(Message msg)
{
if (msg.what == 2)
{
pd.dismiss();
Toast.makeText(context, context.getString(R.string.toast_VerifyProblem), Toast.LENGTH_SHORT).show();
}
if (msg.what == 3)
{
pd.dismiss();
Toast.makeText(context, context.getString(R.string.toast_AccountOK), Toast.LENGTH_SHORT).show();
prefManager.setUser(testMalUser);
prefManager.setPass(testMalPass);
prefManager.setInit(true);
prefManager.commitChanges();
Intent goHome = new Intent(context, Home.class);
goHome.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra("net.somethingdreadful.MAL.firstSync", true);
startActivity(goHome);
}
super.handleMessage(msg);
}
};
}
private void tryConnection()
{
pd = ProgressDialog.show(this, context.getString(R.string.dialog_Verifying), context.getString(R.string.dialog_VerifyingBlurb));
netThread = new networkThread();
netThread.start();
}
public class networkThread extends Thread
{
@Override
public void run()
{
boolean valid = MALManager.verifyAccount(testMalUser, testMalPass);
String words = "";
Message msg = new Message();
if (valid == false)
{
msg.what = 2;
messenger.sendMessage(msg);
}
else
{
msg.what = 3;
messenger.sendMessage(msg);
}
}
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firstrun);
malUser = (EditText) findViewById(R.id.edittext_malUser);
malPass = (EditText) findViewById(R.id.edittext_malPass);
Button connectButton = (Button) findViewById(R.id.button_connectToMal);
Button registerButton = (Button) findViewById(R.id.registerButton);
context = getApplicationContext();
prefManager = new PrefManager(context);
connectButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
testMalUser = malUser.getText().toString();
testMalPass = malPass.getText().toString();
tryConnection();
}
});
registerButton.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://myanimelist.net/register.php"));
startActivity(browserIntent);
}
});
messenger = new Handler() {
public void handleMessage(Message msg)
{
if (msg.what == 2)
{
pd.dismiss();
Toast.makeText(context, context.getString(R.string.toast_VerifyProblem), Toast.LENGTH_SHORT).show();
}
if (msg.what == 3)
{
pd.dismiss();
Toast.makeText(context, context.getString(R.string.toast_AccountOK), Toast.LENGTH_SHORT).show();
prefManager.setUser(testMalUser);
prefManager.setPass(testMalPass);
prefManager.setInit(true);
prefManager.commitChanges();
Intent goHome = new Intent(context, Home.class);
goHome.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra("net.somethingdreadful.MAL.firstSync", true);
startActivity(goHome);
}
super.handleMessage(msg);
}
};
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firstrun);
malUser = (EditText) findViewById(R.id.edittext_malUser);
malPass = (EditText) findViewById(R.id.edittext_malPass);
Button connectButton = (Button) findViewById(R.id.button_connectToMal);
Button registerButton = (Button) findViewById(R.id.registerButton);
context = getApplicationContext();
prefManager = new PrefManager(context);
connectButton.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
testMalUser = malUser.getText().toString().replace(" ", "");
testMalPass = malPass.getText().toString();
tryConnection();
}
});
registerButton.setOnClickListener(new OnClickListener()
{
public void onClick(View arg0) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://myanimelist.net/register.php"));
startActivity(browserIntent);
}
});
messenger = new Handler() {
public void handleMessage(Message msg)
{
if (msg.what == 2)
{
pd.dismiss();
Toast.makeText(context, context.getString(R.string.toast_VerifyProblem), Toast.LENGTH_SHORT).show();
}
if (msg.what == 3)
{
pd.dismiss();
Toast.makeText(context, context.getString(R.string.toast_AccountOK), Toast.LENGTH_SHORT).show();
prefManager.setUser(testMalUser);
prefManager.setPass(testMalPass);
prefManager.setInit(true);
prefManager.commitChanges();
Intent goHome = new Intent(context, Home.class);
goHome.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
.putExtra("net.somethingdreadful.MAL.firstSync", true);
startActivity(goHome);
}
super.handleMessage(msg);
}
};
}
|
diff --git a/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/StopsAlerts.java b/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/StopsAlerts.java
index bf380d426..ed7ad740b 100644
--- a/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/StopsAlerts.java
+++ b/opentripplanner-graph-builder/src/main/java/org/opentripplanner/graph_builder/impl/StopsAlerts.java
@@ -1,69 +1,69 @@
/* This program is free software: you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
package org.opentripplanner.graph_builder.impl;
import lombok.Setter;
import org.opentripplanner.common.IterableLibrary;
import org.opentripplanner.graph_builder.impl.stopsAlerts.IStopTester;
import org.opentripplanner.graph_builder.services.GraphBuilder;
import org.opentripplanner.routing.graph.Graph;
import org.opentripplanner.routing.services.StreetVertexIndexService;
import org.opentripplanner.routing.vertextype.TransitStop;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.*;
public class StopsAlerts implements GraphBuilder {
@Setter
List<IStopTester> stopTesters = new ArrayList<IStopTester>();
@Setter
String logFile = "";
@Override
public void buildGraph(Graph graph, HashMap<Class<?>, Object> extra) {
Logger stopsLog = LoggerFactory.getLogger(LoggerAppenderProvider.createCsvFile4LoggerCat(logFile,"stops"));
stopsLog.info(String.format("%s,%s,%s,%s","stopId","lon","lat","types"));
for (TransitStop ts : IterableLibrary.filter(graph.getVertices(), TransitStop.class)) {
StringBuilder types = new StringBuilder();
for(IStopTester stopTester:stopTesters){
if(stopTester.fulfillDemands(ts,graph)){
if(types.length() > 0) types.append(";");
types.append(stopTester.getType());
}
}
if(types.length() > 0) {
- stopsLog.info(String.format("%s,%f,%f,%s",ts.getIndex() ,ts.getCoordinate().x,ts.getCoordinate().y,types.toString()));
+ stopsLog.info(String.format("%s,%f,%f,%s",ts.getStopId(), ts.getCoordinate().x,ts.getCoordinate().y,types.toString()));
}
}
}
@Override
public List<String> provides() {
return Collections.emptyList();
}
@Override
public List<String> getPrerequisites() {
return Arrays.asList("transit","streets");
}
@Override
public void checkInputs() {
if(logFile.isEmpty())
throw new RuntimeException("missing log file name");
}
}
| true | true | public void buildGraph(Graph graph, HashMap<Class<?>, Object> extra) {
Logger stopsLog = LoggerFactory.getLogger(LoggerAppenderProvider.createCsvFile4LoggerCat(logFile,"stops"));
stopsLog.info(String.format("%s,%s,%s,%s","stopId","lon","lat","types"));
for (TransitStop ts : IterableLibrary.filter(graph.getVertices(), TransitStop.class)) {
StringBuilder types = new StringBuilder();
for(IStopTester stopTester:stopTesters){
if(stopTester.fulfillDemands(ts,graph)){
if(types.length() > 0) types.append(";");
types.append(stopTester.getType());
}
}
if(types.length() > 0) {
stopsLog.info(String.format("%s,%f,%f,%s",ts.getIndex() ,ts.getCoordinate().x,ts.getCoordinate().y,types.toString()));
}
}
}
| public void buildGraph(Graph graph, HashMap<Class<?>, Object> extra) {
Logger stopsLog = LoggerFactory.getLogger(LoggerAppenderProvider.createCsvFile4LoggerCat(logFile,"stops"));
stopsLog.info(String.format("%s,%s,%s,%s","stopId","lon","lat","types"));
for (TransitStop ts : IterableLibrary.filter(graph.getVertices(), TransitStop.class)) {
StringBuilder types = new StringBuilder();
for(IStopTester stopTester:stopTesters){
if(stopTester.fulfillDemands(ts,graph)){
if(types.length() > 0) types.append(";");
types.append(stopTester.getType());
}
}
if(types.length() > 0) {
stopsLog.info(String.format("%s,%f,%f,%s",ts.getStopId(), ts.getCoordinate().x,ts.getCoordinate().y,types.toString()));
}
}
}
|
diff --git a/nexus/nexus-app/src/main/java/org/sonatype/nexus/email/DefaultSmtpSettingsValidator.java b/nexus/nexus-app/src/main/java/org/sonatype/nexus/email/DefaultSmtpSettingsValidator.java
index 216f3dcbf..0d852abf7 100644
--- a/nexus/nexus-app/src/main/java/org/sonatype/nexus/email/DefaultSmtpSettingsValidator.java
+++ b/nexus/nexus-app/src/main/java/org/sonatype/nexus/email/DefaultSmtpSettingsValidator.java
@@ -1,80 +1,80 @@
package org.sonatype.nexus.email;
import org.codehaus.plexus.PlexusContainer;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.component.repository.exception.ComponentLookupException;
import org.codehaus.plexus.context.Context;
import org.codehaus.plexus.context.ContextException;
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.codehaus.plexus.personality.plexus.lifecycle.phase.Contextualizable;
import org.sonatype.micromailer.Address;
import org.sonatype.micromailer.EMailer;
import org.sonatype.micromailer.EmailerConfiguration;
import org.sonatype.micromailer.MailRequest;
import org.sonatype.micromailer.MailRequestStatus;
import org.sonatype.micromailer.imp.DefaultMailType;
import org.sonatype.nexus.configuration.model.CSmtpConfiguration;
/**
* @author velo
*/
@Component( role = SmtpSettingsValidator.class )
public class DefaultSmtpSettingsValidator
extends AbstractLogEnabled
implements SmtpSettingsValidator, Contextualizable
{
private PlexusContainer plexusContainer;
private static final String NEXUS_MAIL_ID = "Nexus";
public boolean sendSmtpConfigurationTest( CSmtpConfiguration smtp, String email )
throws EmailerException
{
EmailerConfiguration config = new EmailerConfiguration();
config.setDebug( smtp.isDebugMode() );
config.setMailHost( smtp.getHostname() );
config.setMailPort( smtp.getPort() );
config.setPassword( smtp.getPassword() );
config.setSsl( smtp.isSslEnabled() );
config.setTls( smtp.isTlsEnabled() );
config.setUsername( smtp.getUsername() );
EMailer emailer;
try
{
emailer = plexusContainer.lookup( EMailer.class );
}
catch ( ComponentLookupException e )
{
throw new EmailerException( "Unable to create EMailer", e );
}
emailer.configure( config );
MailRequest request = new MailRequest( NEXUS_MAIL_ID, DefaultMailType.DEFAULT_TYPE_ID );
request.setFrom( new Address( smtp.getSystemEmailAddress(), "Nexus Repository Manager" ) );
request.getToAddresses().add( new Address( email ) );
- request.getBodyContext().put( DefaultMailType.SUBJECT_KEY, "Nexus: Stmp Configuration validation." );
+ request.getBodyContext().put( DefaultMailType.SUBJECT_KEY, "Nexus: SMTP Configuration validation." );
StringBuilder body = new StringBuilder();
body.append( "Your current SMTP configuration is valid!" );
request.getBodyContext().put( DefaultMailType.BODY_KEY, body.toString() );
MailRequestStatus status = emailer.sendSyncedMail( request );
if ( status.getErrorCause() != null )
{
getLogger().error( "Unable to send e-mail", status.getErrorCause() );
throw new EmailerException( "Unable to send e-mail", status.getErrorCause() );
}
return status.isSent();
}
public void contextualize( Context context )
throws ContextException
{
plexusContainer = (PlexusContainer) context.get( "plexus" );
}
}
| true | true | public boolean sendSmtpConfigurationTest( CSmtpConfiguration smtp, String email )
throws EmailerException
{
EmailerConfiguration config = new EmailerConfiguration();
config.setDebug( smtp.isDebugMode() );
config.setMailHost( smtp.getHostname() );
config.setMailPort( smtp.getPort() );
config.setPassword( smtp.getPassword() );
config.setSsl( smtp.isSslEnabled() );
config.setTls( smtp.isTlsEnabled() );
config.setUsername( smtp.getUsername() );
EMailer emailer;
try
{
emailer = plexusContainer.lookup( EMailer.class );
}
catch ( ComponentLookupException e )
{
throw new EmailerException( "Unable to create EMailer", e );
}
emailer.configure( config );
MailRequest request = new MailRequest( NEXUS_MAIL_ID, DefaultMailType.DEFAULT_TYPE_ID );
request.setFrom( new Address( smtp.getSystemEmailAddress(), "Nexus Repository Manager" ) );
request.getToAddresses().add( new Address( email ) );
request.getBodyContext().put( DefaultMailType.SUBJECT_KEY, "Nexus: Stmp Configuration validation." );
StringBuilder body = new StringBuilder();
body.append( "Your current SMTP configuration is valid!" );
request.getBodyContext().put( DefaultMailType.BODY_KEY, body.toString() );
MailRequestStatus status = emailer.sendSyncedMail( request );
if ( status.getErrorCause() != null )
{
getLogger().error( "Unable to send e-mail", status.getErrorCause() );
throw new EmailerException( "Unable to send e-mail", status.getErrorCause() );
}
return status.isSent();
}
| public boolean sendSmtpConfigurationTest( CSmtpConfiguration smtp, String email )
throws EmailerException
{
EmailerConfiguration config = new EmailerConfiguration();
config.setDebug( smtp.isDebugMode() );
config.setMailHost( smtp.getHostname() );
config.setMailPort( smtp.getPort() );
config.setPassword( smtp.getPassword() );
config.setSsl( smtp.isSslEnabled() );
config.setTls( smtp.isTlsEnabled() );
config.setUsername( smtp.getUsername() );
EMailer emailer;
try
{
emailer = plexusContainer.lookup( EMailer.class );
}
catch ( ComponentLookupException e )
{
throw new EmailerException( "Unable to create EMailer", e );
}
emailer.configure( config );
MailRequest request = new MailRequest( NEXUS_MAIL_ID, DefaultMailType.DEFAULT_TYPE_ID );
request.setFrom( new Address( smtp.getSystemEmailAddress(), "Nexus Repository Manager" ) );
request.getToAddresses().add( new Address( email ) );
request.getBodyContext().put( DefaultMailType.SUBJECT_KEY, "Nexus: SMTP Configuration validation." );
StringBuilder body = new StringBuilder();
body.append( "Your current SMTP configuration is valid!" );
request.getBodyContext().put( DefaultMailType.BODY_KEY, body.toString() );
MailRequestStatus status = emailer.sendSyncedMail( request );
if ( status.getErrorCause() != null )
{
getLogger().error( "Unable to send e-mail", status.getErrorCause() );
throw new EmailerException( "Unable to send e-mail", status.getErrorCause() );
}
return status.isSent();
}
|
diff --git a/src/org/apache/ws/security/message/WSSecEncryptedKey.java b/src/org/apache/ws/security/message/WSSecEncryptedKey.java
index e33c46752..fed191af6 100644
--- a/src/org/apache/ws/security/message/WSSecEncryptedKey.java
+++ b/src/org/apache/ws/security/message/WSSecEncryptedKey.java
@@ -1,494 +1,495 @@
/*
* Copyright 2003-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.ws.security.message;
import java.security.InvalidKeyException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.ws.security.WSConstants;
import org.apache.ws.security.WSSecurityException;
import org.apache.ws.security.components.crypto.Crypto;
import org.apache.ws.security.message.token.BinarySecurity;
import org.apache.ws.security.message.token.Reference;
import org.apache.ws.security.message.token.SecurityTokenReference;
import org.apache.ws.security.message.token.X509Security;
import org.apache.ws.security.util.WSSecurityUtil;
import org.apache.xml.security.keys.KeyInfo;
import org.apache.xml.security.keys.content.X509Data;
import org.apache.xml.security.keys.content.x509.XMLX509IssuerSerial;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
/**
* Builder class to build an EncryptedKey.
*
* This is expecially useful in the case where the same
* <code>EncryptedKey</code> has to be used to sign and encrypt the message In
* such a situation this builder will add the <code>EncryptedKey</code> to the
* security header and we can use the information form the builder to provide to
* other builders to reference to the token
*/
public class WSSecEncryptedKey extends WSSecBase {
private static Log log = LogFactory.getLog(WSSecEncryptedKey.class
.getName());
protected Document document;
/**
* soap:Envelope element
*/
protected Element envelope = null;
/**
* Session key used as the secret in key derivation
*/
protected byte[] ephemeralKey;
/**
* Remote user's alias to obtain the cert to encrypt the ephemeral key
*/
protected String encrUser = null;
/**
* Algorithm used to encrypt the ephemeral key
*/
protected String keyEncAlgo = WSConstants.KEYTRANSPORT_RSA15;
/**
* xenc:EncryptedKey element
*/
protected Element encryptedKeyElement = null;
/**
* The Token identifier of the token that the <code>DerivedKeyToken</code>
* is (or to be) derived from.
*/
protected String encKeyId = null;
/**
* BinarySecurityToken to be included in the case where BST_DIRECT_REFERENCE
* is used to refer to the asymm encryption cert
*/
protected BinarySecurity bstToken = null;
protected X509Certificate useThisCert = null;
/**
* Key size in bits
* Defaults to 128
*/
protected int keySize = 128;
/**
* Set the user name to get the encryption certificate.
*
* The public key of this certificate is used, thus no password necessary.
* The user name is a keystore alias usually.
*
* @param user
*/
public void setUserInfo(String user) {
this.user = user;
}
/**
* Get the id generated during <code>prepare()</code>.
*
* Returns the the value of wsu:Id attribute of the EncryptedKey element.
*
* @return Return the wsu:Id of this token or null if <code>prepare()</code>
* was not called before.
*/
public String getId() {
return encKeyId;
}
/**
* Prepare the ephemeralKey and the tokens required to be added to the
* security header
*
* @param doc
* The SOAP envelope as <code>Document</code>
* @param crypto
* An instance of the Crypto API to handle keystore and
* certificates
* @throws WSSecurityException
*/
public void prepare(Document doc, Crypto crypto) throws WSSecurityException {
document = doc;
/*
* Set up the ephemeral key
*/
if (this.ephemeralKey == null) {
this.ephemeralKey = generateEphemeralKey();
}
/*
* Get the certificate that contains the public key for the public key
* algorithm that will encrypt the generated symmetric (session) key.
*/
X509Certificate remoteCert = null;
if (useThisCert != null) {
remoteCert = useThisCert;
} else {
X509Certificate[] certs = crypto.getCertificates(user);
if (certs == null || certs.length <= 0) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"invalidX509Data", new Object[] { "for Encryption" });
}
remoteCert = certs[0];
}
prepareInternal(ephemeralKey, remoteCert, crypto);
}
/**
* Encrypt the symmetric key data and prepare the EncryptedKey element
*
* This method does the most work for to prepare the EncryptedKey element.
* It is also used by the WSSecEncrypt sub-class.
*
* @param keyBytes
* The bytes that represent the symmetric key
* @param remoteCert
* The certificate that contains the public key to encrypt the
* seymmetric key data
* @param crypto
* An instance of the Crypto API to handle keystore and
* certificates
* @throws WSSecurityException
*/
protected void prepareInternal(byte[] keyBytes, X509Certificate remoteCert,
Crypto crypto) throws WSSecurityException {
String certUri = "EncCertId-" + remoteCert.hashCode();
Cipher cipher = WSSecurityUtil.getCipherInstance(keyEncAlgo);
try {
cipher.init(Cipher.ENCRYPT_MODE, remoteCert);
} catch (InvalidKeyException e) {
throw new WSSecurityException(WSSecurityException.FAILED_ENC_DEC,
null, null, e);
}
if (doDebug) {
log.debug("cipher blksize: " + cipher.getBlockSize()
+ ", symm key length: " + keyBytes.length);
}
- if (cipher.getBlockSize() < keyBytes.length) {
+ int blockSize = cipher.getBlockSize();
+ if (blockSize > 0 && blockSize < keyBytes.length) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"unsupportedKeyTransp",
new Object[] { "public key algorithm too weak to encrypt "
+ "symmetric key" });
}
byte[] encryptedKey = null;
try {
encryptedKey = cipher.doFinal(keyBytes);
} catch (IllegalStateException e1) {
throw new WSSecurityException(WSSecurityException.FAILED_ENC_DEC,
null, null, e1);
} catch (IllegalBlockSizeException e1) {
throw new WSSecurityException(WSSecurityException.FAILED_ENC_DEC,
null, null, e1);
} catch (BadPaddingException e1) {
throw new WSSecurityException(WSSecurityException.FAILED_ENC_DEC,
null, null, e1);
}
Text keyText = WSSecurityUtil.createBase64EncodedTextNode(document,
encryptedKey);
/*
* Now we need to setup the EncryptedKey header block 1) create a
* EncryptedKey element and set a wsu:Id for it 2) Generate ds:KeyInfo
* element, this wraps the wsse:SecurityTokenReference 3) Create and set
* up the SecurityTokenReference according to the keyIdentifer parameter
* 4) Create the CipherValue element structure and insert the encrypted
* session key
*/
encryptedKeyElement = createEnrcyptedKey(document, keyEncAlgo);
if(this.encKeyId == null || "".equals(this.encKeyId)) {
this.encKeyId = "EncKeyId-" + encryptedKeyElement.hashCode();
}
encryptedKeyElement.setAttributeNS(null, "Id", this.encKeyId);
KeyInfo keyInfo = new KeyInfo(document);
SecurityTokenReference secToken = new SecurityTokenReference(document);
switch (keyIdentifierType) {
case WSConstants.X509_KEY_IDENTIFIER:
secToken.setKeyIdentifier(remoteCert);
break;
case WSConstants.SKI_KEY_IDENTIFIER:
secToken.setKeyIdentifierSKI(remoteCert, crypto);
break;
case WSConstants.THUMBPRINT_IDENTIFIER:
secToken.setKeyIdentifierThumb(remoteCert);
break;
case WSConstants.ISSUER_SERIAL:
XMLX509IssuerSerial data = new XMLX509IssuerSerial(document,
remoteCert);
X509Data x509Data = new X509Data(document);
x509Data.add(data);
secToken.setX509IssuerSerial(x509Data);
break;
case WSConstants.BST_DIRECT_REFERENCE:
Reference ref = new Reference(document);
ref.setURI("#" + certUri);
bstToken = new X509Security(document);
((X509Security) bstToken).setX509Certificate(remoteCert);
bstToken.setID(certUri);
ref.setValueType(bstToken.getValueType());
secToken.setReference(ref);
break;
default:
throw new WSSecurityException(WSSecurityException.FAILURE,
"unsupportedKeyId");
}
keyInfo.addUnknownElement(secToken.getElement());
WSSecurityUtil.appendChildElement(document, encryptedKeyElement,
keyInfo.getElement());
Element xencCipherValue = createCipherValue(document,
encryptedKeyElement);
xencCipherValue.appendChild(keyText);
envelope = document.getDocumentElement();
envelope.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:"
+ WSConstants.ENC_PREFIX, WSConstants.ENC_NS);
}
/**
* Create an ephemeral key
*
* @return
* @throws WSSecurityException
*/
protected byte[] generateEphemeralKey() throws WSSecurityException {
try {
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] temp = new byte[this.keySize / 8];
random.nextBytes(temp);
return temp;
} catch (Exception e) {
throw new WSSecurityException(
"Error in creating the ephemeral key", e);
}
}
/**
* Create DOM subtree for <code>xenc:EncryptedKey</code>
*
* @param doc
* the SOAP enevelope parent document
* @param keyTransportAlgo
* specifies which alogrithm to use to encrypt the symmetric key
* @return an <code>xenc:EncryptedKey</code> element
*/
protected Element createEnrcyptedKey(Document doc, String keyTransportAlgo) {
Element encryptedKey = doc.createElementNS(WSConstants.ENC_NS,
WSConstants.ENC_PREFIX + ":EncryptedKey");
WSSecurityUtil.setNamespace(encryptedKey, WSConstants.ENC_NS,
WSConstants.ENC_PREFIX);
Element encryptionMethod = doc.createElementNS(WSConstants.ENC_NS,
WSConstants.ENC_PREFIX + ":EncryptionMethod");
encryptionMethod.setAttributeNS(null, "Algorithm", keyTransportAlgo);
WSSecurityUtil.appendChildElement(doc, encryptedKey, encryptionMethod);
return encryptedKey;
}
protected Element createCipherValue(Document doc, Element encryptedKey) {
Element cipherData = doc.createElementNS(WSConstants.ENC_NS,
WSConstants.ENC_PREFIX + ":CipherData");
Element cipherValue = doc.createElementNS(WSConstants.ENC_NS,
WSConstants.ENC_PREFIX + ":CipherValue");
cipherData.appendChild(cipherValue);
WSSecurityUtil.appendChildElement(doc, encryptedKey, cipherData);
return cipherValue;
}
/**
* Prepend the EncryptedKey element to the elements already in the Security
* header.
*
* The method can be called any time after <code>prepare()</code>. This
* allows to insert the EncryptedKey element at any position in the Security
* header.
*
* @param secHeader
* The security header that holds the Signature element.
*/
public void prependToHeader(WSSecHeader secHeader) {
WSSecurityUtil.prependChildElement(document, secHeader
.getSecurityHeader(), encryptedKeyElement, false);
}
/**
* Append the EncryptedKey element to the elements already in the Security
* header.
*
* The method can be called any time after <code>prepare()</code>. This
* allows to insert the EncryptedKey element at any position in the Security
* header.
*
* @param secHeader
* The security header that holds the Signature element.
*/
public void appendToHeader(WSSecHeader secHeader) {
WSSecurityUtil.appendChildElement(document, secHeader
.getSecurityHeader(), encryptedKeyElement);
}
/**
* Prepend the BinarySecurityToken to the elements already in the Security
* header.
*
* The method can be called any time after <code>prepare()</code>. This
* allows to insert the BST element at any position in the Security header.
*
* @param secHeader
* The security header that holds the BST element.
*/
public void prependBSTElementToHeader(WSSecHeader secHeader) {
if (bstToken != null) {
WSSecurityUtil.prependChildElement(document, secHeader
.getSecurityHeader(), bstToken.getElement(), false);
}
bstToken = null;
}
/**
* Append the BinarySecurityToken to the elements already in the Security
* header.
*
* The method can be called any time after <code>prepare()</code>. This
* allows to insert the BST element at any position in the Security header.
*
* @param secHeader
* The security header that holds the BST element.
*/
public void appendBSTElementToHeader(WSSecHeader secHeader) {
if (bstToken != null) {
WSSecurityUtil.appendChildElement(document, secHeader
.getSecurityHeader(), bstToken.getElement());
}
bstToken = null;
}
/**
* @return Returns the ephemeralKey.
*/
public byte[] getEphemeralKey() {
return ephemeralKey;
}
/**
* Set the X509 Certificate to use for encryption.
*
* If this is set <b>and</b> the key identifier is set to
* <code>DirectReference</code> then use this certificate to get the
* public key for encryption.
*
* @param cert
* is the X509 certificate to use for encryption
*/
public void setUseThisCert(X509Certificate cert) {
useThisCert = cert;
}
/**
* @return Returns the encryptedKeyElement.
*/
public Element getEncryptedKeyElement() {
return encryptedKeyElement;
}
/**
* @return Returns the BinarySecurityToken element.
*/
public Element getBinarySecurityTokenElement() {
if(this.bstToken != null) {
return this.bstToken.getElement();
} else {
return null;
}
}
public void setKeySize(int keySize) throws WSSecurityException {
if(keySize < 64) {
//Minimum size has to be 64 bits - E.g. A DES key
throw new WSSecurityException("invalidKeySize");
}
this.keySize = keySize;
}
public void setKeyEncAlgo(String keyEncAlgo) {
this.keyEncAlgo = keyEncAlgo;
}
/**
* @param ephemeralKey The ephemeralKey to set.
*/
public void setEphemeralKey(byte[] ephemeralKey) {
this.ephemeralKey = ephemeralKey;
}
/**
* Get the id of the BSt generated during <code>prepare()</code>.
*
* @return Returns the the value of wsu:Id attribute of the
* BinaruSecurityToken element.
*/
public String getBSTTokenId() {
if(this.bstToken == null) {
return null;
}
return this.bstToken.getID();
}
/**
* @param document The document to set.
*/
public void setDocument(Document document) {
this.document = document;
}
/**
* @param encKeyId The encKeyId to set.
*/
public void setEncKeyId(String encKeyId) {
this.encKeyId = encKeyId;
}
}
| true | true | protected void prepareInternal(byte[] keyBytes, X509Certificate remoteCert,
Crypto crypto) throws WSSecurityException {
String certUri = "EncCertId-" + remoteCert.hashCode();
Cipher cipher = WSSecurityUtil.getCipherInstance(keyEncAlgo);
try {
cipher.init(Cipher.ENCRYPT_MODE, remoteCert);
} catch (InvalidKeyException e) {
throw new WSSecurityException(WSSecurityException.FAILED_ENC_DEC,
null, null, e);
}
if (doDebug) {
log.debug("cipher blksize: " + cipher.getBlockSize()
+ ", symm key length: " + keyBytes.length);
}
if (cipher.getBlockSize() < keyBytes.length) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"unsupportedKeyTransp",
new Object[] { "public key algorithm too weak to encrypt "
+ "symmetric key" });
}
byte[] encryptedKey = null;
try {
encryptedKey = cipher.doFinal(keyBytes);
} catch (IllegalStateException e1) {
throw new WSSecurityException(WSSecurityException.FAILED_ENC_DEC,
null, null, e1);
} catch (IllegalBlockSizeException e1) {
throw new WSSecurityException(WSSecurityException.FAILED_ENC_DEC,
null, null, e1);
} catch (BadPaddingException e1) {
throw new WSSecurityException(WSSecurityException.FAILED_ENC_DEC,
null, null, e1);
}
Text keyText = WSSecurityUtil.createBase64EncodedTextNode(document,
encryptedKey);
/*
* Now we need to setup the EncryptedKey header block 1) create a
* EncryptedKey element and set a wsu:Id for it 2) Generate ds:KeyInfo
* element, this wraps the wsse:SecurityTokenReference 3) Create and set
* up the SecurityTokenReference according to the keyIdentifer parameter
* 4) Create the CipherValue element structure and insert the encrypted
* session key
*/
encryptedKeyElement = createEnrcyptedKey(document, keyEncAlgo);
if(this.encKeyId == null || "".equals(this.encKeyId)) {
this.encKeyId = "EncKeyId-" + encryptedKeyElement.hashCode();
}
encryptedKeyElement.setAttributeNS(null, "Id", this.encKeyId);
KeyInfo keyInfo = new KeyInfo(document);
SecurityTokenReference secToken = new SecurityTokenReference(document);
switch (keyIdentifierType) {
case WSConstants.X509_KEY_IDENTIFIER:
secToken.setKeyIdentifier(remoteCert);
break;
case WSConstants.SKI_KEY_IDENTIFIER:
secToken.setKeyIdentifierSKI(remoteCert, crypto);
break;
case WSConstants.THUMBPRINT_IDENTIFIER:
secToken.setKeyIdentifierThumb(remoteCert);
break;
case WSConstants.ISSUER_SERIAL:
XMLX509IssuerSerial data = new XMLX509IssuerSerial(document,
remoteCert);
X509Data x509Data = new X509Data(document);
x509Data.add(data);
secToken.setX509IssuerSerial(x509Data);
break;
case WSConstants.BST_DIRECT_REFERENCE:
Reference ref = new Reference(document);
ref.setURI("#" + certUri);
bstToken = new X509Security(document);
((X509Security) bstToken).setX509Certificate(remoteCert);
bstToken.setID(certUri);
ref.setValueType(bstToken.getValueType());
secToken.setReference(ref);
break;
default:
throw new WSSecurityException(WSSecurityException.FAILURE,
"unsupportedKeyId");
}
keyInfo.addUnknownElement(secToken.getElement());
WSSecurityUtil.appendChildElement(document, encryptedKeyElement,
keyInfo.getElement());
Element xencCipherValue = createCipherValue(document,
encryptedKeyElement);
xencCipherValue.appendChild(keyText);
envelope = document.getDocumentElement();
envelope.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:"
+ WSConstants.ENC_PREFIX, WSConstants.ENC_NS);
}
| protected void prepareInternal(byte[] keyBytes, X509Certificate remoteCert,
Crypto crypto) throws WSSecurityException {
String certUri = "EncCertId-" + remoteCert.hashCode();
Cipher cipher = WSSecurityUtil.getCipherInstance(keyEncAlgo);
try {
cipher.init(Cipher.ENCRYPT_MODE, remoteCert);
} catch (InvalidKeyException e) {
throw new WSSecurityException(WSSecurityException.FAILED_ENC_DEC,
null, null, e);
}
if (doDebug) {
log.debug("cipher blksize: " + cipher.getBlockSize()
+ ", symm key length: " + keyBytes.length);
}
int blockSize = cipher.getBlockSize();
if (blockSize > 0 && blockSize < keyBytes.length) {
throw new WSSecurityException(WSSecurityException.FAILURE,
"unsupportedKeyTransp",
new Object[] { "public key algorithm too weak to encrypt "
+ "symmetric key" });
}
byte[] encryptedKey = null;
try {
encryptedKey = cipher.doFinal(keyBytes);
} catch (IllegalStateException e1) {
throw new WSSecurityException(WSSecurityException.FAILED_ENC_DEC,
null, null, e1);
} catch (IllegalBlockSizeException e1) {
throw new WSSecurityException(WSSecurityException.FAILED_ENC_DEC,
null, null, e1);
} catch (BadPaddingException e1) {
throw new WSSecurityException(WSSecurityException.FAILED_ENC_DEC,
null, null, e1);
}
Text keyText = WSSecurityUtil.createBase64EncodedTextNode(document,
encryptedKey);
/*
* Now we need to setup the EncryptedKey header block 1) create a
* EncryptedKey element and set a wsu:Id for it 2) Generate ds:KeyInfo
* element, this wraps the wsse:SecurityTokenReference 3) Create and set
* up the SecurityTokenReference according to the keyIdentifer parameter
* 4) Create the CipherValue element structure and insert the encrypted
* session key
*/
encryptedKeyElement = createEnrcyptedKey(document, keyEncAlgo);
if(this.encKeyId == null || "".equals(this.encKeyId)) {
this.encKeyId = "EncKeyId-" + encryptedKeyElement.hashCode();
}
encryptedKeyElement.setAttributeNS(null, "Id", this.encKeyId);
KeyInfo keyInfo = new KeyInfo(document);
SecurityTokenReference secToken = new SecurityTokenReference(document);
switch (keyIdentifierType) {
case WSConstants.X509_KEY_IDENTIFIER:
secToken.setKeyIdentifier(remoteCert);
break;
case WSConstants.SKI_KEY_IDENTIFIER:
secToken.setKeyIdentifierSKI(remoteCert, crypto);
break;
case WSConstants.THUMBPRINT_IDENTIFIER:
secToken.setKeyIdentifierThumb(remoteCert);
break;
case WSConstants.ISSUER_SERIAL:
XMLX509IssuerSerial data = new XMLX509IssuerSerial(document,
remoteCert);
X509Data x509Data = new X509Data(document);
x509Data.add(data);
secToken.setX509IssuerSerial(x509Data);
break;
case WSConstants.BST_DIRECT_REFERENCE:
Reference ref = new Reference(document);
ref.setURI("#" + certUri);
bstToken = new X509Security(document);
((X509Security) bstToken).setX509Certificate(remoteCert);
bstToken.setID(certUri);
ref.setValueType(bstToken.getValueType());
secToken.setReference(ref);
break;
default:
throw new WSSecurityException(WSSecurityException.FAILURE,
"unsupportedKeyId");
}
keyInfo.addUnknownElement(secToken.getElement());
WSSecurityUtil.appendChildElement(document, encryptedKeyElement,
keyInfo.getElement());
Element xencCipherValue = createCipherValue(document,
encryptedKeyElement);
xencCipherValue.appendChild(keyText);
envelope = document.getDocumentElement();
envelope.setAttributeNS(WSConstants.XMLNS_NS, "xmlns:"
+ WSConstants.ENC_PREFIX, WSConstants.ENC_NS);
}
|
diff --git a/h5/CommandLine.java b/h5/CommandLine.java
index 5e105e6..67af478 100644
--- a/h5/CommandLine.java
+++ b/h5/CommandLine.java
@@ -1,23 +1,23 @@
import java.util.Arrays;
import java.util.Comparator;
import java.util.Collections;
public class CommandLine {
public static void main(String [] args) {
if(args[args.length-1].equals("down")) {
Arrays.sort(args,Collections.reverseOrder());
for(String str:args) {
- if(System.getProperty(str) != null){ System.out.println(
- System.getProperty(str));
+ if(System.getProperty(str) != null){
+ System.out.println(System.getProperty(str));
}
}
} else {
Arrays.sort(args);
for(String str:args) {
if(System.getProperty(str) != null){
System.out.println(System.getProperty(str));
}
}
}
}
}
| true | true | public static void main(String [] args) {
if(args[args.length-1].equals("down")) {
Arrays.sort(args,Collections.reverseOrder());
for(String str:args) {
if(System.getProperty(str) != null){ System.out.println(
System.getProperty(str));
}
}
} else {
Arrays.sort(args);
for(String str:args) {
if(System.getProperty(str) != null){
System.out.println(System.getProperty(str));
}
}
}
}
| public static void main(String [] args) {
if(args[args.length-1].equals("down")) {
Arrays.sort(args,Collections.reverseOrder());
for(String str:args) {
if(System.getProperty(str) != null){
System.out.println(System.getProperty(str));
}
}
} else {
Arrays.sort(args);
for(String str:args) {
if(System.getProperty(str) != null){
System.out.println(System.getProperty(str));
}
}
}
}
|
diff --git a/application/src/se/chalmers/dat255/sleepfighter/activities/AlarmSettingsActivity.java b/application/src/se/chalmers/dat255/sleepfighter/activities/AlarmSettingsActivity.java
index 089c06b7..4487d530 100644
--- a/application/src/se/chalmers/dat255/sleepfighter/activities/AlarmSettingsActivity.java
+++ b/application/src/se/chalmers/dat255/sleepfighter/activities/AlarmSettingsActivity.java
@@ -1,157 +1,158 @@
package se.chalmers.dat255.sleepfighter.activities;
import java.util.HashSet;
import java.util.Locale;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.view.MenuItem;
import android.widget.Toast;
import android.support.v4.app.NavUtils;
import se.chalmers.dat255.sleepfighter.R;
import se.chalmers.dat255.sleepfighter.TimepickerPreference;
import se.chalmers.dat255.sleepfighter.debug.Debug;
import se.chalmers.dat255.sleepfighter.model.Alarm;
import se.chalmers.dat255.sleepfighter.model.AlarmList;
import se.chalmers.dat255.sleepfighter.utils.DateTextUtils;
import se.chalmers.dat255.sleepfighter.SFApplication;
public class AlarmSettingsActivity extends PreferenceActivity {
private static final String NAME = "pref_alarm_name";
private static final String TIME = "pref_alarm_time";
private static final String DAYS = "pref_enabled_days";
// is used in sBindPreferenceSummaryToValueListener
private static String[] weekdayStrings;
private static Alarm alarm;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
weekdayStrings = AlarmSettingsActivity.this.getResources().getStringArray(R.array.week_days);
if (getIntent().getExtras() == null) {
throw new IllegalArgumentException();
}
int id = this.getIntent().getExtras().getInt("id");
AlarmList alarms = ((SFApplication) getApplication()).getAlarms();
alarm = alarms.getById(id);
if (alarm == null) {
// TODO: Better handling for final product
Toast.makeText(this, "Alarm is null (ID: " + id + ")", Toast.LENGTH_SHORT).show();
finish();
}
if (!"".equals(alarm.getName())) {
this.setTitle(alarm.getName());
}
// TODO: Remove this debug thing
this.setTitle(this.getTitle() + " (ID: " + alarm.getId() + ")");
setupSimplePreferencesScreen();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
// Using deprecated methods because we need to support Android API level 8
@SuppressWarnings("deprecation")
private void setupSimplePreferencesScreen() {
addPreferencesFromResource(R.xml.pref_alarm_general);
bindPreferenceSummaryToValue(findPreference(TIME));
bindPreferenceSummaryToValue(findPreference(NAME));
bindPreferenceSummaryToValue(findPreference(DAYS));
}
private static Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object value) {
if (TIME.equals(preference.getKey())) {
TimepickerPreference tpPref = (TimepickerPreference) preference;
int hour = tpPref.getHour();
int minute = tpPref.getMinute();
alarm.setTime(hour, minute);
preference.setSummary((hour < 10 ? "0" : "") + hour + ":" + (minute < 10 ? "0" : "") + minute);
}
else if (NAME.equals(preference.getKey())) {
String stringValue = value.toString();
alarm.setName(stringValue);
preference.setSummary(stringValue);
} else if(DAYS.equals(preference.getKey())) {
boolean[] enabledDays = { false, false, false, false, false, false, false };
// a set of all the selected weekdays.
+ @SuppressWarnings("unchecked")
HashSet<String> set = (HashSet<String>)value;
for(int i = 0; i < weekdayStrings.length; ++i) {
if(set.contains(weekdayStrings [i])) {
Debug.d("day enabled: " + weekdayStrings[i]);
enabledDays[i] = true;
}
}
alarm.setEnabledDays(enabledDays);
preference.setSummary(formatDays(alarm));
}
return true;
}
};
private static String formatDays(final Alarm alarm) {
String formatted = "";
// Compute weekday names & join.
final int indiceLength = 2;
final String[] days = DateTextUtils.getWeekdayNames( indiceLength, Locale.getDefault() );
final boolean[] enabled = alarm.getEnabledDays();
for(int i = 0; i < days.length; ++i) {
if(enabled[i] == true) {
formatted += days[i] + " ";
}
}
return formatted;
}
private static void bindPreferenceSummaryToValue(Preference preference) {
preference.setPersistent(false);
if (NAME.equals(preference.getKey())) {
preference.setSummary(alarm.getName());
}
else if (TIME.equals(preference.getKey())) {
preference.setSummary(alarm.getTimeString());
} else if(DAYS.equals(preference.getKey())) {
preference.setSummary(formatDays(alarm));
}
preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
}
}
| true | true | public boolean onPreferenceChange(Preference preference, Object value) {
if (TIME.equals(preference.getKey())) {
TimepickerPreference tpPref = (TimepickerPreference) preference;
int hour = tpPref.getHour();
int minute = tpPref.getMinute();
alarm.setTime(hour, minute);
preference.setSummary((hour < 10 ? "0" : "") + hour + ":" + (minute < 10 ? "0" : "") + minute);
}
else if (NAME.equals(preference.getKey())) {
String stringValue = value.toString();
alarm.setName(stringValue);
preference.setSummary(stringValue);
} else if(DAYS.equals(preference.getKey())) {
boolean[] enabledDays = { false, false, false, false, false, false, false };
// a set of all the selected weekdays.
HashSet<String> set = (HashSet<String>)value;
for(int i = 0; i < weekdayStrings.length; ++i) {
if(set.contains(weekdayStrings [i])) {
Debug.d("day enabled: " + weekdayStrings[i]);
enabledDays[i] = true;
}
}
alarm.setEnabledDays(enabledDays);
preference.setSummary(formatDays(alarm));
}
return true;
}
| public boolean onPreferenceChange(Preference preference, Object value) {
if (TIME.equals(preference.getKey())) {
TimepickerPreference tpPref = (TimepickerPreference) preference;
int hour = tpPref.getHour();
int minute = tpPref.getMinute();
alarm.setTime(hour, minute);
preference.setSummary((hour < 10 ? "0" : "") + hour + ":" + (minute < 10 ? "0" : "") + minute);
}
else if (NAME.equals(preference.getKey())) {
String stringValue = value.toString();
alarm.setName(stringValue);
preference.setSummary(stringValue);
} else if(DAYS.equals(preference.getKey())) {
boolean[] enabledDays = { false, false, false, false, false, false, false };
// a set of all the selected weekdays.
@SuppressWarnings("unchecked")
HashSet<String> set = (HashSet<String>)value;
for(int i = 0; i < weekdayStrings.length; ++i) {
if(set.contains(weekdayStrings [i])) {
Debug.d("day enabled: " + weekdayStrings[i]);
enabledDays[i] = true;
}
}
alarm.setEnabledDays(enabledDays);
preference.setSummary(formatDays(alarm));
}
return true;
}
|
diff --git a/PlayersInCubes/src/me/asofold/bukkit/pic/core/CubeServer.java b/PlayersInCubes/src/me/asofold/bukkit/pic/core/CubeServer.java
index c4f4790..9fa534e 100644
--- a/PlayersInCubes/src/me/asofold/bukkit/pic/core/CubeServer.java
+++ b/PlayersInCubes/src/me/asofold/bukkit/pic/core/CubeServer.java
@@ -1,68 +1,69 @@
package me.asofold.bukkit.pic.core;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
*
* @author mc_dev
*
*/
public final class CubeServer {
private final Map<CubePos, CubeData> cubes = new HashMap<CubePos, CubeData>(500);
public PicCore core;
public final int cubeSize;
public CubeServer(final PicCore core, int cubeSize){
this.core = core;
this.cubeSize = cubeSize;
}
/**
* Called when a CubeData has no players anymore.
* @param cubeData
*/
public final void cubeEmpty(final CubeData cubeData) {
cubes.remove(cubeData.cube);
// TODO: park it. ? Map by hash directly into an Array of lists + check for new cubes by hash ?
}
public final void renderBlind(final PicPlayer pp, final Set<String> names) {
core.renderBlind(pp, names);
}
public final void renderSeen(final PicPlayer pp, final Set<String> names) {
core.renderSeen(pp, names);
}
/**
* Check which cubes have to be added.
* @param pp
* @param distCube Maximal distance to cube centers.
*/
public final void update(final PicPlayer pp, final int distCube) {
// Dumb: check all cubes within distance
for (int x = pp.x - distCube; x < pp.x + distCube; x += cubeSize){
for (int y = pp.y - distCube; y < pp.y + distCube; y += cubeSize){
for (int z = pp.z - distCube; z < pp.z + distCube; z += cubeSize){
// TODO: optimize here and just get the hash later
- final CubePos pos = new Cube(x, y, z, cubeSize);
+ final CubePos pos = new CubePos(x, y, z);
if (pp.cubes.contains(pos)) continue;
CubeData data = cubes.get(pos);
if (data == null){
// create new one
data = new CubeData(new Cube(x, y, z, cubeSize), this);
cubes.put(pos, data);
}
data.add(pp);
+ pp.cubes.add(data);
}
}
}
}
}
| false | true | public final void update(final PicPlayer pp, final int distCube) {
// Dumb: check all cubes within distance
for (int x = pp.x - distCube; x < pp.x + distCube; x += cubeSize){
for (int y = pp.y - distCube; y < pp.y + distCube; y += cubeSize){
for (int z = pp.z - distCube; z < pp.z + distCube; z += cubeSize){
// TODO: optimize here and just get the hash later
final CubePos pos = new Cube(x, y, z, cubeSize);
if (pp.cubes.contains(pos)) continue;
CubeData data = cubes.get(pos);
if (data == null){
// create new one
data = new CubeData(new Cube(x, y, z, cubeSize), this);
cubes.put(pos, data);
}
data.add(pp);
}
}
}
}
| public final void update(final PicPlayer pp, final int distCube) {
// Dumb: check all cubes within distance
for (int x = pp.x - distCube; x < pp.x + distCube; x += cubeSize){
for (int y = pp.y - distCube; y < pp.y + distCube; y += cubeSize){
for (int z = pp.z - distCube; z < pp.z + distCube; z += cubeSize){
// TODO: optimize here and just get the hash later
final CubePos pos = new CubePos(x, y, z);
if (pp.cubes.contains(pos)) continue;
CubeData data = cubes.get(pos);
if (data == null){
// create new one
data = new CubeData(new Cube(x, y, z, cubeSize), this);
cubes.put(pos, data);
}
data.add(pp);
pp.cubes.add(data);
}
}
}
}
|
diff --git a/java-api/src/de/zib/scalaris/Benchmark.java b/java-api/src/de/zib/scalaris/Benchmark.java
index 5f87d485..258ad459 100644
--- a/java-api/src/de/zib/scalaris/Benchmark.java
+++ b/java-api/src/de/zib/scalaris/Benchmark.java
@@ -1,933 +1,933 @@
/**
* Copyright 2007-2011 Zuse Institute Berlin
*
* 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 de.zib.scalaris;
import java.util.Random;
import com.ericsson.otp.erlang.OtpErlangBinary;
import com.ericsson.otp.erlang.OtpErlangString;
/**
* Provides methods to run benchmarks and print the results.
*
* Also provides some default benchmarks.
*
* @author Nico Kruber, [email protected]
* @version 2.0
* @since 2.0
*/
public class Benchmark {
/**
* The size of a single data item that is send to scalaris.
*/
protected static final int BENCH_DATA_SIZE = 1000;
/**
* The time when the (whole) benchmark suite was started.
*
* This is used to create different erlang keys for each run.
*/
protected static long benchTime = System.currentTimeMillis();
/**
* The time at the start of a single benchmark.
*/
protected static long timeAtStart = 0;
/**
* Default minimal benchmark.
*
* Tests some strategies for writing key/value pairs to scalaris:
* <ol>
* <li>writing {@link OtpErlangBinary} objects (random data, size =
* {@link #BENCH_DATA_SIZE})</li>
* <li>writing {@link OtpErlangString} objects (random data, size =
* {@link #BENCH_DATA_SIZE})</li>
* <li>writing {@link String} objects (random data, size =
* {@link #BENCH_DATA_SIZE})</li>
* </ol>
* each testruns times
* <ul>
* <li>first using a new {@link Transaction} for each test,</li>
* <li>then using a new {@link Transaction} but re-using a single
* {@link Connection},</li>
* <li>and finally re-using a single {@link Transaction} object.</li>
* </ul>
*
* @param testruns
* the number of test runs to execute
* @param benchmarks
* the benchmarks to run (1-9 or -1 for all benchmarks)
*/
public static void minibench(int testruns, int benchmarks) {
long[][] results = new long[3][3];
String[] columns;
String[] rows;
System.out.println("Benchmark of de.zib.scalaris.TransactionSingleOp:");
results[0][0] = benchmarks == -1 || benchmarks == 1 ? scalarisBench1(BENCH_DATA_SIZE, testruns) : -1;
results[1][0] = benchmarks == -1 || benchmarks == 2 ? scalarisBench2(BENCH_DATA_SIZE, testruns) : -1;
results[2][0] = benchmarks == -1 || benchmarks == 3 ? scalarisBench3(BENCH_DATA_SIZE, testruns) : -1;
results[0][1] = benchmarks == -1 || benchmarks == 4 ? scalarisBench4(BENCH_DATA_SIZE, testruns) : -1;
results[1][1] = benchmarks == -1 || benchmarks == 5 ? scalarisBench5(BENCH_DATA_SIZE, testruns) : -1;
results[2][1] = benchmarks == -1 || benchmarks == 6 ? scalarisBench6(BENCH_DATA_SIZE, testruns) : -1;
results[0][2] = benchmarks == -1 || benchmarks == 7 ? scalarisBench7(BENCH_DATA_SIZE, testruns) : -1;
results[1][2] = benchmarks == -1 || benchmarks == 8 ? scalarisBench8(BENCH_DATA_SIZE, testruns) : -1;
results[2][2] = benchmarks == -1 || benchmarks == 9 ? scalarisBench9(BENCH_DATA_SIZE, testruns) : -1;
columns = new String[] {
"TransactionSingleOp.writeObject(OtpErlangString, OtpErlangBinary)",
"TransactionSingleOp.writeObject(OtpErlangString, OtpErlangString)",
"TransactionSingleOp.write(String, String)" };
rows = new String[] {
"separate connection",
"re-use connection",
- "re-use TransactionSingleOp object" };
+ "re-use object" };
printResults(columns, rows, results, testruns);
results = new long[3][3];
System.out.println("-----");
System.out.println("Benchmark of de.zib.scalaris.Transaction:");
results[0][0] = benchmarks == -1 || benchmarks == 1 ? transBench1(BENCH_DATA_SIZE, testruns) : -1;
results[1][0] = benchmarks == -1 || benchmarks == 2 ? transBench2(BENCH_DATA_SIZE, testruns) : -1;
results[2][0] = benchmarks == -1 || benchmarks == 3 ? transBench3(BENCH_DATA_SIZE, testruns) : -1;
results[0][1] = benchmarks == -1 || benchmarks == 4 ? transBench4(BENCH_DATA_SIZE, testruns) : -1;
results[1][1] = benchmarks == -1 || benchmarks == 5 ? transBench5(BENCH_DATA_SIZE, testruns) : -1;
results[2][1] = benchmarks == -1 || benchmarks == 6 ? transBench6(BENCH_DATA_SIZE, testruns) : -1;
results[0][2] = benchmarks == -1 || benchmarks == 7 ? transBench7(BENCH_DATA_SIZE, testruns) : -1;
results[1][2] = benchmarks == -1 || benchmarks == 8 ? transBench8(BENCH_DATA_SIZE, testruns) : -1;
results[2][2] = benchmarks == -1 || benchmarks == 9 ? transBench9(BENCH_DATA_SIZE, testruns) : -1;
columns = new String[] {
"Transaction.writeObject(OtpErlangString, OtpErlangBinary)",
"Transaction.writeObject(OtpErlangString, OtpErlangString)",
"Transaction.write(String, String)" };
rows = new String[] {
"separate connection",
"re-use connection",
- "re-use transaction" };
+ "re-use object" };
printResults(columns, rows, results, testruns);
}
/**
* Prints a result table.
*
* @param columns
* names of the columns
* @param rows
* names of the rows (max 25 chars to protect the layout)
*
* @param results
* the results to print (results[i][j]: i = row, j = column)
*/
protected static void printResults(String[] columns, String[] rows,
long[][] results, int testruns) {
System.out.println("Test runs: " + testruns);
System.out
.println(" \tspeed (transactions / second)");
final String firstColumn = " ";
System.out.print(firstColumn);
for (int i = 0; i < columns.length; ++i) {
System.out.print("\t(" + (i + 1) + ")");
}
System.out.println();
for (int i = 0; i < rows.length; ++i) {
System.out.print(rows[i]
+ firstColumn.substring(0, firstColumn.length()
- rows[i].length() - 1));
for (int j = 0; j < columns.length; j++) {
if (results[i][j] == -1) {
System.out.print("\tn/a");
} else {
System.out.print("\t" + results[i][j]);
}
}
System.out.println();
}
for (int i = 0; i < columns.length; i++) {
System.out.println("(" + (i + 1) + ") " + columns[i]);
}
}
/**
* Call this method when a benchmark is started.
*
* Sets the time the benchmark was started.
*/
final protected static void testBegin() {
timeAtStart = System.currentTimeMillis();
}
/**
* Call this method when a benchmark is finished.
*
* Calculates the time the benchmark took and the number of transactions
* performed during this time.
*
* @return the number of achieved transactions per second
*/
final protected static long testEnd(int testRuns) {
long timeTaken = System.currentTimeMillis() - timeAtStart;
long speed = (testRuns * 1000) / timeTaken;
// System.out.println(" transactions : " + testRuns);
// System.out.println(" time : " + timeTaken + "ms");
// System.out.println(" speed : " + speed + " Transactions/s");
return speed;
}
/**
* Performs a benchmark writing {@link OtpErlangBinary} objects (random
* data, size = {@link #BENCH_DATA_SIZE}) using a new {@link Transaction}
* for each test.
*
* @param size
* the size of a single data item
* @param testRuns
* the number of times to write the value
*
* @return the number of achieved transactions per second
*/
protected static long transBench1(int size, int testRuns) {
try {
// System.out.println("Testing Transaction().writeObject(OtpErlangString, OtpErlangBinary) "
// +
// "with separate connections...");
byte[] data = new byte[size];
Random r = new Random();
r.nextBytes(data);
String key = benchTime + "_transBench1";
OtpErlangBinary value = new OtpErlangBinary(data);
testBegin();
for (int i = 0; i < testRuns; ++i) {
Transaction transaction = new Transaction();
transaction.writeObject(new OtpErlangString(key + i), value);
transaction.commit();
transaction.closeConnection();
}
long speed = testEnd(testRuns);
return speed;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* Performs a benchmark writing {@link OtpErlangBinary} objects (random
* data, size = {@link #BENCH_DATA_SIZE}) using a new {@link Transaction}
* but re-using a single {@link Connection} for each test.
*
* @param size
* the size of a single data item
* @param testRuns
* the number of times to write the value
*
* @return the number of achieved transactions per second
*/
protected static long transBench2(int size, int testRuns) {
try {
// System.out.println("Testing Transaction(Connection).writeObject(OtpErlangString, OtpErlangBinary) "
// +
// "re-using a single connection...");
byte[] data = new byte[size];
Random r = new Random();
r.nextBytes(data);
String key = benchTime + "_transBench2";
OtpErlangBinary value = new OtpErlangBinary(data);
testBegin();
Connection connection = ConnectionFactory.getInstance()
.createConnection();
for (int i = 0; i < testRuns; ++i) {
Transaction transaction = new Transaction(connection);
transaction.writeObject(new OtpErlangString(key + i), value);
transaction.commit();
}
connection.close();
long speed = testEnd(testRuns);
return speed;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* Performs a benchmark writing {@link OtpErlangBinary} objects (random
* data, size = {@link #BENCH_DATA_SIZE}) using a single {@link Transaction}
* object for all tests.
*
* @param size
* the size of a single data item
* @param testRuns
* the number of times to write the value
*
* @return the number of achieved transactions per second
*/
protected static long transBench3(int size, int testRuns) {
try {
// System.out.println("Testing Transaction().writeObject(OtpErlangString, OtpErlangBinary) "
// +
// "re-using a single transaction...");
byte[] data = new byte[size];
Random r = new Random();
r.nextBytes(data);
String key = benchTime + "_transBench3";
OtpErlangBinary value = new OtpErlangBinary(data);
testBegin();
Transaction transaction = new Transaction();
for (int i = 0; i < testRuns; ++i) {
transaction.writeObject(new OtpErlangString(key + i), value);
transaction.commit();
}
transaction.closeConnection();
long speed = testEnd(testRuns);
return speed;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* Performs a benchmark writing {@link OtpErlangString} objects (random
* data, size = {@link #BENCH_DATA_SIZE}) first using a new
* {@link Transaction} for each test.
*
* @param size
* the size of a single data item
* @param testRuns
* the number of times to write the value
*
* @return the number of achieved transactions per second
*/
protected static long transBench4(int size, int testRuns) {
try {
// System.out.println("Testing Transaction().writeObject(OtpErlangString, OtpErlangString) "
// +
// "with separate connections...");
byte[] data = new byte[size];
Random r = new Random();
r.nextBytes(data);
String key = benchTime + "_transBench4";
OtpErlangString value = new OtpErlangString(new String(data));
testBegin();
for (int i = 0; i < testRuns; ++i) {
Transaction transaction = new Transaction();
transaction.writeObject(new OtpErlangString(key + i), value);
transaction.commit();
transaction.closeConnection();
}
long speed = testEnd(testRuns);
return speed;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* Performs a benchmark writing {@link OtpErlangString} objects (random
* data, size = {@link #BENCH_DATA_SIZE}) using a new {@link Transaction}
* but re-using a single {@link Connection} for each test.
*
* @param size
* the size of a single data item
* @param testRuns
* the number of times to write the value
*
* @return the number of achieved transactions per second
*/
protected static long transBench5(int size, int testRuns) {
try {
// System.out.println("Testing Transaction(Connection).writeObject(OtpErlangString, OtpErlangString) "
// +
// "re-using a single connection...");
byte[] data = new byte[size];
Random r = new Random();
r.nextBytes(data);
String key = benchTime + "_transBench5";
OtpErlangString value = new OtpErlangString(new String(data));
testBegin();
Connection connection = ConnectionFactory.getInstance()
.createConnection();
for (int i = 0; i < testRuns; ++i) {
Transaction transaction = new Transaction(connection);
transaction.writeObject(new OtpErlangString(key + i), value);
transaction.commit();
}
connection.close();
long speed = testEnd(testRuns);
return speed;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* Performs a benchmark writing {@link OtpErlangString} objects (random
* data, size = {@link #BENCH_DATA_SIZE}) re-using a single
* {@link Transaction} object for all tests..
*
* @param size
* the size of a single data item
* @param testRuns
* the number of times to write the value
*
* @return the number of achieved transactions per second
*/
protected static long transBench6(int size, int testRuns) {
try {
// System.out.println("Testing Transaction().writeObject(OtpErlangString, OtpErlangString) "
// +
// "re-using a single transaction...");
byte[] data = new byte[size];
Random r = new Random();
r.nextBytes(data);
String key = benchTime + "_transBench6";
OtpErlangString value = new OtpErlangString(new String(data));
testBegin();
Transaction transaction = new Transaction();
for (int i = 0; i < testRuns; ++i) {
transaction.writeObject(new OtpErlangString(key + i), value);
transaction.commit();
}
transaction.closeConnection();
long speed = testEnd(testRuns);
return speed;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* Performs a benchmark writing {@link String} objects (random data, size =
* {@link #BENCH_DATA_SIZE}) using a new {@link Transaction} for each test.
*
* @param size
* the size of a single data item
* @param testRuns
* the number of times to write the value
*
* @return the number of achieved transactions per second
*/
protected static long transBench7(int size, int testRuns) {
try {
// System.out.println("Testing Transaction().write(String, String) "
// +
// "with separate connections...");
byte[] data = new byte[size];
Random r = new Random();
r.nextBytes(data);
String key = benchTime + "_transBench7";
String value = new String(data);
testBegin();
for (int i = 0; i < testRuns; ++i) {
Transaction transaction = new Transaction();
transaction.write(key + i, value);
transaction.commit();
transaction.closeConnection();
}
long speed = testEnd(testRuns);
return speed;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* Performs a benchmark writing {@link String} objects (random data, size =
* {@link #BENCH_DATA_SIZE}) using a new {@link Transaction} but re-using a
* single {@link Connection} for each test.
*
* @param size
* the size of a single data item
* @param testRuns
* the number of times to write the value
*
* @return the number of achieved transactions per second
*/
protected static long transBench8(int size, int testRuns) {
try {
// System.out.println("Testing Transaction(Connection).write(String, String) "
// +
// "re-using a single connection...");
byte[] data = new byte[size];
Random r = new Random();
r.nextBytes(data);
String key = benchTime + "_transBench8";
String value = new String(data);
testBegin();
Connection connection = ConnectionFactory.getInstance()
.createConnection();
for (int i = 0; i < testRuns; ++i) {
Transaction transaction = new Transaction(connection);
transaction.write(key + i, value);
transaction.commit();
}
connection.close();
long speed = testEnd(testRuns);
return speed;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* Performs a benchmark writing {@link String} objects (random data, size =
* {@link #BENCH_DATA_SIZE}) re-using a single {@link Transaction} object
* for all tests.
*
* @param size
* the size of a single data item
* @param testRuns
* the number of times to write the value
*
* @return the number of achieved transactions per second
*/
protected static long transBench9(int size, int testRuns) {
try {
// System.out.println("Testing Transaction().write(String, String) "
// +
// "re-using a single transaction...");
byte[] data = new byte[size];
Random r = new Random();
r.nextBytes(data);
String key = benchTime + "_transBench9";
String value = new String(data);
testBegin();
Transaction transaction = new Transaction();
for (int i = 0; i < testRuns; ++i) {
transaction.write(key + i, value);
transaction.commit();
}
transaction.closeConnection();
long speed = testEnd(testRuns);
return speed;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* Performs a benchmark writing {@link OtpErlangBinary} objects (random
* data, size = {@link #BENCH_DATA_SIZE}) using a new {@link TransactionSingleOp}
* object for each test.
*
* @param size
* the size of a single data item
* @param testRuns
* the number of times to write the value
*
* @return the number of achieved transactions per second
*/
protected static long scalarisBench1(int size, int testRuns) {
try {
// System.out.println("Testing TransactionSingleOp().writeObject(OtpErlangString, OtpErlangBinary) "
// +
// "with separate connections...");
byte[] data = new byte[size];
Random r = new Random();
r.nextBytes(data);
String key = benchTime + "_scalarisBench1";
OtpErlangBinary value = new OtpErlangBinary(data);
testBegin();
for (int i = 0; i < testRuns; ++i) {
TransactionSingleOp sc = new TransactionSingleOp();
sc.writeObject(new OtpErlangString(key + i), value);
sc.closeConnection();
}
long speed = testEnd(testRuns);
return speed;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* Performs a benchmark writing {@link OtpErlangBinary} objects (random
* data, size = {@link #BENCH_DATA_SIZE}) using a new {@link TransactionSingleOp}
* object but re-using a single {@link Connection} for each test.
*
* @param size
* the size of a single data item
* @param testRuns
* the number of times to write the value
*
* @return the number of achieved transactions per second
*/
protected static long scalarisBench2(int size, int testRuns) {
try {
// System.out.println("Testing TransactionSingleOp(Connection).writeObject(OtpErlangString, OtpErlangBinary) "
// +
// "re-using a single connection...");
byte[] data = new byte[size];
Random r = new Random();
r.nextBytes(data);
String key = benchTime + "_scalarisBench2";
OtpErlangBinary value = new OtpErlangBinary(data);
testBegin();
Connection connection = ConnectionFactory.getInstance()
.createConnection();
for (int i = 0; i < testRuns; ++i) {
TransactionSingleOp sc = new TransactionSingleOp(connection);
sc.writeObject(new OtpErlangString(key + i), value);
}
connection.close();
long speed = testEnd(testRuns);
return speed;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* Performs a benchmark writing {@link OtpErlangBinary} objects (random
* data, size = {@link #BENCH_DATA_SIZE}) using a single {@link TransactionSingleOp}
* object for all tests.
*
* @param size
* the size of a single data item
* @param testRuns
* the number of times to write the value
*
* @return the number of achieved transactions per second
*/
protected static long scalarisBench3(int size, int testRuns) {
try {
// System.out.println("Testing TransactionSingleOp().writeObject(OtpErlangString, OtpErlangBinary) "
// +
// "re-using a single transaction...");
byte[] data = new byte[size];
Random r = new Random();
r.nextBytes(data);
String key = benchTime + "_scalarisBench3";
OtpErlangBinary value = new OtpErlangBinary(data);
testBegin();
TransactionSingleOp sc = new TransactionSingleOp();
for (int i = 0; i < testRuns; ++i) {
sc.writeObject(new OtpErlangString(key + i), value);
}
sc.closeConnection();
long speed = testEnd(testRuns);
return speed;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* Performs a benchmark writing {@link OtpErlangString} objects (random
* data, size = {@link #BENCH_DATA_SIZE}) first using a new
* {@link TransactionSingleOp} object for each test.
*
* @param size
* the size of a single data item
* @param testRuns
* the number of times to write the value
*
* @return the number of achieved transactions per second
*/
protected static long scalarisBench4(int size, int testRuns) {
try {
// System.out.println("Testing TransactionSingleOp().writeObject(OtpErlangString, OtpErlangString) "
// +
// "with separate connections...");
byte[] data = new byte[size];
Random r = new Random();
r.nextBytes(data);
String key = benchTime + "_scalarisBench4";
OtpErlangString value = new OtpErlangString(new String(data));
testBegin();
for (int i = 0; i < testRuns; ++i) {
TransactionSingleOp sc = new TransactionSingleOp();
sc.writeObject(new OtpErlangString(key + i), value);
sc.closeConnection();
}
long speed = testEnd(testRuns);
return speed;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* Performs a benchmark writing {@link OtpErlangString} objects (random
* data, size = {@link #BENCH_DATA_SIZE}) using a new {@link TransactionSingleOp}
* object but re-using a single {@link Connection} for each test.
*
* @param size
* the size of a single data item
* @param testRuns
* the number of times to write the value
*
* @return the number of achieved transactions per second
*/
protected static long scalarisBench5(int size, int testRuns) {
try {
// System.out.println("Testing TransactionSingleOp(Connection).writeObject(OtpErlangString, OtpErlangString) "
// +
// "re-using a single connection...");
byte[] data = new byte[size];
Random r = new Random();
r.nextBytes(data);
String key = benchTime + "_scalarisBench5";
OtpErlangString value = new OtpErlangString(new String(data));
testBegin();
Connection connection = ConnectionFactory.getInstance()
.createConnection();
for (int i = 0; i < testRuns; ++i) {
TransactionSingleOp sc = new TransactionSingleOp(connection);
sc.writeObject(new OtpErlangString(key + i), value);
}
connection.close();
long speed = testEnd(testRuns);
return speed;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* Performs a benchmark writing {@link OtpErlangString} objects (random
* data, size = {@link #BENCH_DATA_SIZE}) re-using a single
* {@link TransactionSingleOp} object for all tests..
*
* @param size
* the size of a single data item
* @param testRuns
* the number of times to write the value
*
* @return the number of achieved transactions per second
*/
protected static long scalarisBench6(int size, int testRuns) {
try {
// System.out.println("Testing TransactionSingleOp().writeObject(OtpErlangString, OtpErlangString) "
// +
// "re-using a single transaction...");
byte[] data = new byte[size];
Random r = new Random();
r.nextBytes(data);
String key = benchTime + "_scalarisBench6";
OtpErlangString value = new OtpErlangString(new String(data));
testBegin();
TransactionSingleOp sc = new TransactionSingleOp();
for (int i = 0; i < testRuns; ++i) {
sc.writeObject(new OtpErlangString(key + i), value);
}
sc.closeConnection();
long speed = testEnd(testRuns);
return speed;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* Performs a benchmark writing {@link String} objects (random data, size =
* {@link #BENCH_DATA_SIZE}) using a new {@link TransactionSingleOp} object for each
* test.
*
* @param size
* the size of a single data item
* @param testRuns
* the number of times to write the value
*
* @return the number of achieved transactions per second
*/
protected static long scalarisBench7(int size, int testRuns) {
try {
// System.out.println("Testing TransactionSingleOp().write(String, String) "
// +
// "with separate connections...");
byte[] data = new byte[size];
Random r = new Random();
r.nextBytes(data);
String key = benchTime + "_scalarisBench7";
String value = new String(data);
testBegin();
for (int i = 0; i < testRuns; ++i) {
TransactionSingleOp sc = new TransactionSingleOp();
sc.write(key + i, value);
sc.closeConnection();
}
long speed = testEnd(testRuns);
return speed;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* Performs a benchmark writing {@link String} objects (random data, size =
* {@link #BENCH_DATA_SIZE}) using a new {@link TransactionSingleOp} object but
* re-using a single {@link Connection} for each test.
*
* @param size
* the size of a single data item
* @param testRuns
* the number of times to write the value
*
* @return the number of achieved transactions per second
*/
protected static long scalarisBench8(int size, int testRuns) {
try {
// System.out.println("Testing TransactionSingleOp(Connection).write(String, String) "
// +
// "re-using a single connection...");
byte[] data = new byte[size];
Random r = new Random();
r.nextBytes(data);
String key = benchTime + "_scalarisBench8";
String value = new String(data);
testBegin();
Connection connection = ConnectionFactory.getInstance()
.createConnection();
for (int i = 0; i < testRuns; ++i) {
TransactionSingleOp sc = new TransactionSingleOp(connection);
sc.write(key + i, value);
}
connection.close();
long speed = testEnd(testRuns);
return speed;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* Performs a benchmark writing {@link String} objects (random data, size =
* {@link #BENCH_DATA_SIZE}) re-using a single {@link TransactionSingleOp} object for
* all tests.
*
* @param size
* the size of a single data item
* @param testRuns
* the number of times to write the value
*
* @return the number of achieved transactions per second
*/
protected static long scalarisBench9(int size, int testRuns) {
try {
// System.out.println("Testing TransactionSingleOp().write(String, String) "
// +
// "re-using a single transaction...");
byte[] data = new byte[size];
Random r = new Random();
r.nextBytes(data);
String key = benchTime + "_scalarisBench9";
String value = new String(data);
testBegin();
TransactionSingleOp sc = new TransactionSingleOp();
for (int i = 0; i < testRuns; ++i) {
sc.write(key + i, value);
}
sc.closeConnection();
long speed = testEnd(testRuns);
return speed;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
| false | true | public static void minibench(int testruns, int benchmarks) {
long[][] results = new long[3][3];
String[] columns;
String[] rows;
System.out.println("Benchmark of de.zib.scalaris.TransactionSingleOp:");
results[0][0] = benchmarks == -1 || benchmarks == 1 ? scalarisBench1(BENCH_DATA_SIZE, testruns) : -1;
results[1][0] = benchmarks == -1 || benchmarks == 2 ? scalarisBench2(BENCH_DATA_SIZE, testruns) : -1;
results[2][0] = benchmarks == -1 || benchmarks == 3 ? scalarisBench3(BENCH_DATA_SIZE, testruns) : -1;
results[0][1] = benchmarks == -1 || benchmarks == 4 ? scalarisBench4(BENCH_DATA_SIZE, testruns) : -1;
results[1][1] = benchmarks == -1 || benchmarks == 5 ? scalarisBench5(BENCH_DATA_SIZE, testruns) : -1;
results[2][1] = benchmarks == -1 || benchmarks == 6 ? scalarisBench6(BENCH_DATA_SIZE, testruns) : -1;
results[0][2] = benchmarks == -1 || benchmarks == 7 ? scalarisBench7(BENCH_DATA_SIZE, testruns) : -1;
results[1][2] = benchmarks == -1 || benchmarks == 8 ? scalarisBench8(BENCH_DATA_SIZE, testruns) : -1;
results[2][2] = benchmarks == -1 || benchmarks == 9 ? scalarisBench9(BENCH_DATA_SIZE, testruns) : -1;
columns = new String[] {
"TransactionSingleOp.writeObject(OtpErlangString, OtpErlangBinary)",
"TransactionSingleOp.writeObject(OtpErlangString, OtpErlangString)",
"TransactionSingleOp.write(String, String)" };
rows = new String[] {
"separate connection",
"re-use connection",
"re-use TransactionSingleOp object" };
printResults(columns, rows, results, testruns);
results = new long[3][3];
System.out.println("-----");
System.out.println("Benchmark of de.zib.scalaris.Transaction:");
results[0][0] = benchmarks == -1 || benchmarks == 1 ? transBench1(BENCH_DATA_SIZE, testruns) : -1;
results[1][0] = benchmarks == -1 || benchmarks == 2 ? transBench2(BENCH_DATA_SIZE, testruns) : -1;
results[2][0] = benchmarks == -1 || benchmarks == 3 ? transBench3(BENCH_DATA_SIZE, testruns) : -1;
results[0][1] = benchmarks == -1 || benchmarks == 4 ? transBench4(BENCH_DATA_SIZE, testruns) : -1;
results[1][1] = benchmarks == -1 || benchmarks == 5 ? transBench5(BENCH_DATA_SIZE, testruns) : -1;
results[2][1] = benchmarks == -1 || benchmarks == 6 ? transBench6(BENCH_DATA_SIZE, testruns) : -1;
results[0][2] = benchmarks == -1 || benchmarks == 7 ? transBench7(BENCH_DATA_SIZE, testruns) : -1;
results[1][2] = benchmarks == -1 || benchmarks == 8 ? transBench8(BENCH_DATA_SIZE, testruns) : -1;
results[2][2] = benchmarks == -1 || benchmarks == 9 ? transBench9(BENCH_DATA_SIZE, testruns) : -1;
columns = new String[] {
"Transaction.writeObject(OtpErlangString, OtpErlangBinary)",
"Transaction.writeObject(OtpErlangString, OtpErlangString)",
"Transaction.write(String, String)" };
rows = new String[] {
"separate connection",
"re-use connection",
"re-use transaction" };
printResults(columns, rows, results, testruns);
}
| public static void minibench(int testruns, int benchmarks) {
long[][] results = new long[3][3];
String[] columns;
String[] rows;
System.out.println("Benchmark of de.zib.scalaris.TransactionSingleOp:");
results[0][0] = benchmarks == -1 || benchmarks == 1 ? scalarisBench1(BENCH_DATA_SIZE, testruns) : -1;
results[1][0] = benchmarks == -1 || benchmarks == 2 ? scalarisBench2(BENCH_DATA_SIZE, testruns) : -1;
results[2][0] = benchmarks == -1 || benchmarks == 3 ? scalarisBench3(BENCH_DATA_SIZE, testruns) : -1;
results[0][1] = benchmarks == -1 || benchmarks == 4 ? scalarisBench4(BENCH_DATA_SIZE, testruns) : -1;
results[1][1] = benchmarks == -1 || benchmarks == 5 ? scalarisBench5(BENCH_DATA_SIZE, testruns) : -1;
results[2][1] = benchmarks == -1 || benchmarks == 6 ? scalarisBench6(BENCH_DATA_SIZE, testruns) : -1;
results[0][2] = benchmarks == -1 || benchmarks == 7 ? scalarisBench7(BENCH_DATA_SIZE, testruns) : -1;
results[1][2] = benchmarks == -1 || benchmarks == 8 ? scalarisBench8(BENCH_DATA_SIZE, testruns) : -1;
results[2][2] = benchmarks == -1 || benchmarks == 9 ? scalarisBench9(BENCH_DATA_SIZE, testruns) : -1;
columns = new String[] {
"TransactionSingleOp.writeObject(OtpErlangString, OtpErlangBinary)",
"TransactionSingleOp.writeObject(OtpErlangString, OtpErlangString)",
"TransactionSingleOp.write(String, String)" };
rows = new String[] {
"separate connection",
"re-use connection",
"re-use object" };
printResults(columns, rows, results, testruns);
results = new long[3][3];
System.out.println("-----");
System.out.println("Benchmark of de.zib.scalaris.Transaction:");
results[0][0] = benchmarks == -1 || benchmarks == 1 ? transBench1(BENCH_DATA_SIZE, testruns) : -1;
results[1][0] = benchmarks == -1 || benchmarks == 2 ? transBench2(BENCH_DATA_SIZE, testruns) : -1;
results[2][0] = benchmarks == -1 || benchmarks == 3 ? transBench3(BENCH_DATA_SIZE, testruns) : -1;
results[0][1] = benchmarks == -1 || benchmarks == 4 ? transBench4(BENCH_DATA_SIZE, testruns) : -1;
results[1][1] = benchmarks == -1 || benchmarks == 5 ? transBench5(BENCH_DATA_SIZE, testruns) : -1;
results[2][1] = benchmarks == -1 || benchmarks == 6 ? transBench6(BENCH_DATA_SIZE, testruns) : -1;
results[0][2] = benchmarks == -1 || benchmarks == 7 ? transBench7(BENCH_DATA_SIZE, testruns) : -1;
results[1][2] = benchmarks == -1 || benchmarks == 8 ? transBench8(BENCH_DATA_SIZE, testruns) : -1;
results[2][2] = benchmarks == -1 || benchmarks == 9 ? transBench9(BENCH_DATA_SIZE, testruns) : -1;
columns = new String[] {
"Transaction.writeObject(OtpErlangString, OtpErlangBinary)",
"Transaction.writeObject(OtpErlangString, OtpErlangString)",
"Transaction.write(String, String)" };
rows = new String[] {
"separate connection",
"re-use connection",
"re-use object" };
printResults(columns, rows, results, testruns);
}
|
diff --git a/HDX-System/src/main/java/org/ocha/hdx/exporter/country/AbstractExporterCountry_XLSX.java b/HDX-System/src/main/java/org/ocha/hdx/exporter/country/AbstractExporterCountry_XLSX.java
index fe3ee9c..44da3ef 100644
--- a/HDX-System/src/main/java/org/ocha/hdx/exporter/country/AbstractExporterCountry_XLSX.java
+++ b/HDX-System/src/main/java/org/ocha/hdx/exporter/country/AbstractExporterCountry_XLSX.java
@@ -1,137 +1,137 @@
package org.ocha.hdx.exporter.country;
import java.util.ArrayList;
import java.util.Map;
import org.apache.poi.ss.util.WorkbookUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.ocha.hdx.exporter.Exporter;
import org.ocha.hdx.exporter.Exporter_XLSX;
import org.ocha.hdx.exporter.helper.ReportRow;
import org.ocha.hdx.service.ExporterService;
public abstract class AbstractExporterCountry_XLSX extends Exporter_XLSX<ExporterCountryQueryData> {
public AbstractExporterCountry_XLSX(final Exporter<XSSFWorkbook, ExporterCountryQueryData> exporter) {
super(exporter);
}
public AbstractExporterCountry_XLSX(final ExporterService exporterService) {
super(exporterService);
}
protected XSSFWorkbook export(final XSSFWorkbook workbook, final ExporterCountryQueryData queryData, final Map<String, ReportRow> data, final String sheetName) {
// TODO i18n, UT
// Create the sheet
final String safeName = WorkbookUtil.createSafeSheetName(sheetName);
final XSSFSheet sheet = workbook.createSheet(safeName);
// Define the headers
final ArrayList<Object> headers = new ArrayList<Object>();
headers.add("Indicator ID");
headers.add("Indicator name");
- headers.add("Source code");
+ headers.add("Source dataset");
headers.add("Units");
headers.add("Dataset summary");
// Retrieve years from the data, as specifying 0 for fromYear/toYear in the queryData allows for earliest/latest data available.
int fromYear = Integer.MAX_VALUE;
int toYear = Integer.MIN_VALUE;
for (final String indicatorCode : data.keySet()) {
final ReportRow reportRow = data.get(indicatorCode);
if (fromYear > reportRow.getMinYear()) {
fromYear = reportRow.getMinYear();
}
if (toYear < reportRow.getMaxYear()) {
toYear = reportRow.getMaxYear();
}
}
- for (int year = fromYear; year <= toYear; year++) {
+ for (int year = toYear; year >= fromYear; year--) {
headers.add(year);
}
// Assign the headers to the title row
createHeaderCells(sheet, headers);
// TODO Set the indicators info (cells A2:Dx), maybe create a custom query for this.
// Fill with the data
// We start right just after the headers row
int rowIndex = 1;
for (final String indicatorCode : data.keySet()) {
final ReportRow reportRow = data.get(indicatorCode);
final XSSFRow row = sheet.createRow(rowIndex);
rowIndex++;
createCell(row, (short) 0, reportRow.getIndicatorCode());
createCell(row, (short) 1, reportRow.getIndicatorName());
createCell(row, (short) 2, reportRow.getSourceCode());
createCell(row, (short) 3, reportRow.getUnit());
createDatasetSummaryCell(reportRow, (short) 4, row);
- for (int year = fromYear; year <= toYear; year++) {
- final short columnIndex = (short) ((5 + year) - fromYear);
+ for (int year = toYear; year >= fromYear; year--) {
+ final short columnIndex = (short) ((5 + toYear) - year);
final Double value = reportRow.getDoubleValue(year);
if (null != value) {
createNumCell(row, columnIndex, value);
} else {
createCell(row, columnIndex, " ");
}
}
}
// Freeze the headers
// Freeze the 2 first columns
sheet.createFreezePane(2, 1, 2, 1);
// Auto size the columns
// Except Indicator ID and Dataset summary which is fixed
for (int i = 0; i < (headers.size() + data.keySet().size()); i++) {
if (0 == i) {
sheet.setColumnWidth(i, 3000);
} else if (4 == i) {
sheet.setColumnWidth(i, 20000);
} else {
sheet.autoSizeColumn(i);
}
}
return super.export(workbook, queryData);
}
private static void createDatasetSummaryCell(final ReportRow reportRow, final short position, final XSSFRow row) {
final String datasetSummary = reportRow.getDatasetSummary();
/*
if ((null != datasetSummary) && (50 < datasetSummary.length())) {
final XSSFCell cell = createCell(row, position, datasetSummary.substring(0, 50) + " ...");
final XSSFCreationHelper creationHelper = row.getSheet().getWorkbook().getCreationHelper();
final Drawing drawing = row.getSheet().createDrawingPatriarch();
// When the comment box is visible, have it show in a 1x3 space
final ClientAnchor anchor = creationHelper.createClientAnchor();
anchor.setCol1(cell.getColumnIndex());
anchor.setCol2(cell.getColumnIndex() + 1);
anchor.setRow1(row.getRowNum());
anchor.setRow2(row.getRowNum() + 3);
// Create the comment and set the text+author
final Comment comment = drawing.createCellComment(anchor);
final RichTextString str = creationHelper.createRichTextString(datasetSummary);
comment.setString(str);
// Assign the comment to the cell
cell.setCellComment(comment);
} else {
*/
createCell(row, position, datasetSummary);
/*
}
*/
}
}
| false | true | protected XSSFWorkbook export(final XSSFWorkbook workbook, final ExporterCountryQueryData queryData, final Map<String, ReportRow> data, final String sheetName) {
// TODO i18n, UT
// Create the sheet
final String safeName = WorkbookUtil.createSafeSheetName(sheetName);
final XSSFSheet sheet = workbook.createSheet(safeName);
// Define the headers
final ArrayList<Object> headers = new ArrayList<Object>();
headers.add("Indicator ID");
headers.add("Indicator name");
headers.add("Source code");
headers.add("Units");
headers.add("Dataset summary");
// Retrieve years from the data, as specifying 0 for fromYear/toYear in the queryData allows for earliest/latest data available.
int fromYear = Integer.MAX_VALUE;
int toYear = Integer.MIN_VALUE;
for (final String indicatorCode : data.keySet()) {
final ReportRow reportRow = data.get(indicatorCode);
if (fromYear > reportRow.getMinYear()) {
fromYear = reportRow.getMinYear();
}
if (toYear < reportRow.getMaxYear()) {
toYear = reportRow.getMaxYear();
}
}
for (int year = fromYear; year <= toYear; year++) {
headers.add(year);
}
// Assign the headers to the title row
createHeaderCells(sheet, headers);
// TODO Set the indicators info (cells A2:Dx), maybe create a custom query for this.
// Fill with the data
// We start right just after the headers row
int rowIndex = 1;
for (final String indicatorCode : data.keySet()) {
final ReportRow reportRow = data.get(indicatorCode);
final XSSFRow row = sheet.createRow(rowIndex);
rowIndex++;
createCell(row, (short) 0, reportRow.getIndicatorCode());
createCell(row, (short) 1, reportRow.getIndicatorName());
createCell(row, (short) 2, reportRow.getSourceCode());
createCell(row, (short) 3, reportRow.getUnit());
createDatasetSummaryCell(reportRow, (short) 4, row);
for (int year = fromYear; year <= toYear; year++) {
final short columnIndex = (short) ((5 + year) - fromYear);
final Double value = reportRow.getDoubleValue(year);
if (null != value) {
createNumCell(row, columnIndex, value);
} else {
createCell(row, columnIndex, " ");
}
}
}
// Freeze the headers
// Freeze the 2 first columns
sheet.createFreezePane(2, 1, 2, 1);
// Auto size the columns
// Except Indicator ID and Dataset summary which is fixed
for (int i = 0; i < (headers.size() + data.keySet().size()); i++) {
if (0 == i) {
sheet.setColumnWidth(i, 3000);
} else if (4 == i) {
sheet.setColumnWidth(i, 20000);
} else {
sheet.autoSizeColumn(i);
}
}
return super.export(workbook, queryData);
}
| protected XSSFWorkbook export(final XSSFWorkbook workbook, final ExporterCountryQueryData queryData, final Map<String, ReportRow> data, final String sheetName) {
// TODO i18n, UT
// Create the sheet
final String safeName = WorkbookUtil.createSafeSheetName(sheetName);
final XSSFSheet sheet = workbook.createSheet(safeName);
// Define the headers
final ArrayList<Object> headers = new ArrayList<Object>();
headers.add("Indicator ID");
headers.add("Indicator name");
headers.add("Source dataset");
headers.add("Units");
headers.add("Dataset summary");
// Retrieve years from the data, as specifying 0 for fromYear/toYear in the queryData allows for earliest/latest data available.
int fromYear = Integer.MAX_VALUE;
int toYear = Integer.MIN_VALUE;
for (final String indicatorCode : data.keySet()) {
final ReportRow reportRow = data.get(indicatorCode);
if (fromYear > reportRow.getMinYear()) {
fromYear = reportRow.getMinYear();
}
if (toYear < reportRow.getMaxYear()) {
toYear = reportRow.getMaxYear();
}
}
for (int year = toYear; year >= fromYear; year--) {
headers.add(year);
}
// Assign the headers to the title row
createHeaderCells(sheet, headers);
// TODO Set the indicators info (cells A2:Dx), maybe create a custom query for this.
// Fill with the data
// We start right just after the headers row
int rowIndex = 1;
for (final String indicatorCode : data.keySet()) {
final ReportRow reportRow = data.get(indicatorCode);
final XSSFRow row = sheet.createRow(rowIndex);
rowIndex++;
createCell(row, (short) 0, reportRow.getIndicatorCode());
createCell(row, (short) 1, reportRow.getIndicatorName());
createCell(row, (short) 2, reportRow.getSourceCode());
createCell(row, (short) 3, reportRow.getUnit());
createDatasetSummaryCell(reportRow, (short) 4, row);
for (int year = toYear; year >= fromYear; year--) {
final short columnIndex = (short) ((5 + toYear) - year);
final Double value = reportRow.getDoubleValue(year);
if (null != value) {
createNumCell(row, columnIndex, value);
} else {
createCell(row, columnIndex, " ");
}
}
}
// Freeze the headers
// Freeze the 2 first columns
sheet.createFreezePane(2, 1, 2, 1);
// Auto size the columns
// Except Indicator ID and Dataset summary which is fixed
for (int i = 0; i < (headers.size() + data.keySet().size()); i++) {
if (0 == i) {
sheet.setColumnWidth(i, 3000);
} else if (4 == i) {
sheet.setColumnWidth(i, 20000);
} else {
sheet.autoSizeColumn(i);
}
}
return super.export(workbook, queryData);
}
|
diff --git a/src/main/java/ar/edu/utn/tacs/group5/controller/AddTorrentController.java b/src/main/java/ar/edu/utn/tacs/group5/controller/AddTorrentController.java
index fbaa0fe..d6aeb7d 100644
--- a/src/main/java/ar/edu/utn/tacs/group5/controller/AddTorrentController.java
+++ b/src/main/java/ar/edu/utn/tacs/group5/controller/AddTorrentController.java
@@ -1,28 +1,28 @@
package ar.edu.utn.tacs.group5.controller;
import java.util.logging.Logger;
import org.slim3.controller.Controller;
import org.slim3.controller.Navigation;
import ar.edu.utn.tacs.group5.controller.Constants;
import ar.edu.utn.tacs.group5.service.FeedService;
public class AddTorrentController extends Controller {
private Logger logger = Logger.getLogger(this.getClass().getName());
private FeedService feedService = new FeedService();
@Override
public Navigation run() throws Exception {
- String userId = sessionScope(Constants.USER_ID);
+ Long userId = sessionScope(Constants.USER_ID);
String link = param(Constants.LINK);
logger.info(link);
- feedService.addTorrent(Long.valueOf(userId), link);
+ feedService.addTorrent(userId, link);
if(Boolean.valueOf(param(Constants.FROM_FB))){
return redirect("index.jsp");
}
return null;
}
}
| false | true | public Navigation run() throws Exception {
String userId = sessionScope(Constants.USER_ID);
String link = param(Constants.LINK);
logger.info(link);
feedService.addTorrent(Long.valueOf(userId), link);
if(Boolean.valueOf(param(Constants.FROM_FB))){
return redirect("index.jsp");
}
return null;
}
| public Navigation run() throws Exception {
Long userId = sessionScope(Constants.USER_ID);
String link = param(Constants.LINK);
logger.info(link);
feedService.addTorrent(userId, link);
if(Boolean.valueOf(param(Constants.FROM_FB))){
return redirect("index.jsp");
}
return null;
}
|
diff --git a/achartengine/src/org/achartengine/chart/XYChart.java b/achartengine/src/org/achartengine/chart/XYChart.java
index 62d35be..6ee23e2 100644
--- a/achartengine/src/org/achartengine/chart/XYChart.java
+++ b/achartengine/src/org/achartengine/chart/XYChart.java
@@ -1,959 +1,959 @@
/**
* Copyright (C) 2009 - 2012 SC 4ViewSoft SRL
*
* 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.achartengine.chart;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedMap;
import org.achartengine.model.Point;
import org.achartengine.model.SeriesSelection;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.renderer.BasicStroke;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYMultipleSeriesRenderer.Orientation;
import org.achartengine.util.MathHelper;
import android.graphics.Canvas;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.graphics.Paint.Cap;
import android.graphics.Paint.Join;
import android.graphics.Paint.Style;
import android.graphics.PathEffect;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
/**
* The XY chart rendering class.
*/
public abstract class XYChart extends AbstractChart {
/** The multiple series dataset. */
protected XYMultipleSeriesDataset mDataset;
/** The multiple series renderer. */
protected XYMultipleSeriesRenderer mRenderer;
/** The current scale value. */
private float mScale;
/** The current translate value. */
private float mTranslate;
/** The canvas center point. */
private Point mCenter;
/** The visible chart area, in screen coordinates. */
private Rect mScreenR;
/** The calculated range. */
private final Map<Integer, double[]> mCalcRange = new HashMap<Integer, double[]>();
/**
* The clickable areas for all points. The array index is the series index,
* and the RectF list index is the point index in that series.
*/
private Map<Integer, List<ClickableArea>> clickableAreas = new HashMap<Integer, List<ClickableArea>>();
protected XYChart() {
}
/**
* Builds a new XY chart instance.
*
* @param dataset the multiple series dataset
* @param renderer the multiple series renderer
*/
public XYChart(XYMultipleSeriesDataset dataset, XYMultipleSeriesRenderer renderer) {
mDataset = dataset;
mRenderer = renderer;
}
// TODO: javadoc
protected void setDatasetRenderer(XYMultipleSeriesDataset dataset,
XYMultipleSeriesRenderer renderer) {
mDataset = dataset;
mRenderer = renderer;
}
/**
* The graphical representation of the XY chart.
*
* @param canvas the canvas to paint to
* @param x the top left x value of the view to draw to
* @param y the top left y value of the view to draw to
* @param width the width of the view to draw to
* @param height the height of the view to draw to
* @param paint the paint
*/
public void draw(Canvas canvas, int x, int y, int width, int height, Paint paint) {
paint.setAntiAlias(mRenderer.isAntialiasing());
int legendSize = getLegendSize(mRenderer, height / 5, mRenderer.getAxisTitleTextSize());
int[] margins = mRenderer.getMargins();
int left = x + margins[1];
int top = y + margins[0];
int right = x + width - margins[3];
int sLength = mDataset.getSeriesCount();
String[] titles = new String[sLength];
for (int i = 0; i < sLength; i++) {
titles[i] = mDataset.getSeriesAt(i).getTitle();
}
if (mRenderer.isFitLegend() && mRenderer.isShowLegend()) {
legendSize = drawLegend(canvas, mRenderer, titles, left, right, y, width, height, legendSize,
paint, true);
}
int bottom = y + height - margins[2] - legendSize;
if (mScreenR == null) {
mScreenR = new Rect();
}
mScreenR.set(left, top, right, bottom);
drawBackground(mRenderer, canvas, x, y, width, height, paint, false, DefaultRenderer.NO_COLOR);
if (paint.getTypeface() == null
|| (mRenderer.getTextTypeface() != null && paint.getTypeface().equals(
mRenderer.getTextTypeface()))
|| !paint.getTypeface().toString().equals(mRenderer.getTextTypefaceName())
|| paint.getTypeface().getStyle() != mRenderer.getTextTypefaceStyle()) {
if (mRenderer.getTextTypeface() != null) {
paint.setTypeface(mRenderer.getTextTypeface());
} else {
paint.setTypeface(Typeface.create(mRenderer.getTextTypefaceName(),
mRenderer.getTextTypefaceStyle()));
}
}
Orientation or = mRenderer.getOrientation();
if (or == Orientation.VERTICAL) {
right -= legendSize;
bottom += legendSize - 20;
}
int angle = or.getAngle();
boolean rotate = angle == 90;
mScale = (float) (height) / width;
mTranslate = Math.abs(width - height) / 2;
if (mScale < 1) {
mTranslate *= -1;
}
mCenter = new Point((x + width) / 2, (y + height) / 2);
if (rotate) {
transform(canvas, angle, false);
}
int maxScaleNumber = -Integer.MAX_VALUE;
for (int i = 0; i < sLength; i++) {
maxScaleNumber = Math.max(maxScaleNumber, mDataset.getSeriesAt(i).getScaleNumber());
}
maxScaleNumber++;
if (maxScaleNumber < 0) {
return;
}
double[] minX = new double[maxScaleNumber];
double[] maxX = new double[maxScaleNumber];
double[] minY = new double[maxScaleNumber];
double[] maxY = new double[maxScaleNumber];
boolean[] isMinXSet = new boolean[maxScaleNumber];
boolean[] isMaxXSet = new boolean[maxScaleNumber];
boolean[] isMinYSet = new boolean[maxScaleNumber];
boolean[] isMaxYSet = new boolean[maxScaleNumber];
for (int i = 0; i < maxScaleNumber; i++) {
minX[i] = mRenderer.getXAxisMin(i);
maxX[i] = mRenderer.getXAxisMax(i);
minY[i] = mRenderer.getYAxisMin(i);
maxY[i] = mRenderer.getYAxisMax(i);
isMinXSet[i] = mRenderer.isMinXSet(i);
isMaxXSet[i] = mRenderer.isMaxXSet(i);
isMinYSet[i] = mRenderer.isMinYSet(i);
isMaxYSet[i] = mRenderer.isMaxYSet(i);
if (mCalcRange.get(i) == null) {
mCalcRange.put(i, new double[4]);
}
}
double[] xPixelsPerUnit = new double[maxScaleNumber];
double[] yPixelsPerUnit = new double[maxScaleNumber];
for (int i = 0; i < sLength; i++) {
XYSeries series = mDataset.getSeriesAt(i);
int scale = series.getScaleNumber();
if (series.getItemCount() == 0) {
continue;
}
if (!isMinXSet[scale]) {
double minimumX = series.getMinX();
minX[scale] = Math.min(minX[scale], minimumX);
mCalcRange.get(scale)[0] = minX[scale];
}
if (!isMaxXSet[scale]) {
double maximumX = series.getMaxX();
maxX[scale] = Math.max(maxX[scale], maximumX);
mCalcRange.get(scale)[1] = maxX[scale];
}
if (!isMinYSet[scale]) {
double minimumY = series.getMinY();
minY[scale] = Math.min(minY[scale], (float) minimumY);
mCalcRange.get(scale)[2] = minY[scale];
}
if (!isMaxYSet[scale]) {
double maximumY = series.getMaxY();
maxY[scale] = Math.max(maxY[scale], (float) maximumY);
mCalcRange.get(scale)[3] = maxY[scale];
}
}
for (int i = 0; i < maxScaleNumber; i++) {
if (maxX[i] - minX[i] != 0) {
xPixelsPerUnit[i] = (right - left) / (maxX[i] - minX[i]);
}
if (maxY[i] - minY[i] != 0) {
yPixelsPerUnit[i] = (float) ((bottom - top) / (maxY[i] - minY[i]));
}
}
boolean hasValues = false;
// use a linked list for these reasons:
// 1) Avoid a large contiguous memory allocation
// 2) We don't need random seeking, only sequential reading/writing, so
// linked list makes sense
clickableAreas = new HashMap<Integer, List<ClickableArea>>();
for (int i = 0; i < sLength; i++) {
XYSeries series = mDataset.getSeriesAt(i);
int scale = series.getScaleNumber();
if (series.getItemCount() == 0) {
continue;
}
hasValues = true;
SimpleSeriesRenderer seriesRenderer = mRenderer.getSeriesRendererAt(i);
// int originalValuesLength = series.getItemCount();
// int valuesLength = originalValuesLength;
// int length = valuesLength * 2;
List<Float> points = new ArrayList<Float>();
List<Double> values = new ArrayList<Double>();
float yAxisValue = Math.min(bottom, (float) (bottom + yPixelsPerUnit[scale] * minY[scale]));
LinkedList<ClickableArea> clickableArea = new LinkedList<ClickableArea>();
clickableAreas.put(i, clickableArea);
synchronized (series) {
SortedMap<Double, Double> range = series.getRange(minX[scale], maxX[scale],
seriesRenderer.isDisplayBoundingPoints());
int startIndex = -1;
for (Entry<Double, Double> value : range.entrySet()) {
double xValue = value.getKey();
double yValue = value.getValue();
if (startIndex < 0 && (!isNullValue(yValue) || isRenderNullValues())) {
startIndex = series.getIndexForKey(xValue);
}
// points.add((float) (left + xPixelsPerUnit[scale]
// * (value.getKey().floatValue() - minX[scale])));
// points.add((float) (bottom - yPixelsPerUnit[scale]
// * (value.getValue().floatValue() - minY[scale])));
values.add(value.getKey());
values.add(value.getValue());
if (!isNullValue(yValue)) {
points.add((float) (left + xPixelsPerUnit[scale] * (xValue - minX[scale])));
points.add((float) (bottom - yPixelsPerUnit[scale] * (yValue - minY[scale])));
} else if (isRenderNullValues()) {
points.add((float) (left + xPixelsPerUnit[scale] * (xValue - minX[scale])));
points.add((float) (bottom - yPixelsPerUnit[scale] * (-minY[scale])));
} else {
if (points.size() > 0) {
drawSeries(series, canvas, paint, points, seriesRenderer, yAxisValue, i, or,
startIndex);
ClickableArea[] clickableAreasForSubSeries = clickableAreasForPoints(points, values,
yAxisValue, i, startIndex);
clickableArea.addAll(Arrays.asList(clickableAreasForSubSeries));
points.clear();
values.clear();
startIndex = -1;
}
clickableArea.add(null);
}
}
int count = series.getAnnotationCount();
if (count > 0) {
paint.setColor(mRenderer.getLabelsColor());
Rect bound = new Rect();
for (int j = 0; j < count; j++) {
- float xS = (float) (left + xPixelsPerUnit[scale] * series.getAnnotationX(j) - minX[scale]);
+ float xS = (float) (left + xPixelsPerUnit[scale] * (series.getAnnotationX(j) - minX[scale]));
float yS = (float) (bottom - yPixelsPerUnit[scale]
* (series.getAnnotationY(j) - minY[scale]));
paint.getTextBounds(series.getAnnotationAt(j), 0, series.getAnnotationAt(j).length(),
bound);
if (xS < (xS + bound.width()) && yS < canvas.getHeight()) {
drawString(canvas, series.getAnnotationAt(j), xS, yS, paint);
}
}
}
if (points.size() > 0) {
drawSeries(series, canvas, paint, points, seriesRenderer, yAxisValue, i, or, startIndex);
ClickableArea[] clickableAreasForSubSeries = clickableAreasForPoints(points, values,
yAxisValue, i, startIndex);
clickableArea.addAll(Arrays.asList(clickableAreasForSubSeries));
}
}
}
// draw stuff over the margins such as data doesn't render on these areas
drawBackground(mRenderer, canvas, x, bottom, width, height - bottom, paint, true,
mRenderer.getMarginsColor());
drawBackground(mRenderer, canvas, x, y, width, margins[0], paint, true,
mRenderer.getMarginsColor());
if (or == Orientation.HORIZONTAL) {
drawBackground(mRenderer, canvas, x, y, left - x, height - y, paint, true,
mRenderer.getMarginsColor());
drawBackground(mRenderer, canvas, right, y, margins[3], height - y, paint, true,
mRenderer.getMarginsColor());
} else if (or == Orientation.VERTICAL) {
drawBackground(mRenderer, canvas, right, y, width - right, height - y, paint, true,
mRenderer.getMarginsColor());
drawBackground(mRenderer, canvas, x, y, left - x, height - y, paint, true,
mRenderer.getMarginsColor());
}
boolean showLabels = mRenderer.isShowLabels() && hasValues;
boolean showGridX = mRenderer.isShowGridX();
boolean showCustomTextGrid = mRenderer.isShowCustomTextGrid();
if (showLabels || showGridX) {
List<Double> xLabels = getValidLabels(getXLabels(minX[0], maxX[0], mRenderer.getXLabels()));
Map<Integer, List<Double>> allYLabels = getYLabels(minY, maxY, maxScaleNumber);
int xLabelsLeft = left;
if (showLabels) {
paint.setColor(mRenderer.getXLabelsColor());
paint.setTextSize(mRenderer.getLabelsTextSize());
paint.setTextAlign(mRenderer.getXLabelsAlign());
if (mRenderer.getXLabelsAlign() == Align.LEFT) {
xLabelsLeft += mRenderer.getLabelsTextSize() / 4;
}
}
drawXLabels(xLabels, mRenderer.getXTextLabelLocations(), canvas, paint, xLabelsLeft, top,
bottom, xPixelsPerUnit[0], minX[0], maxX[0]);
drawYLabels(allYLabels, canvas, paint, maxScaleNumber, left, right, bottom, yPixelsPerUnit,
minY);
if (showLabels) {
paint.setColor(mRenderer.getLabelsColor());
for (int i = 0; i < maxScaleNumber; i++) {
Align axisAlign = mRenderer.getYAxisAlign(i);
Double[] yTextLabelLocations = mRenderer.getYTextLabelLocations(i);
for (Double location : yTextLabelLocations) {
if (minY[i] <= location && location <= maxY[i]) {
float yLabel = (float) (bottom - yPixelsPerUnit[i]
* (location.doubleValue() - minY[i]));
String label = mRenderer.getYTextLabel(location, i);
paint.setColor(mRenderer.getYLabelsColor(i));
paint.setTextAlign(mRenderer.getYLabelsAlign(i));
if (or == Orientation.HORIZONTAL) {
if (axisAlign == Align.LEFT) {
canvas.drawLine(left + getLabelLinePos(axisAlign), yLabel, left, yLabel, paint);
drawText(canvas, label, left, yLabel - 2, paint, mRenderer.getYLabelsAngle());
} else {
canvas.drawLine(right, yLabel, right + getLabelLinePos(axisAlign), yLabel, paint);
drawText(canvas, label, right, yLabel - 2, paint, mRenderer.getYLabelsAngle());
}
if (showCustomTextGrid) {
paint.setColor(mRenderer.getGridColor());
canvas.drawLine(left, yLabel, right, yLabel, paint);
}
} else {
canvas.drawLine(right - getLabelLinePos(axisAlign), yLabel, right, yLabel, paint);
drawText(canvas, label, right + 10, yLabel - 2, paint, mRenderer.getYLabelsAngle());
if (showCustomTextGrid) {
paint.setColor(mRenderer.getGridColor());
canvas.drawLine(right, yLabel, left, yLabel, paint);
}
}
}
}
}
}
if (showLabels) {
paint.setColor(mRenderer.getLabelsColor());
float size = mRenderer.getAxisTitleTextSize();
paint.setTextSize(size);
paint.setTextAlign(Align.CENTER);
if (or == Orientation.HORIZONTAL) {
drawText(
canvas,
mRenderer.getXTitle(),
x + width / 2,
bottom + mRenderer.getLabelsTextSize() * 4 / 3 + mRenderer.getXLabelsPadding() + size,
paint, 0);
for (int i = 0; i < maxScaleNumber; i++) {
Align axisAlign = mRenderer.getYAxisAlign(i);
if (axisAlign == Align.LEFT) {
drawText(canvas, mRenderer.getYTitle(i), x + size, y + height / 2, paint, -90);
} else {
drawText(canvas, mRenderer.getYTitle(i), x + width, y + height / 2, paint, -90);
}
}
paint.setTextSize(mRenderer.getChartTitleTextSize());
drawText(canvas, mRenderer.getChartTitle(), x + width / 2,
y + mRenderer.getChartTitleTextSize(), paint, 0);
} else if (or == Orientation.VERTICAL) {
drawText(canvas, mRenderer.getXTitle(), x + width / 2,
y + height - size + mRenderer.getXLabelsPadding(), paint, -90);
drawText(canvas, mRenderer.getYTitle(), right + 20, y + height / 2, paint, 0);
paint.setTextSize(mRenderer.getChartTitleTextSize());
drawText(canvas, mRenderer.getChartTitle(), x + size, top + height / 2, paint, 0);
}
}
}
if (or == Orientation.HORIZONTAL) {
drawLegend(canvas, mRenderer, titles, left, right, y + (int) mRenderer.getXLabelsPadding(),
width, height, legendSize, paint, false);
} else if (or == Orientation.VERTICAL) {
transform(canvas, angle, true);
drawLegend(canvas, mRenderer, titles, left, right, y + (int) mRenderer.getXLabelsPadding(),
width, height, legendSize, paint, false);
transform(canvas, angle, false);
}
if (mRenderer.isShowAxes()) {
paint.setColor(mRenderer.getAxesColor());
canvas.drawLine(left, bottom, right, bottom, paint);
boolean rightAxis = false;
for (int i = 0; i < maxScaleNumber && !rightAxis; i++) {
rightAxis = mRenderer.getYAxisAlign(i) == Align.RIGHT;
}
if (or == Orientation.HORIZONTAL) {
canvas.drawLine(left, top, left, bottom, paint);
if (rightAxis) {
canvas.drawLine(right, top, right, bottom, paint);
}
} else if (or == Orientation.VERTICAL) {
canvas.drawLine(right, top, right, bottom, paint);
}
}
if (rotate) {
transform(canvas, angle, true);
}
}
protected List<Double> getXLabels(double min, double max, int count) {
return MathHelper.getLabels(min, max, count);
}
protected Map<Integer, List<Double>> getYLabels(double[] minY, double[] maxY, int maxScaleNumber) {
Map<Integer, List<Double>> allYLabels = new HashMap<Integer, List<Double>>();
for (int i = 0; i < maxScaleNumber; i++) {
allYLabels.put(i,
getValidLabels(MathHelper.getLabels(minY[i], maxY[i], mRenderer.getYLabels())));
}
return allYLabels;
}
protected Rect getScreenR() {
return mScreenR;
}
protected void setScreenR(Rect screenR) {
mScreenR = screenR;
}
private List<Double> getValidLabels(List<Double> labels) {
List<Double> result = new ArrayList<Double>(labels);
for (Double label : labels) {
if (label.isNaN()) {
result.remove(label);
}
}
return result;
}
/**
* Draws the series.
*
* @param series the series
* @param canvas the canvas
* @param paint the paint object
* @param pointsList the points to be rendered
* @param seriesRenderer the series renderer
* @param yAxisValue the y axis value in pixels
* @param seriesIndex the series index
* @param or the orientation
* @param startIndex the start index of the rendering points
*/
protected void drawSeries(XYSeries series, Canvas canvas, Paint paint, List<Float> pointsList,
SimpleSeriesRenderer seriesRenderer, float yAxisValue, int seriesIndex, Orientation or,
int startIndex) {
BasicStroke stroke = seriesRenderer.getStroke();
Cap cap = paint.getStrokeCap();
Join join = paint.getStrokeJoin();
float miter = paint.getStrokeMiter();
PathEffect pathEffect = paint.getPathEffect();
Style style = paint.getStyle();
if (stroke != null) {
PathEffect effect = null;
if (stroke.getIntervals() != null) {
effect = new DashPathEffect(stroke.getIntervals(), stroke.getPhase());
}
setStroke(stroke.getCap(), stroke.getJoin(), stroke.getMiter(), Style.FILL_AND_STROKE,
effect, paint);
}
// float[] points = MathHelper.getFloats(pointsList);
drawSeries(canvas, paint, pointsList, seriesRenderer, yAxisValue, seriesIndex, startIndex);
if (isRenderPoints(seriesRenderer)) {
ScatterChart pointsChart = getPointsChart();
if (pointsChart != null) {
pointsChart.drawSeries(canvas, paint, pointsList, seriesRenderer, yAxisValue, seriesIndex,
startIndex);
}
}
paint.setTextSize(seriesRenderer.getChartValuesTextSize());
if (or == Orientation.HORIZONTAL) {
paint.setTextAlign(Align.CENTER);
} else {
paint.setTextAlign(Align.LEFT);
}
if (seriesRenderer.isDisplayChartValues()) {
paint.setTextAlign(seriesRenderer.getChartValuesTextAlign());
drawChartValuesText(canvas, series, seriesRenderer, paint, pointsList, seriesIndex,
startIndex);
}
if (stroke != null) {
setStroke(cap, join, miter, style, pathEffect, paint);
}
}
private void setStroke(Cap cap, Join join, float miter, Style style, PathEffect pathEffect,
Paint paint) {
paint.setStrokeCap(cap);
paint.setStrokeJoin(join);
paint.setStrokeMiter(miter);
paint.setPathEffect(pathEffect);
paint.setStyle(style);
}
/**
* The graphical representation of the series values as text.
*
* @param canvas the canvas to paint to
* @param series the series to be painted
* @param renderer the series renderer
* @param paint the paint to be used for drawing
* @param points the array of points to be used for drawing the series
* @param seriesIndex the index of the series currently being drawn
* @param startIndex the start index of the rendering points
*/
protected void drawChartValuesText(Canvas canvas, XYSeries series, SimpleSeriesRenderer renderer,
Paint paint, List<Float> points, int seriesIndex, int startIndex) {
if (points.size() > 1) { // there are more than one point
// record the first point's position
float previousPointX = points.get(0);
float previousPointY = points.get(1);
for (int k = 0; k < points.size(); k += 2) {
if (k == 2) { // decide whether to display first two points' values or
// not
if (Math.abs(points.get(2) - points.get(0)) > renderer.getDisplayChartValuesDistance()
|| Math.abs(points.get(3) - points.get(1)) > renderer.getDisplayChartValuesDistance()) {
// first point
drawText(canvas, getLabel(renderer.getChartValuesFormat(), series.getY(startIndex)),
points.get(0), points.get(1) - renderer.getChartValuesSpacing(), paint, 0);
// second point
drawText(canvas,
getLabel(renderer.getChartValuesFormat(), series.getY(startIndex + 1)),
points.get(2), points.get(3) - renderer.getChartValuesSpacing(), paint, 0);
previousPointX = points.get(2);
previousPointY = points.get(3);
}
} else if (k > 2) {
// compare current point's position with the previous point's, if they
// are not too close, display
if (Math.abs(points.get(k) - previousPointX) > renderer.getDisplayChartValuesDistance()
|| Math.abs(points.get(k + 1) - previousPointY) > renderer
.getDisplayChartValuesDistance()) {
drawText(canvas,
getLabel(renderer.getChartValuesFormat(), series.getY(startIndex + k / 2)),
points.get(k), points.get(k + 1) - renderer.getChartValuesSpacing(), paint, 0);
previousPointX = points.get(k);
previousPointY = points.get(k + 1);
}
}
}
} else { // if only one point, display it
for (int k = 0; k < points.size(); k += 2) {
drawText(canvas,
getLabel(renderer.getChartValuesFormat(), series.getY(startIndex + k / 2)),
points.get(k), points.get(k + 1) - renderer.getChartValuesSpacing(), paint, 0);
}
}
}
/**
* The graphical representation of a text, to handle both HORIZONTAL and
* VERTICAL orientations and extra rotation angles.
*
* @param canvas the canvas to paint to
* @param text the text to be rendered
* @param x the X axis location of the text
* @param y the Y axis location of the text
* @param paint the paint to be used for drawing
* @param extraAngle the text angle
*/
protected void drawText(Canvas canvas, String text, float x, float y, Paint paint,
float extraAngle) {
float angle = -mRenderer.getOrientation().getAngle() + extraAngle;
if (angle != 0) {
// canvas.scale(1 / mScale, mScale);
canvas.rotate(angle, x, y);
}
drawString(canvas, text, x, y, paint);
if (angle != 0) {
canvas.rotate(-angle, x, y);
// canvas.scale(mScale, 1 / mScale);
}
}
/**
* Transform the canvas such as it can handle both HORIZONTAL and VERTICAL
* orientations.
*
* @param canvas the canvas to paint to
* @param angle the angle of rotation
* @param inverse if the inverse transform needs to be applied
*/
private void transform(Canvas canvas, float angle, boolean inverse) {
if (inverse) {
canvas.scale(1 / mScale, mScale);
canvas.translate(mTranslate, -mTranslate);
canvas.rotate(-angle, mCenter.getX(), mCenter.getY());
} else {
canvas.rotate(angle, mCenter.getX(), mCenter.getY());
canvas.translate(-mTranslate, mTranslate);
canvas.scale(mScale, 1 / mScale);
}
}
/**
* The graphical representation of the labels on the X axis.
*
* @param xLabels the X labels values
* @param xTextLabelLocations the X text label locations
* @param canvas the canvas to paint to
* @param paint the paint to be used for drawing
* @param left the left value of the labels area
* @param top the top value of the labels area
* @param bottom the bottom value of the labels area
* @param xPixelsPerUnit the amount of pixels per one unit in the chart labels
* @param minX the minimum value on the X axis in the chart
* @param maxX the maximum value on the X axis in the chart
*/
protected void drawXLabels(List<Double> xLabels, Double[] xTextLabelLocations, Canvas canvas,
Paint paint, int left, int top, int bottom, double xPixelsPerUnit, double minX, double maxX) {
int length = xLabels.size();
boolean showLabels = mRenderer.isShowLabels();
boolean showGridY = mRenderer.isShowGridY();
for (int i = 0; i < length; i++) {
double label = xLabels.get(i);
float xLabel = (float) (left + xPixelsPerUnit * (label - minX));
if (showLabels) {
paint.setColor(mRenderer.getXLabelsColor());
canvas.drawLine(xLabel, bottom, xLabel, bottom + mRenderer.getLabelsTextSize() / 3, paint);
drawText(canvas, getLabel(mRenderer.getLabelFormat(), label), xLabel,
bottom + mRenderer.getLabelsTextSize() * 4 / 3 + mRenderer.getXLabelsPadding(), paint,
mRenderer.getXLabelsAngle());
}
if (showGridY) {
paint.setColor(mRenderer.getGridColor());
canvas.drawLine(xLabel, bottom, xLabel, top, paint);
}
}
drawXTextLabels(xTextLabelLocations, canvas, paint, showLabels, left, top, bottom,
xPixelsPerUnit, minX, maxX);
}
/**
* The graphical representation of the labels on the Y axis.
*
* @param allYLabels the Y labels values
* @param canvas the canvas to paint to
* @param paint the paint to be used for drawing
* @param maxScaleNumber the maximum scale number
* @param left the left value of the labels area
* @param right the right value of the labels area
* @param bottom the bottom value of the labels area
* @param yPixelsPerUnit the amount of pixels per one unit in the chart labels
* @param minY the minimum value on the Y axis in the chart
*/
protected void drawYLabels(Map<Integer, List<Double>> allYLabels, Canvas canvas, Paint paint,
int maxScaleNumber, int left, int right, int bottom, double[] yPixelsPerUnit, double[] minY) {
Orientation or = mRenderer.getOrientation();
boolean showGridX = mRenderer.isShowGridX();
boolean showLabels = mRenderer.isShowLabels();
for (int i = 0; i < maxScaleNumber; i++) {
paint.setTextAlign(mRenderer.getYLabelsAlign(i));
List<Double> yLabels = allYLabels.get(i);
int length = yLabels.size();
for (int j = 0; j < length; j++) {
double label = yLabels.get(j);
Align axisAlign = mRenderer.getYAxisAlign(i);
boolean textLabel = mRenderer.getYTextLabel(label, i) != null;
float yLabel = (float) (bottom - yPixelsPerUnit[i] * (label - minY[i]));
if (or == Orientation.HORIZONTAL) {
if (showLabels && !textLabel) {
paint.setColor(mRenderer.getYLabelsColor(i));
if (axisAlign == Align.LEFT) {
canvas.drawLine(left + getLabelLinePos(axisAlign), yLabel, left, yLabel, paint);
drawText(canvas, getLabel(mRenderer.getLabelFormat(), label),
left - mRenderer.getYLabelsPadding(),
yLabel - mRenderer.getYLabelsVerticalPadding(), paint,
mRenderer.getYLabelsAngle());
} else {
canvas.drawLine(right, yLabel, right + getLabelLinePos(axisAlign), yLabel, paint);
drawText(canvas, getLabel(mRenderer.getLabelFormat(), label),
right + mRenderer.getYLabelsPadding(),
yLabel - mRenderer.getYLabelsVerticalPadding(), paint,
mRenderer.getYLabelsAngle());
}
}
if (showGridX) {
paint.setColor(mRenderer.getGridColor());
canvas.drawLine(left, yLabel, right, yLabel, paint);
}
} else if (or == Orientation.VERTICAL) {
if (showLabels && !textLabel) {
paint.setColor(mRenderer.getYLabelsColor(i));
canvas.drawLine(right - getLabelLinePos(axisAlign), yLabel, right, yLabel, paint);
drawText(canvas, getLabel(mRenderer.getLabelFormat(), label),
right + 10 + mRenderer.getYLabelsPadding(), yLabel - 2, paint,
mRenderer.getYLabelsAngle());
}
if (showGridX) {
paint.setColor(mRenderer.getGridColor());
canvas.drawLine(right, yLabel, left, yLabel, paint);
}
}
}
}
}
/**
* The graphical representation of the text labels on the X axis.
*
* @param xTextLabelLocations the X text label locations
* @param canvas the canvas to paint to
* @param paint the paint to be used for drawing
* @param left the left value of the labels area
* @param top the top value of the labels area
* @param bottom the bottom value of the labels area
* @param xPixelsPerUnit the amount of pixels per one unit in the chart labels
* @param minX the minimum value on the X axis in the chart
* @param maxX the maximum value on the X axis in the chart
*/
protected void drawXTextLabels(Double[] xTextLabelLocations, Canvas canvas, Paint paint,
boolean showLabels, int left, int top, int bottom, double xPixelsPerUnit, double minX,
double maxX) {
boolean showCustomTextGrid = mRenderer.isShowCustomTextGrid();
if (showLabels) {
paint.setColor(mRenderer.getXLabelsColor());
for (Double location : xTextLabelLocations) {
if (minX <= location && location <= maxX) {
float xLabel = (float) (left + xPixelsPerUnit * (location.doubleValue() - minX));
paint.setColor(mRenderer.getXLabelsColor());
canvas
.drawLine(xLabel, bottom, xLabel, bottom + mRenderer.getLabelsTextSize() / 3, paint);
drawText(canvas, mRenderer.getXTextLabel(location), xLabel,
bottom + mRenderer.getLabelsTextSize() * 4 / 3, paint, mRenderer.getXLabelsAngle());
if (showCustomTextGrid) {
paint.setColor(mRenderer.getGridColor());
canvas.drawLine(xLabel, bottom, xLabel, top, paint);
}
}
}
}
}
// TODO: docs
public XYMultipleSeriesRenderer getRenderer() {
return mRenderer;
}
public XYMultipleSeriesDataset getDataset() {
return mDataset;
}
public double[] getCalcRange(int scale) {
return mCalcRange.get(scale);
}
public void setCalcRange(double[] range, int scale) {
mCalcRange.put(scale, range);
}
public double[] toRealPoint(float screenX, float screenY) {
return toRealPoint(screenX, screenY, 0);
}
public double[] toScreenPoint(double[] realPoint) {
return toScreenPoint(realPoint, 0);
}
private int getLabelLinePos(Align align) {
int pos = 4;
if (align == Align.LEFT) {
pos = -pos;
}
return pos;
}
/**
* Transforms a screen point to a real coordinates point.
*
* @param screenX the screen x axis value
* @param screenY the screen y axis value
* @return the real coordinates point
*/
public double[] toRealPoint(float screenX, float screenY, int scale) {
double realMinX = mRenderer.getXAxisMin(scale);
double realMaxX = mRenderer.getXAxisMax(scale);
double realMinY = mRenderer.getYAxisMin(scale);
double realMaxY = mRenderer.getYAxisMax(scale);
if (mScreenR != null) {
return new double[] {
(screenX - mScreenR.left) * (realMaxX - realMinX) / mScreenR.width() + realMinX,
(mScreenR.top + mScreenR.height() - screenY) * (realMaxY - realMinY) / mScreenR.height()
+ realMinY };
} else {
return new double[] { screenX, screenY };
}
}
public double[] toScreenPoint(double[] realPoint, int scale) {
double realMinX = mRenderer.getXAxisMin(scale);
double realMaxX = mRenderer.getXAxisMax(scale);
double realMinY = mRenderer.getYAxisMin(scale);
double realMaxY = mRenderer.getYAxisMax(scale);
if (!mRenderer.isMinXSet(scale) || !mRenderer.isMaxXSet(scale) || !mRenderer.isMinXSet(scale)
|| !mRenderer.isMaxYSet(scale)) {
double[] calcRange = getCalcRange(scale);
realMinX = calcRange[0];
realMaxX = calcRange[1];
realMinY = calcRange[2];
realMaxY = calcRange[3];
}
if (mScreenR != null) {
return new double[] {
(realPoint[0] - realMinX) * mScreenR.width() / (realMaxX - realMinX) + mScreenR.left,
(realMaxY - realPoint[1]) * mScreenR.height() / (realMaxY - realMinY) + mScreenR.top };
} else {
return realPoint;
}
}
public SeriesSelection getSeriesAndPointForScreenCoordinate(final Point screenPoint) {
if (clickableAreas != null)
for (int seriesIndex = clickableAreas.size() - 1; seriesIndex >= 0; seriesIndex--) {
// series 0 is drawn first. Then series 1 is drawn on top, and series 2
// on top of that.
// we want to know what the user clicked on, so traverse them in the
// order they appear on the screen.
int pointIndex = 0;
if (clickableAreas.get(seriesIndex) != null) {
RectF rectangle;
for (ClickableArea area : clickableAreas.get(seriesIndex)) {
rectangle = area.getRect();
if (rectangle != null && rectangle.contains(screenPoint.getX(), screenPoint.getY())) {
return new SeriesSelection(seriesIndex, pointIndex, area.getX(), area.getY());
}
pointIndex++;
}
}
}
return super.getSeriesAndPointForScreenCoordinate(screenPoint);
}
/**
* The graphical representation of a series.
*
* @param canvas the canvas to paint to
* @param paint the paint to be used for drawing
* @param points the array of points to be used for drawing the series
* @param seriesRenderer the series renderer
* @param yAxisValue the minimum value of the y axis
* @param seriesIndex the index of the series currently being drawn
* @param startIndex the start index of the rendering points
*/
public abstract void drawSeries(Canvas canvas, Paint paint, List<Float> points,
SimpleSeriesRenderer seriesRenderer, float yAxisValue, int seriesIndex, int startIndex);
/**
* Returns the clickable areas for all passed points
*
* @param points the array of points
* @param values the array of values of each point
* @param yAxisValue the minimum value of the y axis
* @param seriesIndex the index of the series to which the points belong
* @return an array of rectangles with the clickable area
* @param startIndex the start index of the rendering points
*/
protected abstract ClickableArea[] clickableAreasForPoints(List<Float> points,
List<Double> values, float yAxisValue, int seriesIndex, int startIndex);
/**
* Returns if the chart should display the null values.
*
* @return if null values should be rendered
*/
protected boolean isRenderNullValues() {
return false;
}
/**
* Returns if the chart should display the points as a certain shape.
*
* @param renderer the series renderer
*/
public boolean isRenderPoints(SimpleSeriesRenderer renderer) {
return false;
}
/**
* Returns the default axis minimum.
*
* @return the default axis minimum
*/
public double getDefaultMinimum() {
return MathHelper.NULL_VALUE;
}
/**
* Returns the scatter chart to be used for drawing the data points.
*
* @return the data points scatter chart
*/
public ScatterChart getPointsChart() {
return null;
}
/**
* Returns the chart type identifier.
*
* @return the chart type
*/
public abstract String getChartType();
}
| true | true | public void draw(Canvas canvas, int x, int y, int width, int height, Paint paint) {
paint.setAntiAlias(mRenderer.isAntialiasing());
int legendSize = getLegendSize(mRenderer, height / 5, mRenderer.getAxisTitleTextSize());
int[] margins = mRenderer.getMargins();
int left = x + margins[1];
int top = y + margins[0];
int right = x + width - margins[3];
int sLength = mDataset.getSeriesCount();
String[] titles = new String[sLength];
for (int i = 0; i < sLength; i++) {
titles[i] = mDataset.getSeriesAt(i).getTitle();
}
if (mRenderer.isFitLegend() && mRenderer.isShowLegend()) {
legendSize = drawLegend(canvas, mRenderer, titles, left, right, y, width, height, legendSize,
paint, true);
}
int bottom = y + height - margins[2] - legendSize;
if (mScreenR == null) {
mScreenR = new Rect();
}
mScreenR.set(left, top, right, bottom);
drawBackground(mRenderer, canvas, x, y, width, height, paint, false, DefaultRenderer.NO_COLOR);
if (paint.getTypeface() == null
|| (mRenderer.getTextTypeface() != null && paint.getTypeface().equals(
mRenderer.getTextTypeface()))
|| !paint.getTypeface().toString().equals(mRenderer.getTextTypefaceName())
|| paint.getTypeface().getStyle() != mRenderer.getTextTypefaceStyle()) {
if (mRenderer.getTextTypeface() != null) {
paint.setTypeface(mRenderer.getTextTypeface());
} else {
paint.setTypeface(Typeface.create(mRenderer.getTextTypefaceName(),
mRenderer.getTextTypefaceStyle()));
}
}
Orientation or = mRenderer.getOrientation();
if (or == Orientation.VERTICAL) {
right -= legendSize;
bottom += legendSize - 20;
}
int angle = or.getAngle();
boolean rotate = angle == 90;
mScale = (float) (height) / width;
mTranslate = Math.abs(width - height) / 2;
if (mScale < 1) {
mTranslate *= -1;
}
mCenter = new Point((x + width) / 2, (y + height) / 2);
if (rotate) {
transform(canvas, angle, false);
}
int maxScaleNumber = -Integer.MAX_VALUE;
for (int i = 0; i < sLength; i++) {
maxScaleNumber = Math.max(maxScaleNumber, mDataset.getSeriesAt(i).getScaleNumber());
}
maxScaleNumber++;
if (maxScaleNumber < 0) {
return;
}
double[] minX = new double[maxScaleNumber];
double[] maxX = new double[maxScaleNumber];
double[] minY = new double[maxScaleNumber];
double[] maxY = new double[maxScaleNumber];
boolean[] isMinXSet = new boolean[maxScaleNumber];
boolean[] isMaxXSet = new boolean[maxScaleNumber];
boolean[] isMinYSet = new boolean[maxScaleNumber];
boolean[] isMaxYSet = new boolean[maxScaleNumber];
for (int i = 0; i < maxScaleNumber; i++) {
minX[i] = mRenderer.getXAxisMin(i);
maxX[i] = mRenderer.getXAxisMax(i);
minY[i] = mRenderer.getYAxisMin(i);
maxY[i] = mRenderer.getYAxisMax(i);
isMinXSet[i] = mRenderer.isMinXSet(i);
isMaxXSet[i] = mRenderer.isMaxXSet(i);
isMinYSet[i] = mRenderer.isMinYSet(i);
isMaxYSet[i] = mRenderer.isMaxYSet(i);
if (mCalcRange.get(i) == null) {
mCalcRange.put(i, new double[4]);
}
}
double[] xPixelsPerUnit = new double[maxScaleNumber];
double[] yPixelsPerUnit = new double[maxScaleNumber];
for (int i = 0; i < sLength; i++) {
XYSeries series = mDataset.getSeriesAt(i);
int scale = series.getScaleNumber();
if (series.getItemCount() == 0) {
continue;
}
if (!isMinXSet[scale]) {
double minimumX = series.getMinX();
minX[scale] = Math.min(minX[scale], minimumX);
mCalcRange.get(scale)[0] = minX[scale];
}
if (!isMaxXSet[scale]) {
double maximumX = series.getMaxX();
maxX[scale] = Math.max(maxX[scale], maximumX);
mCalcRange.get(scale)[1] = maxX[scale];
}
if (!isMinYSet[scale]) {
double minimumY = series.getMinY();
minY[scale] = Math.min(minY[scale], (float) minimumY);
mCalcRange.get(scale)[2] = minY[scale];
}
if (!isMaxYSet[scale]) {
double maximumY = series.getMaxY();
maxY[scale] = Math.max(maxY[scale], (float) maximumY);
mCalcRange.get(scale)[3] = maxY[scale];
}
}
for (int i = 0; i < maxScaleNumber; i++) {
if (maxX[i] - minX[i] != 0) {
xPixelsPerUnit[i] = (right - left) / (maxX[i] - minX[i]);
}
if (maxY[i] - minY[i] != 0) {
yPixelsPerUnit[i] = (float) ((bottom - top) / (maxY[i] - minY[i]));
}
}
boolean hasValues = false;
// use a linked list for these reasons:
// 1) Avoid a large contiguous memory allocation
// 2) We don't need random seeking, only sequential reading/writing, so
// linked list makes sense
clickableAreas = new HashMap<Integer, List<ClickableArea>>();
for (int i = 0; i < sLength; i++) {
XYSeries series = mDataset.getSeriesAt(i);
int scale = series.getScaleNumber();
if (series.getItemCount() == 0) {
continue;
}
hasValues = true;
SimpleSeriesRenderer seriesRenderer = mRenderer.getSeriesRendererAt(i);
// int originalValuesLength = series.getItemCount();
// int valuesLength = originalValuesLength;
// int length = valuesLength * 2;
List<Float> points = new ArrayList<Float>();
List<Double> values = new ArrayList<Double>();
float yAxisValue = Math.min(bottom, (float) (bottom + yPixelsPerUnit[scale] * minY[scale]));
LinkedList<ClickableArea> clickableArea = new LinkedList<ClickableArea>();
clickableAreas.put(i, clickableArea);
synchronized (series) {
SortedMap<Double, Double> range = series.getRange(minX[scale], maxX[scale],
seriesRenderer.isDisplayBoundingPoints());
int startIndex = -1;
for (Entry<Double, Double> value : range.entrySet()) {
double xValue = value.getKey();
double yValue = value.getValue();
if (startIndex < 0 && (!isNullValue(yValue) || isRenderNullValues())) {
startIndex = series.getIndexForKey(xValue);
}
// points.add((float) (left + xPixelsPerUnit[scale]
// * (value.getKey().floatValue() - minX[scale])));
// points.add((float) (bottom - yPixelsPerUnit[scale]
// * (value.getValue().floatValue() - minY[scale])));
values.add(value.getKey());
values.add(value.getValue());
if (!isNullValue(yValue)) {
points.add((float) (left + xPixelsPerUnit[scale] * (xValue - minX[scale])));
points.add((float) (bottom - yPixelsPerUnit[scale] * (yValue - minY[scale])));
} else if (isRenderNullValues()) {
points.add((float) (left + xPixelsPerUnit[scale] * (xValue - minX[scale])));
points.add((float) (bottom - yPixelsPerUnit[scale] * (-minY[scale])));
} else {
if (points.size() > 0) {
drawSeries(series, canvas, paint, points, seriesRenderer, yAxisValue, i, or,
startIndex);
ClickableArea[] clickableAreasForSubSeries = clickableAreasForPoints(points, values,
yAxisValue, i, startIndex);
clickableArea.addAll(Arrays.asList(clickableAreasForSubSeries));
points.clear();
values.clear();
startIndex = -1;
}
clickableArea.add(null);
}
}
int count = series.getAnnotationCount();
if (count > 0) {
paint.setColor(mRenderer.getLabelsColor());
Rect bound = new Rect();
for (int j = 0; j < count; j++) {
float xS = (float) (left + xPixelsPerUnit[scale] * series.getAnnotationX(j) - minX[scale]);
float yS = (float) (bottom - yPixelsPerUnit[scale]
* (series.getAnnotationY(j) - minY[scale]));
paint.getTextBounds(series.getAnnotationAt(j), 0, series.getAnnotationAt(j).length(),
bound);
if (xS < (xS + bound.width()) && yS < canvas.getHeight()) {
drawString(canvas, series.getAnnotationAt(j), xS, yS, paint);
}
}
}
if (points.size() > 0) {
drawSeries(series, canvas, paint, points, seriesRenderer, yAxisValue, i, or, startIndex);
ClickableArea[] clickableAreasForSubSeries = clickableAreasForPoints(points, values,
yAxisValue, i, startIndex);
clickableArea.addAll(Arrays.asList(clickableAreasForSubSeries));
}
}
}
// draw stuff over the margins such as data doesn't render on these areas
drawBackground(mRenderer, canvas, x, bottom, width, height - bottom, paint, true,
mRenderer.getMarginsColor());
drawBackground(mRenderer, canvas, x, y, width, margins[0], paint, true,
mRenderer.getMarginsColor());
if (or == Orientation.HORIZONTAL) {
drawBackground(mRenderer, canvas, x, y, left - x, height - y, paint, true,
mRenderer.getMarginsColor());
drawBackground(mRenderer, canvas, right, y, margins[3], height - y, paint, true,
mRenderer.getMarginsColor());
} else if (or == Orientation.VERTICAL) {
drawBackground(mRenderer, canvas, right, y, width - right, height - y, paint, true,
mRenderer.getMarginsColor());
drawBackground(mRenderer, canvas, x, y, left - x, height - y, paint, true,
mRenderer.getMarginsColor());
}
boolean showLabels = mRenderer.isShowLabels() && hasValues;
boolean showGridX = mRenderer.isShowGridX();
boolean showCustomTextGrid = mRenderer.isShowCustomTextGrid();
if (showLabels || showGridX) {
List<Double> xLabels = getValidLabels(getXLabels(minX[0], maxX[0], mRenderer.getXLabels()));
Map<Integer, List<Double>> allYLabels = getYLabels(minY, maxY, maxScaleNumber);
int xLabelsLeft = left;
if (showLabels) {
paint.setColor(mRenderer.getXLabelsColor());
paint.setTextSize(mRenderer.getLabelsTextSize());
paint.setTextAlign(mRenderer.getXLabelsAlign());
if (mRenderer.getXLabelsAlign() == Align.LEFT) {
xLabelsLeft += mRenderer.getLabelsTextSize() / 4;
}
}
drawXLabels(xLabels, mRenderer.getXTextLabelLocations(), canvas, paint, xLabelsLeft, top,
bottom, xPixelsPerUnit[0], minX[0], maxX[0]);
drawYLabels(allYLabels, canvas, paint, maxScaleNumber, left, right, bottom, yPixelsPerUnit,
minY);
if (showLabels) {
paint.setColor(mRenderer.getLabelsColor());
for (int i = 0; i < maxScaleNumber; i++) {
Align axisAlign = mRenderer.getYAxisAlign(i);
Double[] yTextLabelLocations = mRenderer.getYTextLabelLocations(i);
for (Double location : yTextLabelLocations) {
if (minY[i] <= location && location <= maxY[i]) {
float yLabel = (float) (bottom - yPixelsPerUnit[i]
* (location.doubleValue() - minY[i]));
String label = mRenderer.getYTextLabel(location, i);
paint.setColor(mRenderer.getYLabelsColor(i));
paint.setTextAlign(mRenderer.getYLabelsAlign(i));
if (or == Orientation.HORIZONTAL) {
if (axisAlign == Align.LEFT) {
canvas.drawLine(left + getLabelLinePos(axisAlign), yLabel, left, yLabel, paint);
drawText(canvas, label, left, yLabel - 2, paint, mRenderer.getYLabelsAngle());
} else {
canvas.drawLine(right, yLabel, right + getLabelLinePos(axisAlign), yLabel, paint);
drawText(canvas, label, right, yLabel - 2, paint, mRenderer.getYLabelsAngle());
}
if (showCustomTextGrid) {
paint.setColor(mRenderer.getGridColor());
canvas.drawLine(left, yLabel, right, yLabel, paint);
}
} else {
canvas.drawLine(right - getLabelLinePos(axisAlign), yLabel, right, yLabel, paint);
drawText(canvas, label, right + 10, yLabel - 2, paint, mRenderer.getYLabelsAngle());
if (showCustomTextGrid) {
paint.setColor(mRenderer.getGridColor());
canvas.drawLine(right, yLabel, left, yLabel, paint);
}
}
}
}
}
}
if (showLabels) {
paint.setColor(mRenderer.getLabelsColor());
float size = mRenderer.getAxisTitleTextSize();
paint.setTextSize(size);
paint.setTextAlign(Align.CENTER);
if (or == Orientation.HORIZONTAL) {
drawText(
canvas,
mRenderer.getXTitle(),
x + width / 2,
bottom + mRenderer.getLabelsTextSize() * 4 / 3 + mRenderer.getXLabelsPadding() + size,
paint, 0);
for (int i = 0; i < maxScaleNumber; i++) {
Align axisAlign = mRenderer.getYAxisAlign(i);
if (axisAlign == Align.LEFT) {
drawText(canvas, mRenderer.getYTitle(i), x + size, y + height / 2, paint, -90);
} else {
drawText(canvas, mRenderer.getYTitle(i), x + width, y + height / 2, paint, -90);
}
}
paint.setTextSize(mRenderer.getChartTitleTextSize());
drawText(canvas, mRenderer.getChartTitle(), x + width / 2,
y + mRenderer.getChartTitleTextSize(), paint, 0);
} else if (or == Orientation.VERTICAL) {
drawText(canvas, mRenderer.getXTitle(), x + width / 2,
y + height - size + mRenderer.getXLabelsPadding(), paint, -90);
drawText(canvas, mRenderer.getYTitle(), right + 20, y + height / 2, paint, 0);
paint.setTextSize(mRenderer.getChartTitleTextSize());
drawText(canvas, mRenderer.getChartTitle(), x + size, top + height / 2, paint, 0);
}
}
}
if (or == Orientation.HORIZONTAL) {
drawLegend(canvas, mRenderer, titles, left, right, y + (int) mRenderer.getXLabelsPadding(),
width, height, legendSize, paint, false);
} else if (or == Orientation.VERTICAL) {
transform(canvas, angle, true);
drawLegend(canvas, mRenderer, titles, left, right, y + (int) mRenderer.getXLabelsPadding(),
width, height, legendSize, paint, false);
transform(canvas, angle, false);
}
if (mRenderer.isShowAxes()) {
paint.setColor(mRenderer.getAxesColor());
canvas.drawLine(left, bottom, right, bottom, paint);
boolean rightAxis = false;
for (int i = 0; i < maxScaleNumber && !rightAxis; i++) {
rightAxis = mRenderer.getYAxisAlign(i) == Align.RIGHT;
}
if (or == Orientation.HORIZONTAL) {
canvas.drawLine(left, top, left, bottom, paint);
if (rightAxis) {
canvas.drawLine(right, top, right, bottom, paint);
}
} else if (or == Orientation.VERTICAL) {
canvas.drawLine(right, top, right, bottom, paint);
}
}
if (rotate) {
transform(canvas, angle, true);
}
}
| public void draw(Canvas canvas, int x, int y, int width, int height, Paint paint) {
paint.setAntiAlias(mRenderer.isAntialiasing());
int legendSize = getLegendSize(mRenderer, height / 5, mRenderer.getAxisTitleTextSize());
int[] margins = mRenderer.getMargins();
int left = x + margins[1];
int top = y + margins[0];
int right = x + width - margins[3];
int sLength = mDataset.getSeriesCount();
String[] titles = new String[sLength];
for (int i = 0; i < sLength; i++) {
titles[i] = mDataset.getSeriesAt(i).getTitle();
}
if (mRenderer.isFitLegend() && mRenderer.isShowLegend()) {
legendSize = drawLegend(canvas, mRenderer, titles, left, right, y, width, height, legendSize,
paint, true);
}
int bottom = y + height - margins[2] - legendSize;
if (mScreenR == null) {
mScreenR = new Rect();
}
mScreenR.set(left, top, right, bottom);
drawBackground(mRenderer, canvas, x, y, width, height, paint, false, DefaultRenderer.NO_COLOR);
if (paint.getTypeface() == null
|| (mRenderer.getTextTypeface() != null && paint.getTypeface().equals(
mRenderer.getTextTypeface()))
|| !paint.getTypeface().toString().equals(mRenderer.getTextTypefaceName())
|| paint.getTypeface().getStyle() != mRenderer.getTextTypefaceStyle()) {
if (mRenderer.getTextTypeface() != null) {
paint.setTypeface(mRenderer.getTextTypeface());
} else {
paint.setTypeface(Typeface.create(mRenderer.getTextTypefaceName(),
mRenderer.getTextTypefaceStyle()));
}
}
Orientation or = mRenderer.getOrientation();
if (or == Orientation.VERTICAL) {
right -= legendSize;
bottom += legendSize - 20;
}
int angle = or.getAngle();
boolean rotate = angle == 90;
mScale = (float) (height) / width;
mTranslate = Math.abs(width - height) / 2;
if (mScale < 1) {
mTranslate *= -1;
}
mCenter = new Point((x + width) / 2, (y + height) / 2);
if (rotate) {
transform(canvas, angle, false);
}
int maxScaleNumber = -Integer.MAX_VALUE;
for (int i = 0; i < sLength; i++) {
maxScaleNumber = Math.max(maxScaleNumber, mDataset.getSeriesAt(i).getScaleNumber());
}
maxScaleNumber++;
if (maxScaleNumber < 0) {
return;
}
double[] minX = new double[maxScaleNumber];
double[] maxX = new double[maxScaleNumber];
double[] minY = new double[maxScaleNumber];
double[] maxY = new double[maxScaleNumber];
boolean[] isMinXSet = new boolean[maxScaleNumber];
boolean[] isMaxXSet = new boolean[maxScaleNumber];
boolean[] isMinYSet = new boolean[maxScaleNumber];
boolean[] isMaxYSet = new boolean[maxScaleNumber];
for (int i = 0; i < maxScaleNumber; i++) {
minX[i] = mRenderer.getXAxisMin(i);
maxX[i] = mRenderer.getXAxisMax(i);
minY[i] = mRenderer.getYAxisMin(i);
maxY[i] = mRenderer.getYAxisMax(i);
isMinXSet[i] = mRenderer.isMinXSet(i);
isMaxXSet[i] = mRenderer.isMaxXSet(i);
isMinYSet[i] = mRenderer.isMinYSet(i);
isMaxYSet[i] = mRenderer.isMaxYSet(i);
if (mCalcRange.get(i) == null) {
mCalcRange.put(i, new double[4]);
}
}
double[] xPixelsPerUnit = new double[maxScaleNumber];
double[] yPixelsPerUnit = new double[maxScaleNumber];
for (int i = 0; i < sLength; i++) {
XYSeries series = mDataset.getSeriesAt(i);
int scale = series.getScaleNumber();
if (series.getItemCount() == 0) {
continue;
}
if (!isMinXSet[scale]) {
double minimumX = series.getMinX();
minX[scale] = Math.min(minX[scale], minimumX);
mCalcRange.get(scale)[0] = minX[scale];
}
if (!isMaxXSet[scale]) {
double maximumX = series.getMaxX();
maxX[scale] = Math.max(maxX[scale], maximumX);
mCalcRange.get(scale)[1] = maxX[scale];
}
if (!isMinYSet[scale]) {
double minimumY = series.getMinY();
minY[scale] = Math.min(minY[scale], (float) minimumY);
mCalcRange.get(scale)[2] = minY[scale];
}
if (!isMaxYSet[scale]) {
double maximumY = series.getMaxY();
maxY[scale] = Math.max(maxY[scale], (float) maximumY);
mCalcRange.get(scale)[3] = maxY[scale];
}
}
for (int i = 0; i < maxScaleNumber; i++) {
if (maxX[i] - minX[i] != 0) {
xPixelsPerUnit[i] = (right - left) / (maxX[i] - minX[i]);
}
if (maxY[i] - minY[i] != 0) {
yPixelsPerUnit[i] = (float) ((bottom - top) / (maxY[i] - minY[i]));
}
}
boolean hasValues = false;
// use a linked list for these reasons:
// 1) Avoid a large contiguous memory allocation
// 2) We don't need random seeking, only sequential reading/writing, so
// linked list makes sense
clickableAreas = new HashMap<Integer, List<ClickableArea>>();
for (int i = 0; i < sLength; i++) {
XYSeries series = mDataset.getSeriesAt(i);
int scale = series.getScaleNumber();
if (series.getItemCount() == 0) {
continue;
}
hasValues = true;
SimpleSeriesRenderer seriesRenderer = mRenderer.getSeriesRendererAt(i);
// int originalValuesLength = series.getItemCount();
// int valuesLength = originalValuesLength;
// int length = valuesLength * 2;
List<Float> points = new ArrayList<Float>();
List<Double> values = new ArrayList<Double>();
float yAxisValue = Math.min(bottom, (float) (bottom + yPixelsPerUnit[scale] * minY[scale]));
LinkedList<ClickableArea> clickableArea = new LinkedList<ClickableArea>();
clickableAreas.put(i, clickableArea);
synchronized (series) {
SortedMap<Double, Double> range = series.getRange(minX[scale], maxX[scale],
seriesRenderer.isDisplayBoundingPoints());
int startIndex = -1;
for (Entry<Double, Double> value : range.entrySet()) {
double xValue = value.getKey();
double yValue = value.getValue();
if (startIndex < 0 && (!isNullValue(yValue) || isRenderNullValues())) {
startIndex = series.getIndexForKey(xValue);
}
// points.add((float) (left + xPixelsPerUnit[scale]
// * (value.getKey().floatValue() - minX[scale])));
// points.add((float) (bottom - yPixelsPerUnit[scale]
// * (value.getValue().floatValue() - minY[scale])));
values.add(value.getKey());
values.add(value.getValue());
if (!isNullValue(yValue)) {
points.add((float) (left + xPixelsPerUnit[scale] * (xValue - minX[scale])));
points.add((float) (bottom - yPixelsPerUnit[scale] * (yValue - minY[scale])));
} else if (isRenderNullValues()) {
points.add((float) (left + xPixelsPerUnit[scale] * (xValue - minX[scale])));
points.add((float) (bottom - yPixelsPerUnit[scale] * (-minY[scale])));
} else {
if (points.size() > 0) {
drawSeries(series, canvas, paint, points, seriesRenderer, yAxisValue, i, or,
startIndex);
ClickableArea[] clickableAreasForSubSeries = clickableAreasForPoints(points, values,
yAxisValue, i, startIndex);
clickableArea.addAll(Arrays.asList(clickableAreasForSubSeries));
points.clear();
values.clear();
startIndex = -1;
}
clickableArea.add(null);
}
}
int count = series.getAnnotationCount();
if (count > 0) {
paint.setColor(mRenderer.getLabelsColor());
Rect bound = new Rect();
for (int j = 0; j < count; j++) {
float xS = (float) (left + xPixelsPerUnit[scale] * (series.getAnnotationX(j) - minX[scale]));
float yS = (float) (bottom - yPixelsPerUnit[scale]
* (series.getAnnotationY(j) - minY[scale]));
paint.getTextBounds(series.getAnnotationAt(j), 0, series.getAnnotationAt(j).length(),
bound);
if (xS < (xS + bound.width()) && yS < canvas.getHeight()) {
drawString(canvas, series.getAnnotationAt(j), xS, yS, paint);
}
}
}
if (points.size() > 0) {
drawSeries(series, canvas, paint, points, seriesRenderer, yAxisValue, i, or, startIndex);
ClickableArea[] clickableAreasForSubSeries = clickableAreasForPoints(points, values,
yAxisValue, i, startIndex);
clickableArea.addAll(Arrays.asList(clickableAreasForSubSeries));
}
}
}
// draw stuff over the margins such as data doesn't render on these areas
drawBackground(mRenderer, canvas, x, bottom, width, height - bottom, paint, true,
mRenderer.getMarginsColor());
drawBackground(mRenderer, canvas, x, y, width, margins[0], paint, true,
mRenderer.getMarginsColor());
if (or == Orientation.HORIZONTAL) {
drawBackground(mRenderer, canvas, x, y, left - x, height - y, paint, true,
mRenderer.getMarginsColor());
drawBackground(mRenderer, canvas, right, y, margins[3], height - y, paint, true,
mRenderer.getMarginsColor());
} else if (or == Orientation.VERTICAL) {
drawBackground(mRenderer, canvas, right, y, width - right, height - y, paint, true,
mRenderer.getMarginsColor());
drawBackground(mRenderer, canvas, x, y, left - x, height - y, paint, true,
mRenderer.getMarginsColor());
}
boolean showLabels = mRenderer.isShowLabels() && hasValues;
boolean showGridX = mRenderer.isShowGridX();
boolean showCustomTextGrid = mRenderer.isShowCustomTextGrid();
if (showLabels || showGridX) {
List<Double> xLabels = getValidLabels(getXLabels(minX[0], maxX[0], mRenderer.getXLabels()));
Map<Integer, List<Double>> allYLabels = getYLabels(minY, maxY, maxScaleNumber);
int xLabelsLeft = left;
if (showLabels) {
paint.setColor(mRenderer.getXLabelsColor());
paint.setTextSize(mRenderer.getLabelsTextSize());
paint.setTextAlign(mRenderer.getXLabelsAlign());
if (mRenderer.getXLabelsAlign() == Align.LEFT) {
xLabelsLeft += mRenderer.getLabelsTextSize() / 4;
}
}
drawXLabels(xLabels, mRenderer.getXTextLabelLocations(), canvas, paint, xLabelsLeft, top,
bottom, xPixelsPerUnit[0], minX[0], maxX[0]);
drawYLabels(allYLabels, canvas, paint, maxScaleNumber, left, right, bottom, yPixelsPerUnit,
minY);
if (showLabels) {
paint.setColor(mRenderer.getLabelsColor());
for (int i = 0; i < maxScaleNumber; i++) {
Align axisAlign = mRenderer.getYAxisAlign(i);
Double[] yTextLabelLocations = mRenderer.getYTextLabelLocations(i);
for (Double location : yTextLabelLocations) {
if (minY[i] <= location && location <= maxY[i]) {
float yLabel = (float) (bottom - yPixelsPerUnit[i]
* (location.doubleValue() - minY[i]));
String label = mRenderer.getYTextLabel(location, i);
paint.setColor(mRenderer.getYLabelsColor(i));
paint.setTextAlign(mRenderer.getYLabelsAlign(i));
if (or == Orientation.HORIZONTAL) {
if (axisAlign == Align.LEFT) {
canvas.drawLine(left + getLabelLinePos(axisAlign), yLabel, left, yLabel, paint);
drawText(canvas, label, left, yLabel - 2, paint, mRenderer.getYLabelsAngle());
} else {
canvas.drawLine(right, yLabel, right + getLabelLinePos(axisAlign), yLabel, paint);
drawText(canvas, label, right, yLabel - 2, paint, mRenderer.getYLabelsAngle());
}
if (showCustomTextGrid) {
paint.setColor(mRenderer.getGridColor());
canvas.drawLine(left, yLabel, right, yLabel, paint);
}
} else {
canvas.drawLine(right - getLabelLinePos(axisAlign), yLabel, right, yLabel, paint);
drawText(canvas, label, right + 10, yLabel - 2, paint, mRenderer.getYLabelsAngle());
if (showCustomTextGrid) {
paint.setColor(mRenderer.getGridColor());
canvas.drawLine(right, yLabel, left, yLabel, paint);
}
}
}
}
}
}
if (showLabels) {
paint.setColor(mRenderer.getLabelsColor());
float size = mRenderer.getAxisTitleTextSize();
paint.setTextSize(size);
paint.setTextAlign(Align.CENTER);
if (or == Orientation.HORIZONTAL) {
drawText(
canvas,
mRenderer.getXTitle(),
x + width / 2,
bottom + mRenderer.getLabelsTextSize() * 4 / 3 + mRenderer.getXLabelsPadding() + size,
paint, 0);
for (int i = 0; i < maxScaleNumber; i++) {
Align axisAlign = mRenderer.getYAxisAlign(i);
if (axisAlign == Align.LEFT) {
drawText(canvas, mRenderer.getYTitle(i), x + size, y + height / 2, paint, -90);
} else {
drawText(canvas, mRenderer.getYTitle(i), x + width, y + height / 2, paint, -90);
}
}
paint.setTextSize(mRenderer.getChartTitleTextSize());
drawText(canvas, mRenderer.getChartTitle(), x + width / 2,
y + mRenderer.getChartTitleTextSize(), paint, 0);
} else if (or == Orientation.VERTICAL) {
drawText(canvas, mRenderer.getXTitle(), x + width / 2,
y + height - size + mRenderer.getXLabelsPadding(), paint, -90);
drawText(canvas, mRenderer.getYTitle(), right + 20, y + height / 2, paint, 0);
paint.setTextSize(mRenderer.getChartTitleTextSize());
drawText(canvas, mRenderer.getChartTitle(), x + size, top + height / 2, paint, 0);
}
}
}
if (or == Orientation.HORIZONTAL) {
drawLegend(canvas, mRenderer, titles, left, right, y + (int) mRenderer.getXLabelsPadding(),
width, height, legendSize, paint, false);
} else if (or == Orientation.VERTICAL) {
transform(canvas, angle, true);
drawLegend(canvas, mRenderer, titles, left, right, y + (int) mRenderer.getXLabelsPadding(),
width, height, legendSize, paint, false);
transform(canvas, angle, false);
}
if (mRenderer.isShowAxes()) {
paint.setColor(mRenderer.getAxesColor());
canvas.drawLine(left, bottom, right, bottom, paint);
boolean rightAxis = false;
for (int i = 0; i < maxScaleNumber && !rightAxis; i++) {
rightAxis = mRenderer.getYAxisAlign(i) == Align.RIGHT;
}
if (or == Orientation.HORIZONTAL) {
canvas.drawLine(left, top, left, bottom, paint);
if (rightAxis) {
canvas.drawLine(right, top, right, bottom, paint);
}
} else if (or == Orientation.VERTICAL) {
canvas.drawLine(right, top, right, bottom, paint);
}
}
if (rotate) {
transform(canvas, angle, true);
}
}
|
diff --git a/src/net/appositedesigns/fileexplorer/FileListAdapter.java b/src/net/appositedesigns/fileexplorer/FileListAdapter.java
index 31f7117..fa609b0 100644
--- a/src/net/appositedesigns/fileexplorer/FileListAdapter.java
+++ b/src/net/appositedesigns/fileexplorer/FileListAdapter.java
@@ -1,112 +1,118 @@
package net.appositedesigns.fileexplorer;
import java.io.File;
import java.util.List;
import net.apposite.fileexplorer.R;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class FileListAdapter extends BaseAdapter {
public static class ViewHolder
{
public TextView resName;
public ImageView resIcon;
public ImageView resActions;
public TextView resMeta;
}
private Context mContext;
private List<File> files;
private LayoutInflater mInflater;
public FileListAdapter(Context context, List<File> files) {
super();
mContext = context;
this.files = files;
mInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
if(files == null)
{
return 0;
}
else
{
return files.size();
}
}
@Override
public Object getItem(int arg0) {
if(files == null)
return null;
else
return files.get(arg0);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.explorer_item, parent, false);
holder = new ViewHolder();
holder.resName = (TextView)convertView.findViewById(R.id.explorer_resName);
holder.resMeta = (TextView)convertView.findViewById(R.id.explorer_resMeta);
holder.resIcon = (ImageView)convertView.findViewById(R.id.explorer_resIcon);
holder.resActions = (ImageView)convertView.findViewById(R.id.explorer_resActions);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
File currentFile = files.get(position);
holder.resName.setText(currentFile.getName());
holder.resIcon.setImageDrawable(FileExplorerUtils.getIcon(mContext, currentFile));
holder.resMeta.setText(FileExplorerUtils.getSize(currentFile.length()));
if(FileExplorerUtils.isProtected(currentFile))
{
holder.resActions.setVisibility(View.INVISIBLE);
}
else
{
holder.resActions.setVisibility(View.VISIBLE);
holder.resActions.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
- Log.d(Constants.TAG, "Clicked list item more button");
- showPopupMenu(v);
+ try
+ {
+ Log.d(Constants.TAG, "Clicked list item more button");
+ showPopupMenu(v);
+ }
+ catch (Exception e) {
+ e.printStackTrace();
+ }
}
});
}
return convertView;
}
public void showPopupMenu(View v) {
QuickActionHelper helper = new QuickActionHelper(mContext);
helper.onShowBar(v);
}
}
| true | true | public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.explorer_item, parent, false);
holder = new ViewHolder();
holder.resName = (TextView)convertView.findViewById(R.id.explorer_resName);
holder.resMeta = (TextView)convertView.findViewById(R.id.explorer_resMeta);
holder.resIcon = (ImageView)convertView.findViewById(R.id.explorer_resIcon);
holder.resActions = (ImageView)convertView.findViewById(R.id.explorer_resActions);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
File currentFile = files.get(position);
holder.resName.setText(currentFile.getName());
holder.resIcon.setImageDrawable(FileExplorerUtils.getIcon(mContext, currentFile));
holder.resMeta.setText(FileExplorerUtils.getSize(currentFile.length()));
if(FileExplorerUtils.isProtected(currentFile))
{
holder.resActions.setVisibility(View.INVISIBLE);
}
else
{
holder.resActions.setVisibility(View.VISIBLE);
holder.resActions.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d(Constants.TAG, "Clicked list item more button");
showPopupMenu(v);
}
});
}
return convertView;
}
| public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null)
{
convertView = mInflater.inflate(R.layout.explorer_item, parent, false);
holder = new ViewHolder();
holder.resName = (TextView)convertView.findViewById(R.id.explorer_resName);
holder.resMeta = (TextView)convertView.findViewById(R.id.explorer_resMeta);
holder.resIcon = (ImageView)convertView.findViewById(R.id.explorer_resIcon);
holder.resActions = (ImageView)convertView.findViewById(R.id.explorer_resActions);
convertView.setTag(holder);
}
else
{
holder = (ViewHolder)convertView.getTag();
}
File currentFile = files.get(position);
holder.resName.setText(currentFile.getName());
holder.resIcon.setImageDrawable(FileExplorerUtils.getIcon(mContext, currentFile));
holder.resMeta.setText(FileExplorerUtils.getSize(currentFile.length()));
if(FileExplorerUtils.isProtected(currentFile))
{
holder.resActions.setVisibility(View.INVISIBLE);
}
else
{
holder.resActions.setVisibility(View.VISIBLE);
holder.resActions.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
try
{
Log.d(Constants.TAG, "Clicked list item more button");
showPopupMenu(v);
}
catch (Exception e) {
e.printStackTrace();
}
}
});
}
return convertView;
}
|
diff --git a/src/com/wickedspiral/jacss/parser/Parser.java b/src/com/wickedspiral/jacss/parser/Parser.java
index e53095a..0ff14b3 100644
--- a/src/com/wickedspiral/jacss/parser/Parser.java
+++ b/src/com/wickedspiral/jacss/parser/Parser.java
@@ -1,564 +1,564 @@
package com.wickedspiral.jacss.parser;
import com.wickedspiral.jacss.Options;
import com.wickedspiral.jacss.lexer.Token;
import com.wickedspiral.jacss.lexer.TokenListener;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import static com.wickedspiral.jacss.lexer.Token.AT;
import static com.wickedspiral.jacss.lexer.Token.COLON;
import static com.wickedspiral.jacss.lexer.Token.COMMENT;
import static com.wickedspiral.jacss.lexer.Token.EQUALS;
import static com.wickedspiral.jacss.lexer.Token.GT;
import static com.wickedspiral.jacss.lexer.Token.HASH;
import static com.wickedspiral.jacss.lexer.Token.IDENTIFIER;
import static com.wickedspiral.jacss.lexer.Token.LBRACE;
import static com.wickedspiral.jacss.lexer.Token.LPAREN;
import static com.wickedspiral.jacss.lexer.Token.NUMBER;
import static com.wickedspiral.jacss.lexer.Token.PERCENT;
import static com.wickedspiral.jacss.lexer.Token.RBRACE;
import static com.wickedspiral.jacss.lexer.Token.RPAREN;
import static com.wickedspiral.jacss.lexer.Token.SEMICOLON;
import static com.wickedspiral.jacss.lexer.Token.STRING;
import static com.wickedspiral.jacss.lexer.Token.WHITESPACE;
/**
* @author wasche
* @since 2011.08.04
*/
public class Parser implements TokenListener
{
private static final String MS_ALPHA = "progid:dximagetransform.microsoft.alpha(opacity=";
private static final Collection<String> UNITS = new HashSet<>(
Arrays.asList("px", "em", "pt", "in", "cm", "mm", "pc", "ex", "%"));
private static final Collection<String> KEYWORDS = new HashSet<>(
Arrays.asList("normal", "bold", "italic", "serif", "sans-serif", "fixed"));
private static final Collection<String> BOUNDARY_OPS = new HashSet<>(
Arrays.asList("{", "}", ">", ";", ":", ",")); // or comment
private static final Collection<String> DUAL_ZERO_PROPERTIES = new HashSet<>(
Arrays.asList("background-position", "-webkit-transform-origin", "-moz-transform-origin"));
private static final Collection<String> NONE_PROPERTIES = new HashSet<>();
static
{
NONE_PROPERTIES.add("outline");
for (String property : new String[] {"border", "margin", "padding"})
{
NONE_PROPERTIES.add(property);
for (String edge : new String[]{"top", "left", "bottom", "right"})
{
NONE_PROPERTIES.add(property + "-" + edge);
}
}
}
// buffers
private LinkedList<String> ruleBuffer;
private LinkedList<String> valueBuffer;
private LinkedList<String> rgbBuffer;
private String pending;
// flags
private boolean inRule;
private boolean space;
private boolean charset;
private boolean at;
private boolean ie5mac;
private boolean rgb;
private int checkSpace;
// other state
private String property;
private Token lastToken;
private String lastValue;
private final PrintStream out;
private final Options options;
public Parser( PrintStream outputStream, Options options )
{
out = outputStream;
ruleBuffer = new LinkedList<>();
valueBuffer = new LinkedList<>();
rgbBuffer = new LinkedList<>();
inRule = false;
space = false;
charset = false;
at = false;
ie5mac = false;
rgb = false;
checkSpace = -1;
this.options = options;
}
// ++ Output functions
private void output( Collection<String> strings )
{
for ( String s : strings )
{
output( s );
}
}
private void output( String str )
{
out.print( str );
}
private void dump( String str )
{
ruleBuffer.add( pending );
ruleBuffer.add( str );
output( ruleBuffer );
ruleBuffer.clear();
}
private void write( String str )
{
if ( str == null || str.length() == 0 ) return;
if ( str.startsWith( "/*!" ) && ruleBuffer.isEmpty() )
{
output( str );
}
if ( "}".equals( str ) )
{
// check for empty rule
if ( !ruleBuffer.isEmpty() && !"{".equals( ruleBuffer.getLast() ) )
{
output( ruleBuffer );
output( str );
}
ruleBuffer.clear();
}
else
{
ruleBuffer.add( str );
}
}
private void buffer( String str )
{
if ( str == null || str.length() == 0 ) return;
if ( pending == null )
{
pending = str;
}
else
{
write( pending );
pending = str;
}
}
private void queue( String str )
{
if ( str == null || str.length() == 0 ) return;
if ( property != null )
{
valueBuffer.add( str );
}
else
{
buffer( str );
}
}
private void collapseValue()
{
StringBuilder sb = new StringBuilder();
for ( String s : valueBuffer )
{
sb.append( s );
}
String value = sb.toString();
if ( "0 0".equals( value ) || "0 0 0 0".equals( value ) || "0 0 0".equals( value ) )
{
if ( DUAL_ZERO_PROPERTIES.contains( property ) )
{
buffer( "0 0" );
}
else
{
buffer("0");
}
}
else if ("none".equals(value) && (NONE_PROPERTIES.contains(property) || "background".equals(property)) && options.shouldCollapseNone())
{
buffer("0");
}
else
{
buffer(value);
}
}
// ++ TokenListener
public void token(Token token, String value)
{
if (options.isDebug()) System.err.printf("Token: %s, value: %s\n", token, value);
if (rgb)
{
if (NUMBER == token)
{
String h = Integer.toHexString(Integer.parseInt(value)).toLowerCase();
if (h.length() < 2)
{
rgbBuffer.add("0");
}
rgbBuffer.add(h);
}
else if (LPAREN == token)
{
if (NUMBER == lastToken)
{
queue(" ");
}
queue("#");
rgbBuffer.clear();
}
else if (RPAREN == token)
{
if (rgbBuffer.size() == 3)
{
String a = rgbBuffer.get(0);
String b = rgbBuffer.get(1);
String c = rgbBuffer.get(2);
if (a.charAt(0) == a.charAt(1) &&
b.charAt(0) == b.charAt(1) &&
c.charAt(0) == c.charAt(1))
{
queue(a.substring(0, 1));
queue(b.substring(0, 1));
queue(c.substring(0, 1));
rgb = false;
return;
}
}
for (String s : rgbBuffer)
{
queue(s);
}
rgb = false;
}
return;
}
if (token == WHITESPACE)
{
space = true;
return; // most of these are unneeded
}
if (token == COMMENT)
{
// comments are only needed in a few places:
// 1) special comments /*! ... */
if ('!' == value.charAt(2))
{
queue(value);
lastToken = token;
lastValue = value;
}
// 2) IE5/Mac hack
else if ('\\' == value.charAt(value.length()-3))
{
queue("/*\\*/");
lastToken = token;
lastValue = value;
ie5mac = true;
}
else if (ie5mac)
{
queue("/**/");
lastToken = token;
lastValue = value;
ie5mac = false;
}
// 3) After a child selector
else if (GT == lastToken)
{
queue("/**/");
lastToken = token;
lastValue = value;
}
return;
}
// make sure we have space between values for multi-value properties
// margin: 5px 5px
if (
(
NUMBER == lastToken &&
(HASH == token || NUMBER == token)
) ||
(
(IDENTIFIER == lastToken || PERCENT == lastToken || RPAREN == lastToken) &&
(NUMBER == token || IDENTIFIER == token || HASH == token)
)
)
{
queue(" ");
space = false;
}
// rgb()
if (IDENTIFIER == token && "rgb".equals(value))
{
rgb = true;
space = false;
return;
}
if (AT == token)
{
queue(value);
at = true;
}
else if (inRule && COLON == token && property == null)
{
queue(value);
property = lastValue.toLowerCase();
valueBuffer.clear();
}
// first-letter and first-line must be followed by a space
else if (!inRule && COLON == lastToken && ("first-letter".equals(value) || "first-line".equals(value)))
{
queue(value);
queue(" ");
}
else if (SEMICOLON == token)
{
if (at)
{
at = false;
if ("charset".equals(ruleBuffer.get(1)))
{
if (charset)
{
ruleBuffer.clear();
pending = null;
}
else
{
charset = true;
dump(value);
}
}
else
{
dump(value);
}
}
else if (SEMICOLON == lastToken)
{
return; // skip duplicate semicolons
}
else
{
collapseValue();
valueBuffer.clear();
property = null;
queue(value);
}
}
else if (LBRACE == token)
{
if (checkSpace != -1)
{
// start of a rule, the space was correct
checkSpace = -1;
}
if (at)
{
at = false;
dump(value);
pending = null;
}
else
{
inRule = true;
queue(value);
}
}
else if (RBRACE == token)
{
if (checkSpace != -1)
{
// didn't start a rule, space was wrong
ruleBuffer.remove(checkSpace);
checkSpace = -1;
}
if (!valueBuffer.isEmpty())
{
collapseValue();
}
if (";".equals(pending))
{
if (options.keepTailingSemicolons())
{
buffer(";");
}
pending = value;
}
else
{
buffer(value);
}
property = null;
inRule = false;
}
else if (!inRule)
{
if (!space || GT == token || lastToken == null || BOUNDARY_OPS.contains(value))
{
queue(value);
}
else
{
if (COLON == token)
{
checkSpace = ruleBuffer.size() + 1; // include pending value
}
- if ( RBRACE != lastToken )
+ if ( RBRACE != lastToken && COMMENT != lastToken )
{
queue(" ");
}
queue(value);
space = false;
}
}
else if (NUMBER == token && value.startsWith("0."))
{
if ( options.shouldCollapseZeroes() )
{
queue(value.substring(1));
}
else
{
queue( value );
}
}
else if (STRING == token && "-ms-filter".equals(property))
{
if (value.toLowerCase().startsWith(MS_ALPHA, 1))
{
String c = value.substring(0, 1);
String o = value.substring(MS_ALPHA.length()+1, value.length()-2);
queue(c);
queue("alpha(opacity=");
queue(o);
queue(")");
queue(c);
}
else
{
queue(value);
}
}
else if (EQUALS == token)
{
queue(value);
StringBuilder sb = new StringBuilder();
for (String s : valueBuffer)
{
sb.append(s);
}
if (MS_ALPHA.equals(sb.toString().toLowerCase()))
{
buffer("alpha(opacity=");
valueBuffer.clear();
}
}
else
{
String v = value.toLowerCase();
// values of 0 don't need a unit
if (NUMBER == lastToken && "0".equals(lastValue) && (PERCENT == token || IDENTIFIER == token))
{
if (!UNITS.contains(value))
{
queue(" ");
queue(value);
}
}
// use 0 instead of none
else if (COLON == lastToken && "none".equals(value) && NONE_PROPERTIES.contains(property) && options.shouldCollapseNone())
{
queue("0");
}
// force properties to lower case for better gzip compression
else if (COLON != lastToken && IDENTIFIER == token)
{
// #aabbcc
if (HASH == lastToken)
{
if (value.length() == 6 &&
v.charAt(0) == v.charAt(1) &&
v.charAt(2) == v.charAt(3) &&
v.charAt(4) == v.charAt(5))
{
queue(v.substring(0, 1));
queue(v.substring(2, 3));
queue(v.substring(4, 5));
}
else
{
queue(v);
}
}
else
{
if (property == null || KEYWORDS.contains(v))
{
queue(v);
}
else
{
queue(value);
}
}
}
// nothing special, just send it along
else
{
if (KEYWORDS.contains(v))
{
queue(v);
}
else
{
queue(value);
}
}
}
lastToken = token;
lastValue = value;
space = false;
}
public void end()
{
write(pending);
if (!ruleBuffer.isEmpty())
{
output(ruleBuffer);
}
}
}
| true | true | public void token(Token token, String value)
{
if (options.isDebug()) System.err.printf("Token: %s, value: %s\n", token, value);
if (rgb)
{
if (NUMBER == token)
{
String h = Integer.toHexString(Integer.parseInt(value)).toLowerCase();
if (h.length() < 2)
{
rgbBuffer.add("0");
}
rgbBuffer.add(h);
}
else if (LPAREN == token)
{
if (NUMBER == lastToken)
{
queue(" ");
}
queue("#");
rgbBuffer.clear();
}
else if (RPAREN == token)
{
if (rgbBuffer.size() == 3)
{
String a = rgbBuffer.get(0);
String b = rgbBuffer.get(1);
String c = rgbBuffer.get(2);
if (a.charAt(0) == a.charAt(1) &&
b.charAt(0) == b.charAt(1) &&
c.charAt(0) == c.charAt(1))
{
queue(a.substring(0, 1));
queue(b.substring(0, 1));
queue(c.substring(0, 1));
rgb = false;
return;
}
}
for (String s : rgbBuffer)
{
queue(s);
}
rgb = false;
}
return;
}
if (token == WHITESPACE)
{
space = true;
return; // most of these are unneeded
}
if (token == COMMENT)
{
// comments are only needed in a few places:
// 1) special comments /*! ... */
if ('!' == value.charAt(2))
{
queue(value);
lastToken = token;
lastValue = value;
}
// 2) IE5/Mac hack
else if ('\\' == value.charAt(value.length()-3))
{
queue("/*\\*/");
lastToken = token;
lastValue = value;
ie5mac = true;
}
else if (ie5mac)
{
queue("/**/");
lastToken = token;
lastValue = value;
ie5mac = false;
}
// 3) After a child selector
else if (GT == lastToken)
{
queue("/**/");
lastToken = token;
lastValue = value;
}
return;
}
// make sure we have space between values for multi-value properties
// margin: 5px 5px
if (
(
NUMBER == lastToken &&
(HASH == token || NUMBER == token)
) ||
(
(IDENTIFIER == lastToken || PERCENT == lastToken || RPAREN == lastToken) &&
(NUMBER == token || IDENTIFIER == token || HASH == token)
)
)
{
queue(" ");
space = false;
}
// rgb()
if (IDENTIFIER == token && "rgb".equals(value))
{
rgb = true;
space = false;
return;
}
if (AT == token)
{
queue(value);
at = true;
}
else if (inRule && COLON == token && property == null)
{
queue(value);
property = lastValue.toLowerCase();
valueBuffer.clear();
}
// first-letter and first-line must be followed by a space
else if (!inRule && COLON == lastToken && ("first-letter".equals(value) || "first-line".equals(value)))
{
queue(value);
queue(" ");
}
else if (SEMICOLON == token)
{
if (at)
{
at = false;
if ("charset".equals(ruleBuffer.get(1)))
{
if (charset)
{
ruleBuffer.clear();
pending = null;
}
else
{
charset = true;
dump(value);
}
}
else
{
dump(value);
}
}
else if (SEMICOLON == lastToken)
{
return; // skip duplicate semicolons
}
else
{
collapseValue();
valueBuffer.clear();
property = null;
queue(value);
}
}
else if (LBRACE == token)
{
if (checkSpace != -1)
{
// start of a rule, the space was correct
checkSpace = -1;
}
if (at)
{
at = false;
dump(value);
pending = null;
}
else
{
inRule = true;
queue(value);
}
}
else if (RBRACE == token)
{
if (checkSpace != -1)
{
// didn't start a rule, space was wrong
ruleBuffer.remove(checkSpace);
checkSpace = -1;
}
if (!valueBuffer.isEmpty())
{
collapseValue();
}
if (";".equals(pending))
{
if (options.keepTailingSemicolons())
{
buffer(";");
}
pending = value;
}
else
{
buffer(value);
}
property = null;
inRule = false;
}
else if (!inRule)
{
if (!space || GT == token || lastToken == null || BOUNDARY_OPS.contains(value))
{
queue(value);
}
else
{
if (COLON == token)
{
checkSpace = ruleBuffer.size() + 1; // include pending value
}
if ( RBRACE != lastToken )
{
queue(" ");
}
queue(value);
space = false;
}
}
else if (NUMBER == token && value.startsWith("0."))
{
if ( options.shouldCollapseZeroes() )
{
queue(value.substring(1));
}
else
{
queue( value );
}
}
else if (STRING == token && "-ms-filter".equals(property))
{
if (value.toLowerCase().startsWith(MS_ALPHA, 1))
{
String c = value.substring(0, 1);
String o = value.substring(MS_ALPHA.length()+1, value.length()-2);
queue(c);
queue("alpha(opacity=");
queue(o);
queue(")");
queue(c);
}
else
{
queue(value);
}
}
else if (EQUALS == token)
{
queue(value);
StringBuilder sb = new StringBuilder();
for (String s : valueBuffer)
{
sb.append(s);
}
if (MS_ALPHA.equals(sb.toString().toLowerCase()))
{
buffer("alpha(opacity=");
valueBuffer.clear();
}
}
else
{
String v = value.toLowerCase();
// values of 0 don't need a unit
if (NUMBER == lastToken && "0".equals(lastValue) && (PERCENT == token || IDENTIFIER == token))
{
if (!UNITS.contains(value))
{
queue(" ");
queue(value);
}
}
// use 0 instead of none
else if (COLON == lastToken && "none".equals(value) && NONE_PROPERTIES.contains(property) && options.shouldCollapseNone())
{
queue("0");
}
// force properties to lower case for better gzip compression
else if (COLON != lastToken && IDENTIFIER == token)
{
// #aabbcc
if (HASH == lastToken)
{
if (value.length() == 6 &&
v.charAt(0) == v.charAt(1) &&
v.charAt(2) == v.charAt(3) &&
v.charAt(4) == v.charAt(5))
{
queue(v.substring(0, 1));
queue(v.substring(2, 3));
queue(v.substring(4, 5));
}
else
{
queue(v);
}
}
else
{
if (property == null || KEYWORDS.contains(v))
{
queue(v);
}
else
{
queue(value);
}
}
}
// nothing special, just send it along
else
{
if (KEYWORDS.contains(v))
{
queue(v);
}
else
{
queue(value);
}
}
}
lastToken = token;
lastValue = value;
space = false;
}
| public void token(Token token, String value)
{
if (options.isDebug()) System.err.printf("Token: %s, value: %s\n", token, value);
if (rgb)
{
if (NUMBER == token)
{
String h = Integer.toHexString(Integer.parseInt(value)).toLowerCase();
if (h.length() < 2)
{
rgbBuffer.add("0");
}
rgbBuffer.add(h);
}
else if (LPAREN == token)
{
if (NUMBER == lastToken)
{
queue(" ");
}
queue("#");
rgbBuffer.clear();
}
else if (RPAREN == token)
{
if (rgbBuffer.size() == 3)
{
String a = rgbBuffer.get(0);
String b = rgbBuffer.get(1);
String c = rgbBuffer.get(2);
if (a.charAt(0) == a.charAt(1) &&
b.charAt(0) == b.charAt(1) &&
c.charAt(0) == c.charAt(1))
{
queue(a.substring(0, 1));
queue(b.substring(0, 1));
queue(c.substring(0, 1));
rgb = false;
return;
}
}
for (String s : rgbBuffer)
{
queue(s);
}
rgb = false;
}
return;
}
if (token == WHITESPACE)
{
space = true;
return; // most of these are unneeded
}
if (token == COMMENT)
{
// comments are only needed in a few places:
// 1) special comments /*! ... */
if ('!' == value.charAt(2))
{
queue(value);
lastToken = token;
lastValue = value;
}
// 2) IE5/Mac hack
else if ('\\' == value.charAt(value.length()-3))
{
queue("/*\\*/");
lastToken = token;
lastValue = value;
ie5mac = true;
}
else if (ie5mac)
{
queue("/**/");
lastToken = token;
lastValue = value;
ie5mac = false;
}
// 3) After a child selector
else if (GT == lastToken)
{
queue("/**/");
lastToken = token;
lastValue = value;
}
return;
}
// make sure we have space between values for multi-value properties
// margin: 5px 5px
if (
(
NUMBER == lastToken &&
(HASH == token || NUMBER == token)
) ||
(
(IDENTIFIER == lastToken || PERCENT == lastToken || RPAREN == lastToken) &&
(NUMBER == token || IDENTIFIER == token || HASH == token)
)
)
{
queue(" ");
space = false;
}
// rgb()
if (IDENTIFIER == token && "rgb".equals(value))
{
rgb = true;
space = false;
return;
}
if (AT == token)
{
queue(value);
at = true;
}
else if (inRule && COLON == token && property == null)
{
queue(value);
property = lastValue.toLowerCase();
valueBuffer.clear();
}
// first-letter and first-line must be followed by a space
else if (!inRule && COLON == lastToken && ("first-letter".equals(value) || "first-line".equals(value)))
{
queue(value);
queue(" ");
}
else if (SEMICOLON == token)
{
if (at)
{
at = false;
if ("charset".equals(ruleBuffer.get(1)))
{
if (charset)
{
ruleBuffer.clear();
pending = null;
}
else
{
charset = true;
dump(value);
}
}
else
{
dump(value);
}
}
else if (SEMICOLON == lastToken)
{
return; // skip duplicate semicolons
}
else
{
collapseValue();
valueBuffer.clear();
property = null;
queue(value);
}
}
else if (LBRACE == token)
{
if (checkSpace != -1)
{
// start of a rule, the space was correct
checkSpace = -1;
}
if (at)
{
at = false;
dump(value);
pending = null;
}
else
{
inRule = true;
queue(value);
}
}
else if (RBRACE == token)
{
if (checkSpace != -1)
{
// didn't start a rule, space was wrong
ruleBuffer.remove(checkSpace);
checkSpace = -1;
}
if (!valueBuffer.isEmpty())
{
collapseValue();
}
if (";".equals(pending))
{
if (options.keepTailingSemicolons())
{
buffer(";");
}
pending = value;
}
else
{
buffer(value);
}
property = null;
inRule = false;
}
else if (!inRule)
{
if (!space || GT == token || lastToken == null || BOUNDARY_OPS.contains(value))
{
queue(value);
}
else
{
if (COLON == token)
{
checkSpace = ruleBuffer.size() + 1; // include pending value
}
if ( RBRACE != lastToken && COMMENT != lastToken )
{
queue(" ");
}
queue(value);
space = false;
}
}
else if (NUMBER == token && value.startsWith("0."))
{
if ( options.shouldCollapseZeroes() )
{
queue(value.substring(1));
}
else
{
queue( value );
}
}
else if (STRING == token && "-ms-filter".equals(property))
{
if (value.toLowerCase().startsWith(MS_ALPHA, 1))
{
String c = value.substring(0, 1);
String o = value.substring(MS_ALPHA.length()+1, value.length()-2);
queue(c);
queue("alpha(opacity=");
queue(o);
queue(")");
queue(c);
}
else
{
queue(value);
}
}
else if (EQUALS == token)
{
queue(value);
StringBuilder sb = new StringBuilder();
for (String s : valueBuffer)
{
sb.append(s);
}
if (MS_ALPHA.equals(sb.toString().toLowerCase()))
{
buffer("alpha(opacity=");
valueBuffer.clear();
}
}
else
{
String v = value.toLowerCase();
// values of 0 don't need a unit
if (NUMBER == lastToken && "0".equals(lastValue) && (PERCENT == token || IDENTIFIER == token))
{
if (!UNITS.contains(value))
{
queue(" ");
queue(value);
}
}
// use 0 instead of none
else if (COLON == lastToken && "none".equals(value) && NONE_PROPERTIES.contains(property) && options.shouldCollapseNone())
{
queue("0");
}
// force properties to lower case for better gzip compression
else if (COLON != lastToken && IDENTIFIER == token)
{
// #aabbcc
if (HASH == lastToken)
{
if (value.length() == 6 &&
v.charAt(0) == v.charAt(1) &&
v.charAt(2) == v.charAt(3) &&
v.charAt(4) == v.charAt(5))
{
queue(v.substring(0, 1));
queue(v.substring(2, 3));
queue(v.substring(4, 5));
}
else
{
queue(v);
}
}
else
{
if (property == null || KEYWORDS.contains(v))
{
queue(v);
}
else
{
queue(value);
}
}
}
// nothing special, just send it along
else
{
if (KEYWORDS.contains(v))
{
queue(v);
}
else
{
queue(value);
}
}
}
lastToken = token;
lastValue = value;
space = false;
}
|
diff --git a/src/main/java/org/spout/logging/file/RotatingFileHandler.java b/src/main/java/org/spout/logging/file/RotatingFileHandler.java
index 7b85728b8..8974c4146 100644
--- a/src/main/java/org/spout/logging/file/RotatingFileHandler.java
+++ b/src/main/java/org/spout/logging/file/RotatingFileHandler.java
@@ -1,200 +1,200 @@
/*
* This file is part of Spout.
*
* Copyright (c) 2013 Spout LLC <http://www.spout.org/>
* Spout is licensed under the Spout License Version 1.
*
* Spout is free software: you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation, either version 3 of the License, or (at your option)
* any later version.
*
* In addition, 180 days after any changes are published, you can use the
* software, incorporating those changes, under the terms of the MIT license,
* as described in the Spout License Version 1.
*
* Spout 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,
* the MIT license and the Spout License Version 1 along with this program.
* If not, see <http://www.gnu.org/licenses/> for the GNU Lesser General Public
* License and see <http://spout.in/licensev1> for the full license, including
* the MIT license.
*/
package org.spout.logging.file;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.locks.ReentrantLock;
import java.util.logging.Formatter;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
/**
* A formatted rotating file handler, with separate files for each day of logs
*/
public class RotatingFileHandler extends Handler {
private final SimpleDateFormat date;
private final String fileNameFormat;
private final File logDir;
private final boolean autoFlush;
private String logFileName;
private final LogFlushThread logFlush;
private final ReentrantLock writerLock = new ReentrantLock();
private OutputStreamWriter writer;
private DateFormat dateFormat;
private final AtomicBoolean closed = new AtomicBoolean(false);
/**
* Creates a rotating file handler with the specified date handler.
* Use %D for a placeholder for the date in the log name.
*
* @param logDir the directory to create logs in
* @param fileNameFormat
* @param autoFlush whether to automatically flush after every log record
*/
public RotatingFileHandler(File logDir, String fileNameFormat, boolean autoFlush) {
this.logDir = logDir;
this.fileNameFormat = fileNameFormat;
this.autoFlush = autoFlush;
setDateFormat(new SimpleDateFormat("HH:mm:ss"));
date = new SimpleDateFormat("yyyy-MM-dd");
logFileName = calculateFilename();
initImpl();
logFlush = new LogFlushThread();
logFlush.start();
}
private File getLogFile() {
if (!logDir.exists()) {
logDir.mkdirs();
}
return new File(logDir, logFileName);
}
private String calculateFilename() {
return fileNameFormat.replace("%D", date.format(new Date()));
}
private void initImpl() {
File logFile = getLogFile();
try {
writer = new OutputStreamWriter(new FileOutputStream(logFile, true));
} catch (FileNotFoundException ex) {
throw new RuntimeException("Unable to write to " + logFile.getName() + " at " + logFile.getPath());
}
}
@Override
public void close() throws SecurityException {
if (closed.compareAndSet(false, true)) {
closeImpl();
}
}
private void closeImpl() {
try {
if (writer != null) {
writer.close();
}
} catch (IOException ignore) {}
if (logFlush != null) {
logFlush.interrupt();
}
}
@Override
public void flush() {
writerLock.lock();
try {
if (!logFileName.equals(calculateFilename())) {
logFileName = calculateFilename();
try {
writer.close();
} catch (IOException ignore) { }
initImpl();
}
try {
writer.flush();
} catch (IOException ignore) {}
} finally {
writerLock.unlock();
}
}
public void setDateFormat(DateFormat format) {
this.dateFormat = format;
}
public DateFormat getDateFormat() {
return dateFormat;
}
@Override
public void publish(LogRecord record) {
writerLock.lock();
try {
if (writer == null) {
return;
}
- appendDateFormat(writer);
String message;
Formatter formatter = getFormatter();
if (formatter != null) {
message = formatter.format(record);
} else {
message = record.getMessage();
}
- for (String line :message.split("\n")) {
+ for (String line : message.split("\n")) {
+ appendDateFormat(writer);
writer.write(line);
writer.write('\n');
}
if (autoFlush) {
flush();
}
} catch (IOException e) {
return;
} finally {
writerLock.unlock();
}
}
private void appendDateFormat(Writer writer) throws IOException {
DateFormat dateFormat = getDateFormat();
if (dateFormat != null) {
writer.write("[");
writer.write(dateFormat.format(new Date()));
writer.write("] ");
}
}
private class LogFlushThread extends Thread {
public LogFlushThread() {
super("Log Flush Thread");
this.setDaemon(true);
}
@Override
public void run() {
while (!this.isInterrupted()) {
flush();
try {
sleep(60000);
} catch (InterruptedException e) {
}
}
}
}
}
| false | true | public void publish(LogRecord record) {
writerLock.lock();
try {
if (writer == null) {
return;
}
appendDateFormat(writer);
String message;
Formatter formatter = getFormatter();
if (formatter != null) {
message = formatter.format(record);
} else {
message = record.getMessage();
}
for (String line :message.split("\n")) {
writer.write(line);
writer.write('\n');
}
if (autoFlush) {
flush();
}
} catch (IOException e) {
return;
} finally {
writerLock.unlock();
}
}
| public void publish(LogRecord record) {
writerLock.lock();
try {
if (writer == null) {
return;
}
String message;
Formatter formatter = getFormatter();
if (formatter != null) {
message = formatter.format(record);
} else {
message = record.getMessage();
}
for (String line : message.split("\n")) {
appendDateFormat(writer);
writer.write(line);
writer.write('\n');
}
if (autoFlush) {
flush();
}
} catch (IOException e) {
return;
} finally {
writerLock.unlock();
}
}
|
diff --git a/crittercaptors/src/com/blastedstudios/crittercaptors/ui/battle/BattleScreen.java b/crittercaptors/src/com/blastedstudios/crittercaptors/ui/battle/BattleScreen.java
index e2d1a7a..4229cf7 100644
--- a/crittercaptors/src/com/blastedstudios/crittercaptors/ui/battle/BattleScreen.java
+++ b/crittercaptors/src/com/blastedstudios/crittercaptors/ui/battle/BattleScreen.java
@@ -1,95 +1,98 @@
package com.blastedstudios.crittercaptors.ui.battle;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Camera;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Vector3;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.ui.ClickListener;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.TextField;
import com.badlogic.gdx.scenes.scene2d.ui.Window;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
import com.blastedstudios.crittercaptors.CritterCaptors;
import com.blastedstudios.crittercaptors.ExperienceManager;
import com.blastedstudios.crittercaptors.creature.Creature;
import com.blastedstudios.crittercaptors.ui.AbstractScreen;
import com.blastedstudios.crittercaptors.ui.worldmap.WorldMap;
import com.blastedstudios.crittercaptors.util.RenderUtil;
public class BattleScreen extends AbstractScreen {
private Creature enemy;
private Camera camera;
private CreatureInfoWindow creatureInfoWindow, enemyInfoWindow;
private SpriteBatch spriteBatch;
public BattleScreen(CritterCaptors game, Creature enemy) {
super(game);
this.enemy = enemy;
creatureInfoWindow = new CreatureInfoWindow(game, skin, game.getCharacter().getActiveCreature(), 0, (int)stage.height()-200);
enemyInfoWindow = new CreatureInfoWindow(game, skin, enemy, (int)stage.width()-236, 200);
stage.addActor(creatureInfoWindow);
stage.addActor(enemyInfoWindow);
stage.addActor(new BottomMenu(game, skin, this));
spriteBatch = new SpriteBatch();
}
@Override public void render(float arg0){
camera.update();
camera.apply(Gdx.gl10);
Gdx.gl10.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
RenderUtil.drawSky(game.getModel("skydome"), game.getTexture("skydome"), camera.position);
RenderUtil.drawModel(game.getModel(enemy.getName()), new Vector3(-3, 0, 10),
new Vector3(-1,0,-1), new Vector3(100f,100f,100f));
RenderUtil.drawModel(game.getModel(enemy.getName()), new Vector3(1, 0, 3.5f),
new Vector3(1,0,1), new Vector3(100f,100f,100f));
spriteBatch.begin();
spriteBatch.end();
stage.act(arg0);
stage.draw();
}
public void fight(String name) {
int enemyChoice = CritterCaptors.random.nextInt(enemy.getActiveAbilities().size());
Creature playerCreature = game.getCharacter().getActiveCreature();
if(enemy.receiveDamage(playerCreature.attack(enemy, name))){//enemy is dead
//show window indicating victory!
playerCreature.addExperience(ExperienceManager.getKillExperience(enemy));
playerCreature.getEV().add(enemy.getEVYield());
game.setScreen(new WorldMap(game));
}else
playerCreature.receiveDamage(enemy.attack(playerCreature, enemy.getActiveAbilities().get(enemyChoice).name));
creatureInfoWindow.update();
enemyInfoWindow.update();
stage.addActor(new BottomMenu(game, skin, this));
}
@Override public void resize (int width, int height) {
camera = RenderUtil.resize(width, height);
}
public void capture() {
if(CritterCaptors.random.nextFloat() <= enemy.getCatchRate()){
enemy.setActive(game.getCharacter().getNextEmptyActiveIndex());
game.getCharacter().getOwnedCreatures().add(enemy);
game.setScreen(new WorldMap(game));
return;
}
final Window failWindow = new Window(skin);
final Button okButton = new TextButton("Ok", skin.getStyle(TextButtonStyle.class), "ok");
okButton.setClickListener(new ClickListener() {
@Override public void click(Actor actor, float arg1, float arg2) {
actor.getStage().removeActor(failWindow);
}
});
- failWindow.add(new TextField("You have failed to catch!", skin));
+ failWindow.add(new TextField("Catch failed! ", skin));
+ failWindow.row();
+ failWindow.add(okButton);
failWindow.pack();
failWindow.x = Gdx.graphics.getWidth() / 2 - failWindow.width / 2;
failWindow.y = Gdx.graphics.getHeight() / 2 - failWindow.height / 2;
+ stage.addActor(failWindow);
}
}
| false | true | public void capture() {
if(CritterCaptors.random.nextFloat() <= enemy.getCatchRate()){
enemy.setActive(game.getCharacter().getNextEmptyActiveIndex());
game.getCharacter().getOwnedCreatures().add(enemy);
game.setScreen(new WorldMap(game));
return;
}
final Window failWindow = new Window(skin);
final Button okButton = new TextButton("Ok", skin.getStyle(TextButtonStyle.class), "ok");
okButton.setClickListener(new ClickListener() {
@Override public void click(Actor actor, float arg1, float arg2) {
actor.getStage().removeActor(failWindow);
}
});
failWindow.add(new TextField("You have failed to catch!", skin));
failWindow.pack();
failWindow.x = Gdx.graphics.getWidth() / 2 - failWindow.width / 2;
failWindow.y = Gdx.graphics.getHeight() / 2 - failWindow.height / 2;
}
| public void capture() {
if(CritterCaptors.random.nextFloat() <= enemy.getCatchRate()){
enemy.setActive(game.getCharacter().getNextEmptyActiveIndex());
game.getCharacter().getOwnedCreatures().add(enemy);
game.setScreen(new WorldMap(game));
return;
}
final Window failWindow = new Window(skin);
final Button okButton = new TextButton("Ok", skin.getStyle(TextButtonStyle.class), "ok");
okButton.setClickListener(new ClickListener() {
@Override public void click(Actor actor, float arg1, float arg2) {
actor.getStage().removeActor(failWindow);
}
});
failWindow.add(new TextField("Catch failed! ", skin));
failWindow.row();
failWindow.add(okButton);
failWindow.pack();
failWindow.x = Gdx.graphics.getWidth() / 2 - failWindow.width / 2;
failWindow.y = Gdx.graphics.getHeight() / 2 - failWindow.height / 2;
stage.addActor(failWindow);
}
|
diff --git a/server/src/main/java/us/codecraft/blackhole/connector/UDPConnectionWorker.java b/server/src/main/java/us/codecraft/blackhole/connector/UDPConnectionWorker.java
index 3d5c85e..754f5fa 100755
--- a/server/src/main/java/us/codecraft/blackhole/connector/UDPConnectionWorker.java
+++ b/server/src/main/java/us/codecraft/blackhole/connector/UDPConnectionWorker.java
@@ -1,51 +1,52 @@
package us.codecraft.blackhole.connector;
import org.apache.log4j.Logger;
import org.xbill.DNS.Message;
import us.codecraft.blackhole.container.QueryProcesser;
import us.codecraft.blackhole.context.RequestContextProcessor;
import us.codecraft.blackhole.forward.Forwarder;
import java.net.DatagramPacket;
public class UDPConnectionWorker implements Runnable {
private static final Logger logger = Logger
.getLogger(UDPConnectionWorker.class);
private final UDPConnectionResponser responser;
private final DatagramPacket inDataPacket;
private QueryProcesser queryProcesser;
private Forwarder forwarder;
public UDPConnectionWorker(DatagramPacket inDataPacket,
QueryProcesser queryProcesser, UDPConnectionResponser responser,
Forwarder forwarder) {
super();
this.responser = responser;
this.inDataPacket = inDataPacket;
this.queryProcesser = queryProcesser;
this.forwarder = forwarder;
}
public void run() {
try {
RequestContextProcessor.processRequest(inDataPacket);
byte[] response = queryProcesser.process(inDataPacket.getData());
if (response != null) {
responser.response(response);
} else {
- forwarder.forward(inDataPacket.getData(), new Message(
- inDataPacket.getData()), responser);
+ Message query = new Message(
+ inDataPacket.getData());
+ forwarder.forward(query.toWire(), query, responser);
}
} catch (Throwable e) {
logger.warn(
"Error processing UDP connection from "
+ inDataPacket.getSocketAddress() + ", ", e);
}
}
}
| true | true | public void run() {
try {
RequestContextProcessor.processRequest(inDataPacket);
byte[] response = queryProcesser.process(inDataPacket.getData());
if (response != null) {
responser.response(response);
} else {
forwarder.forward(inDataPacket.getData(), new Message(
inDataPacket.getData()), responser);
}
} catch (Throwable e) {
logger.warn(
"Error processing UDP connection from "
+ inDataPacket.getSocketAddress() + ", ", e);
}
}
| public void run() {
try {
RequestContextProcessor.processRequest(inDataPacket);
byte[] response = queryProcesser.process(inDataPacket.getData());
if (response != null) {
responser.response(response);
} else {
Message query = new Message(
inDataPacket.getData());
forwarder.forward(query.toWire(), query, responser);
}
} catch (Throwable e) {
logger.warn(
"Error processing UDP connection from "
+ inDataPacket.getSocketAddress() + ", ", e);
}
}
|
diff --git a/tool/src/java/org/sakaiproject/tool/assessment/ui/listener/evaluation/HistogramListener.java b/tool/src/java/org/sakaiproject/tool/assessment/ui/listener/evaluation/HistogramListener.java
index 17c4e305c..fe0086a46 100755
--- a/tool/src/java/org/sakaiproject/tool/assessment/ui/listener/evaluation/HistogramListener.java
+++ b/tool/src/java/org/sakaiproject/tool/assessment/ui/listener/evaluation/HistogramListener.java
@@ -1,1349 +1,1349 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2004-2005 The Regents of the University of Michigan, Trustees of Indiana University,
* Board of Trustees of the Leland Stanford, Jr., University, and The MIT Corporation
*
* Licensed under the Educational Community License Version 1.0 (the "License");
* By obtaining, using and/or copying this Original Work, you agree that you have read,
* understand, and will comply with the terms and conditions of the Educational Community License.
* You may obtain a copy of the License at:
*
* http://cvs.sakaiproject.org/licenses/license_1_0.html
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
* DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**********************************************************************************/
package org.sakaiproject.tool.assessment.ui.listener.evaluation;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.StringTokenizer;
import javax.faces.event.AbortProcessingException;
import javax.faces.event.ActionEvent;
import javax.faces.event.ActionListener;
import javax.faces.event.ValueChangeEvent;
import javax.faces.event.ValueChangeListener;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.sakaiproject.tool.assessment.data.dao.assessment.PublishedAssessmentData;
import org.sakaiproject.tool.assessment.data.dao.grading.AssessmentGradingData;
import org.sakaiproject.tool.assessment.data.dao.grading.ItemGradingData;
import org.sakaiproject.tool.assessment.data.ifc.assessment.AnswerIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemDataIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.ItemTextIfc;
import org.sakaiproject.tool.assessment.data.ifc.assessment.SectionDataIfc;
import org.sakaiproject.tool.assessment.services.GradingService;
import org.sakaiproject.tool.assessment.services.PersistenceService;
import org.sakaiproject.tool.assessment.ui.bean.evaluation.HistogramBarBean;
import org.sakaiproject.tool.assessment.ui.bean.evaluation.HistogramQuestionScoresBean;
import org.sakaiproject.tool.assessment.ui.bean.evaluation.HistogramScoresBean;
import org.sakaiproject.tool.assessment.ui.bean.evaluation.TotalScoresBean;
import org.sakaiproject.tool.assessment.ui.listener.evaluation.util.EvaluationListenerUtil;
import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil;
import org.sakaiproject.tool.assessment.util.BeanSort;
/**
* <p>
* This handles the selection of the Histogram Aggregate Statistics.
* </p>
* <p>Description: Action Listener for Evaluation Histogram Aggregate Statistics.</p>
* <p>Copyright: Copyright (c) 2004</p>
* <p>Organization: Sakai Project</p>
* @author Ed Smiley
* @version $Id$
*/
public class HistogramListener
implements ActionListener, ValueChangeListener
{
private static Log log = LogFactory.getLog(HistogramListener.class);
private static BeanSort bs;
private static ContextUtil cu;
private static EvaluationListenerUtil util;
/**
* Standard process action method.
* @param ae ActionEvent
* @throws AbortProcessingException
*/
public void processAction(ActionEvent ae) throws
AbortProcessingException
{
log.info("HistogramAggregate Statistics LISTENER.");
TotalScoresBean totalBean = (TotalScoresBean) cu.lookupBean(
"totalScores");
HistogramScoresBean bean = (HistogramScoresBean) cu.lookupBean(
"histogramScores");
String publishedId = totalBean.getPublishedId();
if (publishedId == "0")
{
publishedId = (String) cu.lookupParam("publishedId");
}
log.info("Calling histogramScores.");
if (!histogramScores(publishedId, bean, totalBean))
{
throw new RuntimeException("failed to call questionScores.");
}
}
/**
* Process a value change.
*/
public void processValueChange(ValueChangeEvent event)
{
log.info("HistogramAggregate Statistics Value Change LISTENER.");
TotalScoresBean totalBean = (TotalScoresBean) cu.lookupBean(
"totalScores");
HistogramScoresBean bean = (HistogramScoresBean) cu.lookupBean(
"histogramScores");
String publishedId = totalBean.getPublishedId();
if (publishedId == "0")
{
publishedId = (String) cu.lookupParam("publishedId");
}
log.info("Calling histogramScores.");
if (!histogramScores(publishedId, bean, totalBean))
{
throw new RuntimeException("failed to call questionScores.");
}
}
/**
* This will populate the HistogramScoresBean with the data associated with the
* particular versioned assessment based on the publishedId.
*
* Some of this code will change when we move this to Hibernate persistence.
* @param publishedId String
* @param bean TotalScoresBean
* @return boolean true if successful
*/
public boolean histogramScores(
String publishedId, HistogramScoresBean bean, TotalScoresBean totalBean)
{
try {
String assessmentName = "";
// Get all submissions, or just the last?
String which = cu.lookupParam("allSubmissions");
//log.info("Rachel: allSubmissions = " + which);
if (which == null)
which = "false";
bean.setAllSubmissions(which.equals("true")?true:false);
bean.setItemId(cu.lookupParam("itemId"));
bean.setHasNav(cu.lookupParam("hasNav"));
GradingService delegate = new GradingService();
ArrayList scores = delegate.getTotalScores(publishedId, which);
HashMap itemscores = delegate.getItemScores(new Long(publishedId),
new Long(0), which);
//log.info("ItemScores size = " + itemscores.keySet().size());
bean.setPublishedId(publishedId);
Iterator iter = scores.iterator();
//log.info("Has this many agents: " + scores.size());
if (!iter.hasNext())
return false;
Object next = iter.next();
AssessmentGradingData data = (AssessmentGradingData) next;
if (data.getPublishedAssessment() != null)
{
assessmentName = data.getPublishedAssessment().getTitle();
log.info("ASSESSMENT NAME= " + assessmentName);
// if section set is null, initialize it - daisyf , 01/31/05
PublishedAssessmentData pub = (PublishedAssessmentData)data.getPublishedAssessment();
HashSet sectionSet = PersistenceService.getInstance().
getPublishedAssessmentFacadeQueries().getSectionSetForAssessment(pub);
data.getPublishedAssessment().setSectionSet(sectionSet);
ArrayList parts =
data.getPublishedAssessment().getSectionArraySorted();
ArrayList info = new ArrayList();
Iterator piter = parts.iterator();
int secseq = 1;
double totalpossible = 0;
boolean hasRandompart = false;
boolean isRandompart = false;
while (piter.hasNext()) {
SectionDataIfc section = (SectionDataIfc) piter.next();
String authortype = section.getSectionMetaDataByLabel(SectionDataIfc.AUTHOR_TYPE);
- if (SectionDataIfc.RANDOM_DRAW_FROM_QUESTIONPOOL.equals(authortype)){
+ if (SectionDataIfc.RANDOM_DRAW_FROM_QUESTIONPOOL.equals(new Integer(authortype))){
hasRandompart = true;
isRandompart = true;
}
else {
isRandompart = false;
}
if (section.getSequence() == null)
section.setSequence(new Integer(secseq++));
String title = "Part " + section.getSequence().toString();
title += ", Question ";
ArrayList itemset = section.getItemArraySortedForGrading();
int seq = 1;
Iterator iter2 = itemset.iterator();
while (iter2.hasNext())
{
HistogramQuestionScoresBean qbean =
new HistogramQuestionScoresBean();
// if this part is a randompart , then set randompart = true
qbean.setRandomType(isRandompart);
ItemDataIfc item = (ItemDataIfc) iter2.next();
String type = delegate.getTextForId(item.getTypeId());
if (item.getSequence() == null)
item.setSequence(new Integer(seq++));
qbean.setTitle(title + item.getSequence().toString() +
" (" + type + ")");
qbean.setQuestionText(item.getText());
qbean.setQuestionType(item.getTypeId().toString());
//totalpossible = totalpossible + item.getScore().doubleValue();
ArrayList responses = null;
determineResults(qbean, (ArrayList) itemscores.get
(item.getItemId()));
qbean.setTotalScore(item.getScore().toString());
info.add(qbean);
}
totalpossible = data.getPublishedAssessment().getTotalScore().doubleValue();
}
bean.setInfo(info);
bean.setRandomType(hasRandompart);
// here scores contain AssessmentGradingData
Map assessmentMap = getAssessmentStatisticsMap(scores);
// test to see if it gets back empty map
if (assessmentMap.isEmpty())
{
bean.setNumResponses(0);
}
try
{
BeanUtils.populate(bean, assessmentMap);
// quartiles don't seem to be working, workaround
bean.setQ1( (String) assessmentMap.get("q1"));
bean.setQ2( (String) assessmentMap.get("q2"));
bean.setQ3( (String) assessmentMap.get("q3"));
bean.setQ4( (String) assessmentMap.get("q4"));
bean.setTotalScore( (String) assessmentMap.get("totalScore"));
bean.setTotalPossibleScore(new Double(totalpossible).toString());
HistogramBarBean[] bars =
new HistogramBarBean[bean.getColumnHeight().length];
for (int i=0; i<bean.getColumnHeight().length; i++)
{
bars[i] = new HistogramBarBean();
bars[i].setColumnHeight
(new Integer(bean.getColumnHeight()[i]).toString());
bars[i].setNumStudents(bean.getNumStudentCollection()[i]);
bars[i].setRangeInfo(bean.getRangeCollection()[i]);
//log.info("Set bar " + i + ": " + bean.getColumnHeight()[i] + ", " + bean.getNumStudentCollection()[i] + ", " + bean.getRangeCollection()[i]);
}
bean.setHistogramBars(bars);
///////////////////////////////////////////////////////////
// START DEBUGGING
log.info("TESTING ASSESSMENT MAP");
log.info("assessmentMap: =>");
log.info(assessmentMap);
log.info("--------------------------------------------");
log.info("TESTING TOTALS HISTOGRAM FORM");
log.info(
"HistogramScoresForm Form: =>\n" + "bean.getMean()=" +
bean.getMean() + "\n" +
"bean.getColumnHeight()[0] (first elem)=" +
bean.getColumnHeight()[0] + "\n" + "bean.getInterval()=" +
bean.getInterval() + "\n" + "bean.getLowerQuartile()=" +
bean.getLowerQuartile() + "\n" + "bean.getMaxScore()=" +
bean.getMaxScore() + "\n" + "bean.getMean()=" + bean.getMean() +
"\n" + "bean.getMedian()=" + bean.getMedian() + "\n" +
"bean.getNumResponses()=" + bean.getNumResponses() + "\n" +
"bean.getNumStudentCollection()=" +
bean.getNumStudentCollection() +
"\n" + "bean.getQ1()=" + bean.getQ1() + "\n" + "bean.getQ2()=" +
bean.getQ2() + "\n" + "bean.getQ3()=" + bean.getQ3() + "\n" +
"bean.getQ4()=" + bean.getQ4());
log.info("--------------------------------------------");
// END DEBUGGING CODE
///////////////////////////////////////////////////////////
}
catch (Exception e)
{
log.info("unable to populate bean" + e);
}
bean.setAssessmentName(assessmentName);
}
else
{
return false;
}
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
return true;
}
public void determineResults(HistogramQuestionScoresBean qbean,
ArrayList itemScores)
{
if (itemScores == null)
itemScores = new ArrayList();
if (qbean.getQuestionType().equals("1") || // mcsc
qbean.getQuestionType().equals("2") || // mcmc
qbean.getQuestionType().equals("3") || // mc survey
qbean.getQuestionType().equals("4") || // tf
qbean.getQuestionType().equals("9") || // matching
qbean.getQuestionType().equals("8")) // Fill in the blank
doAnswerStatistics(qbean, itemScores);
if (qbean.getQuestionType().equals("5") || // essay
qbean.getQuestionType().equals("6") || // file upload
qbean.getQuestionType().equals("7")) // audio recording
doScoreStatistics(qbean, itemScores);
}
public void doAnswerStatistics(HistogramQuestionScoresBean qbean,
ArrayList scores)
{
if (scores.isEmpty())
{
qbean.setHistogramBars(new HistogramBarBean[0]);
qbean.setNumResponses(0);
qbean.setPercentCorrect("No responses");
return;
}
int numAnswers = 0;
ItemDataIfc item = ((ItemGradingData) scores.toArray()[0])
.getPublishedItem();
ArrayList text = item.getItemTextArraySorted();
ArrayList answers = null;
if (!qbean.getQuestionType().equals("9"))
{
ItemTextIfc firstText = (ItemTextIfc) text.toArray()[0];
answers = firstText.getAnswerArraySorted();
}
if (qbean.getQuestionType().equals("1"))
getTFMCScores(scores, qbean, answers);
else if (qbean.getQuestionType().equals("2"))
getFIBMCMCScores(scores, qbean, answers);
else if (qbean.getQuestionType().equals("3"))
getTFMCScores(scores, qbean, answers);
else if (qbean.getQuestionType().equals("4"))
getTFMCScores(scores, qbean, answers);
else if (qbean.getQuestionType().equals("8"))
getFIBMCMCScores(scores, qbean, answers);
else if (qbean.getQuestionType().equals("9"))
getMatchingScores(scores, qbean, text);
}
public void getFIBMCMCScores(ArrayList scores,
HistogramQuestionScoresBean qbean, ArrayList answers)
{
HashMap texts = new HashMap();
Iterator iter = answers.iterator();
HashMap results = new HashMap();
HashMap numStudentRespondedMap= new HashMap();
while (iter.hasNext())
{
AnswerIfc answer = (AnswerIfc) iter.next();
texts.put(answer.getId(), answer);
results.put(answer.getId(), new Integer(0));
}
iter = scores.iterator();
while (iter.hasNext())
{
ItemGradingData data = (ItemGradingData) iter.next();
AnswerIfc answer = data.getPublishedAnswer();
if (answer != null)
{
//log.info("Rachel: looking for " + answer.getId());
// found a response
Integer num = null;
// num is a counter
try {
// we found a response, now get existing count from the hashmap
num = (Integer) results.get(answer.getId());
} catch (Exception e) {
log.info("No results for " + answer.getId());
}
if (num == null)
num = new Integer(0);
ArrayList studentResponseList = (ArrayList)numStudentRespondedMap.get(data.getAssessmentGrading().getAssessmentGradingId());
if (studentResponseList==null) {
studentResponseList = new ArrayList();
}
studentResponseList.add(data);
numStudentRespondedMap.put(data.getAssessmentGrading().getAssessmentGradingId(), studentResponseList);
// we found a response, and got the existing num , now update one
if (qbean.getQuestionType().equals("8"))
{
// for fib we only count the number of correct responses
Float autoscore = data.getAutoScore();
if (!autoscore.equals(new Float(0))) {
results.put(answer.getId(), new Integer(num.intValue() + 1));
}
}
else {
// for mc, we count the number of all responses
results.put(answer.getId(), new Integer(num.intValue() + 1));
}
}
}
HistogramBarBean[] bars = new HistogramBarBean[results.keySet().size()];
int[] numarray = new int[results.keySet().size()];
iter = results.keySet().iterator();
int i = 0;
int responses = 0;
int correctresponses = 0;
while (iter.hasNext())
{
Long answerId = (Long) iter.next();
AnswerIfc answer = (AnswerIfc) texts.get(answerId);
int num = ((Integer) results.get(answerId)).intValue();
numarray[i] = num;
bars[i] = new HistogramBarBean();
bars[i].setLabel(answer.getText());
// this doens't not apply to fib , do not show checkmarks for FIB
if (!qbean.getQuestionType().equals("8"))
{
bars[i].setIsCorrect(answer.getIsCorrect());
}
if ((num>1)||(num==0))
{
bars[i].setNumStudentsText(num + " Responses");
}
else
{
bars[i].setNumStudentsText(num + " Response");
}
bars[i].setNumStudents(num);
i++;
}
responses = numStudentRespondedMap.size();
Iterator mapiter = numStudentRespondedMap.keySet().iterator();
while (mapiter.hasNext())
{
Long assessmentGradingId= (Long)mapiter.next();
ArrayList resultsForOneStudent = (ArrayList)numStudentRespondedMap.get(assessmentGradingId);
boolean hasIncorrect = false;
Iterator listiter = resultsForOneStudent.iterator();
while (listiter.hasNext())
{
ItemGradingData item = (ItemGradingData)listiter.next();
if (qbean.getQuestionType().equals("8"))
{
Float autoscore = item.getAutoScore();
if (autoscore.equals(new Float(0))) {
hasIncorrect = true;
break;
}
}
else if (qbean.getQuestionType().equals("2"))
{
// only answered choices are created in the ItemGradingData_T, so we need to check
// if # of checkboxes the student checked is == the number of correct answers
// otherwise if a student only checked one of the multiple correct answers,
// it would count as a correct response
try {
ArrayList itemTextArray = item.getPublishedItem().getItemTextArraySorted();
ArrayList answerArray = ((ItemTextIfc)itemTextArray.get(0)).getAnswerArraySorted();
int corranswers = 0;
Iterator answeriter = answerArray.iterator();
while (answeriter.hasNext()){
AnswerIfc answerchoice = (AnswerIfc) answeriter.next();
if (answerchoice.getIsCorrect().booleanValue()){
corranswers++;
}
}
if (resultsForOneStudent.size() != corranswers){
hasIncorrect = true;
break;
}
}
catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("error calculating mcmc question.");
}
// now check each answer in MCMC
AnswerIfc answer = item.getPublishedAnswer();
if (answer.getIsCorrect() == null || (!answer.getIsCorrect().booleanValue()))
{
hasIncorrect = true;
break;
}
}
}
if (!hasIncorrect) {
correctresponses = correctresponses + 1;
}
}
int[] heights = calColumnHeight(numarray);
for (i=0; i<bars.length; i++)
bars[i].setColumnHeight(new Integer(heights[i]).toString());
qbean.setHistogramBars(bars);
qbean.setNumResponses(responses);
if (responses > 0)
qbean.setPercentCorrect(new Integer((int)(((float) correctresponses/(float) responses) * 100)).toString());
}
public void getTFMCScores(ArrayList scores,
HistogramQuestionScoresBean qbean, ArrayList answers)
{
HashMap texts = new HashMap();
Iterator iter = answers.iterator();
HashMap results = new HashMap();
while (iter.hasNext())
{
AnswerIfc answer = (AnswerIfc) iter.next();
texts.put(answer.getId(), answer);
results.put(answer.getId(), new Integer(0));
}
iter = scores.iterator();
while (iter.hasNext())
{
ItemGradingData data = (ItemGradingData) iter.next();
AnswerIfc answer = data.getPublishedAnswer();
if (answer != null)
{
//log.info("Rachel: looking for " + answer.getId());
// found a response
Integer num = null;
// num is a counter
try {
// we found a response, now get existing count from the hashmap
num = (Integer) results.get(answer.getId());
} catch (Exception e) {
log.info("No results for " + answer.getId());
}
if (num == null)
num = new Integer(0);
// we found a response, and got the existing num , now update one
// check here for the other bug about non-autograded items having 1 even with no responses
results.put(answer.getId(), new Integer(num.intValue() + 1));
}
}
HistogramBarBean[] bars = new HistogramBarBean[results.keySet().size()];
int[] numarray = new int[results.keySet().size()];
iter = results.keySet().iterator();
int i = 0;
int responses = 0;
int correctresponses = 0;
while (iter.hasNext())
{
Long answerId = (Long) iter.next();
AnswerIfc answer = (AnswerIfc) texts.get(answerId);
int num = ((Integer) results.get(answerId)).intValue();
// set i to be the sequence, so that the answer choices will be in the right order on Statistics page , see Bug SAM-440
i=answer.getSequence().intValue()-1;
numarray[i] = num;
bars[i] = new HistogramBarBean();
bars[i].setLabel(answer.getText());
bars[i].setIsCorrect(answer.getIsCorrect());
if ((num>1)||(num==0))
{
bars[i].setNumStudentsText(num + " Responses");
}
else
{
bars[i].setNumStudentsText(num + " Response");
}
bars[i].setNumStudents(num);
responses += num;
if (answer.getIsCorrect() != null && answer.getIsCorrect().booleanValue())
correctresponses += num;
//i++;
}
int[] heights = calColumnHeight(numarray);
for (i=0; i<bars.length; i++)
bars[i].setColumnHeight(new Integer(heights[i]).toString());
qbean.setHistogramBars(bars);
qbean.setNumResponses(responses);
if (responses > 0)
qbean.setPercentCorrect(new Integer((int)(((float) correctresponses/(float) responses) * 100)).toString());
}
public void getMatchingScores(ArrayList scores,
HistogramQuestionScoresBean qbean, ArrayList labels)
{
HashMap texts = new HashMap();
Iterator iter = labels.iterator();
HashMap results = new HashMap();
HashMap numStudentRespondedMap= new HashMap();
while (iter.hasNext())
{
ItemTextIfc label = (ItemTextIfc) iter.next();
texts.put(label.getId(), label);
results.put(label.getId(), new Integer(0));
}
iter = scores.iterator();
while (iter.hasNext())
{
ItemGradingData data = (ItemGradingData) iter.next();
ItemTextIfc text = data.getPublishedItemText();
AnswerIfc answer = data.getPublishedAnswer();
if (answer.getIsCorrect() != null && answer.getIsCorrect().booleanValue())
{
Integer num = (Integer) results.get(text.getId());
if (num == null)
num = new Integer(0);
ArrayList studentResponseList = (ArrayList)numStudentRespondedMap.get(data.getAssessmentGrading().getAssessmentGradingId());
if (studentResponseList==null) {
studentResponseList = new ArrayList();
}
studentResponseList.add(data);
numStudentRespondedMap.put(data.getAssessmentGrading().getAssessmentGradingId(), studentResponseList);
results.put(text.getId(), new Integer(num.intValue() + 1));
}
}
HistogramBarBean[] bars = new HistogramBarBean[results.keySet().size()];
int[] numarray = new int[results.keySet().size()];
iter = results.keySet().iterator();
int i = 0;
int responses = 0;
int correctresponses = 0;
while (iter.hasNext())
{
Long textId = (Long) iter.next();
ItemTextIfc text = (ItemTextIfc) texts.get(textId);
int num = ((Integer) results.get(textId)).intValue();
numarray[i] = num;
bars[i] = new HistogramBarBean();
bars[i].setLabel(text.getText());
bars[i].setNumStudents(num);
if ((num>1)||(num==0))
{
bars[i].setNumStudentsText(num + " Correct Responses");
}
else
{
bars[i].setNumStudentsText(num + " Correct Response");
}
i++;
}
// now calculate responses and correctresponses
// correctresponses = # of students who got all answers correct,
//lydia: i need another map of maps for this . maybe need to modify above logic
responses = numStudentRespondedMap.size();
Iterator mapiter = numStudentRespondedMap.keySet().iterator();
while (mapiter.hasNext())
{
Long assessmentGradingId= (Long)mapiter.next();
ArrayList resultsForOneStudent = (ArrayList)numStudentRespondedMap.get(assessmentGradingId);
boolean hasIncorrect = false;
Iterator listiter = resultsForOneStudent.iterator();
// numStudentRespondedMap only stores correct answers, so now we need to
// check to see if # of rows in itemgradingdata_t == labels.size()
// otherwise if a student only answered one correct answer and
// skipped the rest, it would count as a correct response
while (listiter.hasNext())
{
ItemGradingData item = (ItemGradingData)listiter.next();
if (resultsForOneStudent.size()!= labels.size()){
hasIncorrect = true;
break;
}
}
if (!hasIncorrect) {
correctresponses = correctresponses + 1;
}
}
int[] heights = calColumnHeight(numarray);
for (i=0; i<bars.length; i++)
bars[i].setColumnHeight(new Integer(heights[i]).toString());
qbean.setHistogramBars(bars);
qbean.setNumResponses(responses);
if (responses > 0)
qbean.setPercentCorrect(new Integer((int)(((float) correctresponses/(float) responses) * 100)).toString());
}
public void doScoreStatistics(HistogramQuestionScoresBean qbean,
ArrayList scores)
{
// here scores contain ItemGradingData
Map assessmentMap = getAssessmentStatisticsMap(scores);
// test to see if it gets back empty map
if (assessmentMap.isEmpty())
{
qbean.setNumResponses(0);
}
try
{
BeanUtils.populate(qbean, assessmentMap);
// quartiles don't seem to be working, workaround
qbean.setQ1( (String) assessmentMap.get("q1"));
qbean.setQ2( (String) assessmentMap.get("q2"));
qbean.setQ3( (String) assessmentMap.get("q3"));
qbean.setQ4( (String) assessmentMap.get("q4"));
//qbean.setTotalScore( (String) assessmentMap.get("maxScore"));
HistogramBarBean[] bars =
new HistogramBarBean[qbean.getColumnHeight().length];
// SAK-1933: if there is no response, do not show bars at all
// do not check if assessmentMap is empty, because it's never empty.
if (scores.size() == 0) {
bars = new HistogramBarBean[0];
}
else {
for (int i=0; i<qbean.getColumnHeight().length; i++)
{
bars[i] = new HistogramBarBean();
bars[i].setColumnHeight
(new Integer(qbean.getColumnHeight()[i]).toString());
bars[i].setNumStudents(qbean.getNumStudentCollection()[i]);
if (qbean.getNumStudentCollection()[i]>1)
{
bars[i].setNumStudentsText(qbean.getNumStudentCollection()[i] +
" Responses");
}
else
{
bars[i].setNumStudentsText(qbean.getNumStudentCollection()[i] +
" Response");
}
// bars[i].setNumStudentsText(qbean.getNumStudentCollection()[i] +
// " Responses");
bars[i].setRangeInfo(qbean.getRangeCollection()[i]);
bars[i].setLabel(qbean.getRangeCollection()[i]);
}
}
qbean.setHistogramBars(bars);
} catch (Exception e) {
e.printStackTrace();
}
}
public Map getAssessmentStatisticsMap(ArrayList scoreList)
{
// this function is used to calculate stats for an entire assessment
// or for a non-autograded question
// depending on data's instanceof
Iterator iter = scoreList.iterator();
ArrayList floats = new ArrayList();
while (iter.hasNext())
{
Object data = iter.next();
if (data instanceof AssessmentGradingData) {
floats.add((Float)
((AssessmentGradingData) data).getFinalScore());
}
else
{
float autoScore = (float) 0.0;
if (((ItemGradingData) data).getAutoScore() != null)
autoScore = ((ItemGradingData) data).getAutoScore().floatValue();
float overrideScore = (float) 0.0;
if (((ItemGradingData) data).getOverrideScore() != null)
overrideScore =
((ItemGradingData) data).getOverrideScore().floatValue();
floats.add(new Float(autoScore + overrideScore));
}
}
if (floats.isEmpty())
floats.add(new Float(0.0));
Object[] array = floats.toArray();
Arrays.sort(array);
double[] scores = new double[array.length];
for (int i=0; i<array.length; i++)
scores[i] = ((Float) array[i]).doubleValue();
HashMap statMap = new HashMap();
double min = scores[0];
double max = scores[scores.length - 1];
double total = calTotal(scores);
double mean = calMean(scores, total);
int interval = 0;
interval = calInterval(scores, min, max);
int[] numStudents = calNumStudents(scores, min, max, interval);
statMap.put("maxScore", castingNum(max,2));
statMap.put("interval", new Integer(interval));
statMap.put("numResponses", new Integer(scoreList.size()));
// statMap.put("numResponses", new Integer(scores.length));
statMap.put("totalScore",castingNum(total,2));
statMap.put("mean", castingNum(mean,2));
statMap.put("median", castingNum(calMedian(scores),2));
statMap.put("mode", (new String(calMode(scores))));
statMap.put("numStudentCollection", numStudents);
statMap.put(
"rangeCollection", calRange(scores, numStudents, min, max, interval));
statMap.put("standDev", castingNum(calStandDev(scores, mean, total),2));
statMap.put("columnHeight", calColumnHeight(numStudents));
statMap.put("arrayLength", new Integer(numStudents.length));
statMap.put(
"range",
castingNum(scores[0],2) + " - " +
castingNum(scores[scores.length - 1],2));
statMap.put("q1", castingNum(calQuartiles(scores, 0.25),2));
statMap.put("q2", castingNum(calQuartiles(scores, 0.5),2));
statMap.put("q3", castingNum(calQuartiles(scores, 0.75),2));
statMap.put("q4", castingNum(max,2));
return statMap;
}
/*** What follows is Huong Nguyen's statistics code. ***/
/*** We love you Huong! --rmg ***/
/**
* Calculate the total score for all students
* @param scores array of scores
* @return the total
*/
private static double calTotal(double[] scores)
{
double total = 0;
for(int i = 0; i < scores.length; i++)
{
total = total + scores[i];
}
return total;
}
/**
* Calculate mean.
*
* @param scores array of scores
* @param total the total of all scores
*
* @return mean
*/
private static double calMean(double[] scores, double total)
{
return total / scores.length;
}
/**
* Calculate median.
*
* @param scores array of scores
*
* @return median
*/
private static double calMedian(double[] scores)
{
double median;
if(((scores.length) % 2) == 0)
{
median =
(scores[(scores.length / 2)] + scores[(scores.length / 2) - 1]) / 2;
}
else
{
median = scores[(scores.length - 1) / 2];
}
return median;
}
/**
* Calculate mode
*
* @param scores array of scores
*
* @return mode
*/
private static String calMode(double[] scores)
{
String max = ", " + scores[0];
String temp = ", " + scores[0];
int nmax = 1;
int ntemp = 1;
String scoreString;
for(int i = 1; i < scores.length; i++)
{
if(Math.ceil(scores[i]) == Math.floor(scores[i]))
{
scoreString = "" + (int) scores[i];
}
else
{
scoreString = "" + scores[i];
}
if((", " + scoreString).equals(temp))
{
ntemp++;
if(nmax < ntemp)
{
max = temp;
nmax = ntemp;
}
else if(nmax == ntemp)
{
max = max + temp;
nmax = ntemp;
}
else
{
// nmax>ntemp do nothing
}
}
else
{
temp = ", " + scoreString;
ntemp = 1;
}
}
max = max.substring(2, max.length());
return max;
}
/**
* Calculate standard Deviation
*
* @param scores array of scores
* @param mean the mean
* @param total the total
*
* @return the standard deviation
*/
private static double calStandDev(double[] scores, double mean, double total)
{
for(int i = 0; i < scores.length; i++)
{
total = total + ((scores[i] - mean) * (scores[i] - mean));
}
return Math.sqrt(total / scores.length);
}
/**
* Calculate the interval to use for histograms.
*
* @param scores array of scores
* @param min the minimum score
* @param max the maximum score
*
* @return the interval
*/
private static int calInterval(double[] scores, double min, double max)
{
int interval;
if((max - min) < 10)
{
interval = 1;
}
else
{
interval = (int) Math.ceil((max - min) / 10);
}
return interval;
}
/**
* Calculate the number for each answer.
*
* @param answers array of answers
*
*
* @return array of number giving each answer.
*/
private static int[] calNum(String[] answers, String[] choices, String type)
{
int[] num = new int[choices.length];
for(int i = 0; i < answers.length; i++)
{
for(int j = 0; j < choices.length; j++)
{
if(type.equals("Multiple Correct Answer"))
{
// TODO: using Tokenizer because split() doesn't seem to work.
StringTokenizer st = new StringTokenizer(answers[i], "|");
while(st.hasMoreTokens())
{
String nt = st.nextToken();
if((nt.trim()).equals(choices[j].trim()))
{
num[j] = num[j] + 1;
}
}
/*
String[] answerArray = answers[i].split("|");
for(int k=0;i<answerArray.length ; k++) {
if ( (answerArray[k].trim()).equals(choices[j].trim())) {
num[j] = num[j] + 1;
}
}
*/
}
else
{
if(answers[i].equals(choices[j]))
{
num[j] = num[j] + 1;
}
}
}
}
return num;
}
/**
* Calculate the number correct answer
*
* @param answers array of answers
* @param correct the correct answer
*
* @return the number correct
*/
private int calCorrect(String[] answers, String correct)
{
int cal = 0;
for(int i = 0; i < answers.length; i++)
{
if(answers[i].equals(correct))
{
cal++;
}
}
return cal;
}
/**
* Calculate the number of students per interval for histograms.
*
* @param scores array of scores
* @param min the minimum score
* @param max the maximum score
* @param interval the interval
*
* @return number of students per interval
*/
private static int[] calNumStudents(
double[] scores, double min, double max, int interval)
{
if(min > max)
{
log.info("max(" + max + ") <min(" + min + ")");
max = min;
}
int[] numStudents = new int[(int) Math.ceil((max - min) / interval)];
// this handles a case where there are no num students, treats as if
// a single value of 0
if(numStudents.length == 0)
{
numStudents = new int[1];
numStudents[0] = 0;
}
for(int i = 0; i < scores.length; i++)
{
if(scores[i] <= (min + interval))
{
numStudents[0]++;
}
else
{
for(int j = 1; j < (numStudents.length); j++)
{
if(
((scores[i] > (min + (j * interval))) &&
(scores[i] <= (min + ((j + 1) * interval)))))
{
numStudents[j]++;
break;
}
}
}
}
return numStudents;
}
/**
* Get range text for each interval
*
* @param answers array of ansers
*
*
* @return array of range text strings for each interval
*/
private static String[] calRange(String[] answers, String[] choices)
{
String[] range = new String[choices.length];
int current = 0;
// gracefully handle a condition where there are no answers
if(answers.length == 0)
{
for(int i = 0; i < range.length; i++)
{
range[i] = "unknown";
}
return range;
}
choices[0] = answers[0];
for(int a = 1; a < answers.length; a++)
{
if(! (answers[a].equals(choices[current])))
{
current++;
choices[current] = answers[a];
}
}
return range;
}
/**
* Calculate range strings for each interval.
*
* @param scores array of scores
* @param numStudents number of students for each interval
* @param min the minimium
* @param max the maximum
* @param interval the number of intervals
*
* @return array of range strings for each interval.
*/
private static String[] calRange(
double[] scores, int[] numStudents, double min, double max, int interval)
{
String[] ranges = new String[numStudents.length];
ranges[0] = (int) min + " - " + (int) (min + interval);
int i = 1;
while(i < ranges.length)
{
if((((i + 1) * interval) + min) < max)
{
ranges[i] =
">" + (int) ((i * interval) + min) + " - " +
(int) (((i + 1) * interval) + min);
}
else
{
ranges[i] = ">" + (int) ((i * interval) + min) + " - " + (int) max;
}
i++;
}
return ranges;
}
/**
* Calculate the height of each histogram column.
*
* @param numStudents the number of students for each column
*
* @return array of column heights
*/
private static int[] calColumnHeight(int[] numStudents)
{
int length = numStudents.length;
int[] temp = new int[length];
int[] height = new int[length];
int i = 0;
while(i < length)
{
temp[i] = numStudents[i];
i++;
}
Arrays.sort(temp);
int num = 1;
if((temp.length > 0) && (temp[temp.length - 1] > 0))
{
num = (int) (600 / temp[temp.length - 1]);
int j = 0;
while(j < length)
{
height[j] = num * numStudents[j];
j++;
}
}
return height;
}
/**
* Calculate quartiles.
*
* @param scores score array
* @param r the quartile rank
*
* @return the quartile
*/
private static double calQuartiles(double[] scores, double r)
{
int k;
double f;
k = (int) (Math.floor((r * (scores.length - 1)) + 1));
f = (r * (scores.length - 1)) - Math.floor(r * (scores.length - 1));
// special handling if insufficient data to calculate
if(k < 2)
{
if(scores != null)
{
return scores[0];
}
else
{
return 0;
}
}
return scores[k - 1] + (f * (scores[k] - scores[k - 1]));
}
/**
* DOCUMENTATION PENDING
*
* @param n DOCUMENTATION PENDING
*
* @return DOCUMENTATION PENDING
*/
private String castingNum(double number,int decimal)
{
int indexOfDec=0;
String n;
int index;
if(Math.ceil(number) == Math.floor(number))
{
return ("" + (int) number);
}
else
{
n=""+number;
indexOfDec=n.indexOf(".");
index=indexOfDec+decimal+1;
//log.info("NUMBER : "+n);
//log.info("NUMBER LENGTH : "+n.length());
if(n.length()>index)
{
return n.substring(0,index);
}
else{
return ""+number;
}
}
}
}
| true | true | public boolean histogramScores(
String publishedId, HistogramScoresBean bean, TotalScoresBean totalBean)
{
try {
String assessmentName = "";
// Get all submissions, or just the last?
String which = cu.lookupParam("allSubmissions");
//log.info("Rachel: allSubmissions = " + which);
if (which == null)
which = "false";
bean.setAllSubmissions(which.equals("true")?true:false);
bean.setItemId(cu.lookupParam("itemId"));
bean.setHasNav(cu.lookupParam("hasNav"));
GradingService delegate = new GradingService();
ArrayList scores = delegate.getTotalScores(publishedId, which);
HashMap itemscores = delegate.getItemScores(new Long(publishedId),
new Long(0), which);
//log.info("ItemScores size = " + itemscores.keySet().size());
bean.setPublishedId(publishedId);
Iterator iter = scores.iterator();
//log.info("Has this many agents: " + scores.size());
if (!iter.hasNext())
return false;
Object next = iter.next();
AssessmentGradingData data = (AssessmentGradingData) next;
if (data.getPublishedAssessment() != null)
{
assessmentName = data.getPublishedAssessment().getTitle();
log.info("ASSESSMENT NAME= " + assessmentName);
// if section set is null, initialize it - daisyf , 01/31/05
PublishedAssessmentData pub = (PublishedAssessmentData)data.getPublishedAssessment();
HashSet sectionSet = PersistenceService.getInstance().
getPublishedAssessmentFacadeQueries().getSectionSetForAssessment(pub);
data.getPublishedAssessment().setSectionSet(sectionSet);
ArrayList parts =
data.getPublishedAssessment().getSectionArraySorted();
ArrayList info = new ArrayList();
Iterator piter = parts.iterator();
int secseq = 1;
double totalpossible = 0;
boolean hasRandompart = false;
boolean isRandompart = false;
while (piter.hasNext()) {
SectionDataIfc section = (SectionDataIfc) piter.next();
String authortype = section.getSectionMetaDataByLabel(SectionDataIfc.AUTHOR_TYPE);
if (SectionDataIfc.RANDOM_DRAW_FROM_QUESTIONPOOL.equals(authortype)){
hasRandompart = true;
isRandompart = true;
}
else {
isRandompart = false;
}
if (section.getSequence() == null)
section.setSequence(new Integer(secseq++));
String title = "Part " + section.getSequence().toString();
title += ", Question ";
ArrayList itemset = section.getItemArraySortedForGrading();
int seq = 1;
Iterator iter2 = itemset.iterator();
while (iter2.hasNext())
{
HistogramQuestionScoresBean qbean =
new HistogramQuestionScoresBean();
// if this part is a randompart , then set randompart = true
qbean.setRandomType(isRandompart);
ItemDataIfc item = (ItemDataIfc) iter2.next();
String type = delegate.getTextForId(item.getTypeId());
if (item.getSequence() == null)
item.setSequence(new Integer(seq++));
qbean.setTitle(title + item.getSequence().toString() +
" (" + type + ")");
qbean.setQuestionText(item.getText());
qbean.setQuestionType(item.getTypeId().toString());
//totalpossible = totalpossible + item.getScore().doubleValue();
ArrayList responses = null;
determineResults(qbean, (ArrayList) itemscores.get
(item.getItemId()));
qbean.setTotalScore(item.getScore().toString());
info.add(qbean);
}
totalpossible = data.getPublishedAssessment().getTotalScore().doubleValue();
}
bean.setInfo(info);
bean.setRandomType(hasRandompart);
// here scores contain AssessmentGradingData
Map assessmentMap = getAssessmentStatisticsMap(scores);
// test to see if it gets back empty map
if (assessmentMap.isEmpty())
{
bean.setNumResponses(0);
}
try
{
BeanUtils.populate(bean, assessmentMap);
// quartiles don't seem to be working, workaround
bean.setQ1( (String) assessmentMap.get("q1"));
bean.setQ2( (String) assessmentMap.get("q2"));
bean.setQ3( (String) assessmentMap.get("q3"));
bean.setQ4( (String) assessmentMap.get("q4"));
bean.setTotalScore( (String) assessmentMap.get("totalScore"));
bean.setTotalPossibleScore(new Double(totalpossible).toString());
HistogramBarBean[] bars =
new HistogramBarBean[bean.getColumnHeight().length];
for (int i=0; i<bean.getColumnHeight().length; i++)
{
bars[i] = new HistogramBarBean();
bars[i].setColumnHeight
(new Integer(bean.getColumnHeight()[i]).toString());
bars[i].setNumStudents(bean.getNumStudentCollection()[i]);
bars[i].setRangeInfo(bean.getRangeCollection()[i]);
//log.info("Set bar " + i + ": " + bean.getColumnHeight()[i] + ", " + bean.getNumStudentCollection()[i] + ", " + bean.getRangeCollection()[i]);
}
bean.setHistogramBars(bars);
///////////////////////////////////////////////////////////
// START DEBUGGING
log.info("TESTING ASSESSMENT MAP");
log.info("assessmentMap: =>");
log.info(assessmentMap);
log.info("--------------------------------------------");
log.info("TESTING TOTALS HISTOGRAM FORM");
log.info(
"HistogramScoresForm Form: =>\n" + "bean.getMean()=" +
bean.getMean() + "\n" +
"bean.getColumnHeight()[0] (first elem)=" +
bean.getColumnHeight()[0] + "\n" + "bean.getInterval()=" +
bean.getInterval() + "\n" + "bean.getLowerQuartile()=" +
bean.getLowerQuartile() + "\n" + "bean.getMaxScore()=" +
bean.getMaxScore() + "\n" + "bean.getMean()=" + bean.getMean() +
"\n" + "bean.getMedian()=" + bean.getMedian() + "\n" +
"bean.getNumResponses()=" + bean.getNumResponses() + "\n" +
"bean.getNumStudentCollection()=" +
bean.getNumStudentCollection() +
"\n" + "bean.getQ1()=" + bean.getQ1() + "\n" + "bean.getQ2()=" +
bean.getQ2() + "\n" + "bean.getQ3()=" + bean.getQ3() + "\n" +
"bean.getQ4()=" + bean.getQ4());
log.info("--------------------------------------------");
// END DEBUGGING CODE
///////////////////////////////////////////////////////////
}
catch (Exception e)
{
log.info("unable to populate bean" + e);
}
bean.setAssessmentName(assessmentName);
}
else
{
return false;
}
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
return true;
}
| public boolean histogramScores(
String publishedId, HistogramScoresBean bean, TotalScoresBean totalBean)
{
try {
String assessmentName = "";
// Get all submissions, or just the last?
String which = cu.lookupParam("allSubmissions");
//log.info("Rachel: allSubmissions = " + which);
if (which == null)
which = "false";
bean.setAllSubmissions(which.equals("true")?true:false);
bean.setItemId(cu.lookupParam("itemId"));
bean.setHasNav(cu.lookupParam("hasNav"));
GradingService delegate = new GradingService();
ArrayList scores = delegate.getTotalScores(publishedId, which);
HashMap itemscores = delegate.getItemScores(new Long(publishedId),
new Long(0), which);
//log.info("ItemScores size = " + itemscores.keySet().size());
bean.setPublishedId(publishedId);
Iterator iter = scores.iterator();
//log.info("Has this many agents: " + scores.size());
if (!iter.hasNext())
return false;
Object next = iter.next();
AssessmentGradingData data = (AssessmentGradingData) next;
if (data.getPublishedAssessment() != null)
{
assessmentName = data.getPublishedAssessment().getTitle();
log.info("ASSESSMENT NAME= " + assessmentName);
// if section set is null, initialize it - daisyf , 01/31/05
PublishedAssessmentData pub = (PublishedAssessmentData)data.getPublishedAssessment();
HashSet sectionSet = PersistenceService.getInstance().
getPublishedAssessmentFacadeQueries().getSectionSetForAssessment(pub);
data.getPublishedAssessment().setSectionSet(sectionSet);
ArrayList parts =
data.getPublishedAssessment().getSectionArraySorted();
ArrayList info = new ArrayList();
Iterator piter = parts.iterator();
int secseq = 1;
double totalpossible = 0;
boolean hasRandompart = false;
boolean isRandompart = false;
while (piter.hasNext()) {
SectionDataIfc section = (SectionDataIfc) piter.next();
String authortype = section.getSectionMetaDataByLabel(SectionDataIfc.AUTHOR_TYPE);
if (SectionDataIfc.RANDOM_DRAW_FROM_QUESTIONPOOL.equals(new Integer(authortype))){
hasRandompart = true;
isRandompart = true;
}
else {
isRandompart = false;
}
if (section.getSequence() == null)
section.setSequence(new Integer(secseq++));
String title = "Part " + section.getSequence().toString();
title += ", Question ";
ArrayList itemset = section.getItemArraySortedForGrading();
int seq = 1;
Iterator iter2 = itemset.iterator();
while (iter2.hasNext())
{
HistogramQuestionScoresBean qbean =
new HistogramQuestionScoresBean();
// if this part is a randompart , then set randompart = true
qbean.setRandomType(isRandompart);
ItemDataIfc item = (ItemDataIfc) iter2.next();
String type = delegate.getTextForId(item.getTypeId());
if (item.getSequence() == null)
item.setSequence(new Integer(seq++));
qbean.setTitle(title + item.getSequence().toString() +
" (" + type + ")");
qbean.setQuestionText(item.getText());
qbean.setQuestionType(item.getTypeId().toString());
//totalpossible = totalpossible + item.getScore().doubleValue();
ArrayList responses = null;
determineResults(qbean, (ArrayList) itemscores.get
(item.getItemId()));
qbean.setTotalScore(item.getScore().toString());
info.add(qbean);
}
totalpossible = data.getPublishedAssessment().getTotalScore().doubleValue();
}
bean.setInfo(info);
bean.setRandomType(hasRandompart);
// here scores contain AssessmentGradingData
Map assessmentMap = getAssessmentStatisticsMap(scores);
// test to see if it gets back empty map
if (assessmentMap.isEmpty())
{
bean.setNumResponses(0);
}
try
{
BeanUtils.populate(bean, assessmentMap);
// quartiles don't seem to be working, workaround
bean.setQ1( (String) assessmentMap.get("q1"));
bean.setQ2( (String) assessmentMap.get("q2"));
bean.setQ3( (String) assessmentMap.get("q3"));
bean.setQ4( (String) assessmentMap.get("q4"));
bean.setTotalScore( (String) assessmentMap.get("totalScore"));
bean.setTotalPossibleScore(new Double(totalpossible).toString());
HistogramBarBean[] bars =
new HistogramBarBean[bean.getColumnHeight().length];
for (int i=0; i<bean.getColumnHeight().length; i++)
{
bars[i] = new HistogramBarBean();
bars[i].setColumnHeight
(new Integer(bean.getColumnHeight()[i]).toString());
bars[i].setNumStudents(bean.getNumStudentCollection()[i]);
bars[i].setRangeInfo(bean.getRangeCollection()[i]);
//log.info("Set bar " + i + ": " + bean.getColumnHeight()[i] + ", " + bean.getNumStudentCollection()[i] + ", " + bean.getRangeCollection()[i]);
}
bean.setHistogramBars(bars);
///////////////////////////////////////////////////////////
// START DEBUGGING
log.info("TESTING ASSESSMENT MAP");
log.info("assessmentMap: =>");
log.info(assessmentMap);
log.info("--------------------------------------------");
log.info("TESTING TOTALS HISTOGRAM FORM");
log.info(
"HistogramScoresForm Form: =>\n" + "bean.getMean()=" +
bean.getMean() + "\n" +
"bean.getColumnHeight()[0] (first elem)=" +
bean.getColumnHeight()[0] + "\n" + "bean.getInterval()=" +
bean.getInterval() + "\n" + "bean.getLowerQuartile()=" +
bean.getLowerQuartile() + "\n" + "bean.getMaxScore()=" +
bean.getMaxScore() + "\n" + "bean.getMean()=" + bean.getMean() +
"\n" + "bean.getMedian()=" + bean.getMedian() + "\n" +
"bean.getNumResponses()=" + bean.getNumResponses() + "\n" +
"bean.getNumStudentCollection()=" +
bean.getNumStudentCollection() +
"\n" + "bean.getQ1()=" + bean.getQ1() + "\n" + "bean.getQ2()=" +
bean.getQ2() + "\n" + "bean.getQ3()=" + bean.getQ3() + "\n" +
"bean.getQ4()=" + bean.getQ4());
log.info("--------------------------------------------");
// END DEBUGGING CODE
///////////////////////////////////////////////////////////
}
catch (Exception e)
{
log.info("unable to populate bean" + e);
}
bean.setAssessmentName(assessmentName);
}
else
{
return false;
}
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
return true;
}
|
diff --git a/framework/src/play/db/Evolutions.java b/framework/src/play/db/Evolutions.java
index 2b3b0831..b5c04ce0 100644
--- a/framework/src/play/db/Evolutions.java
+++ b/framework/src/play/db/Evolutions.java
@@ -1,605 +1,607 @@
package play.db;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.lang.StringUtils;
import play.Logger;
import play.Play;
import play.PlayPlugin;
import play.classloading.ApplicationClasses;
import play.classloading.ApplicationClassloader;
import play.exceptions.PlayException;
import play.exceptions.UnexpectedException;
import play.libs.Codec;
import play.libs.IO;
import play.mvc.Http.Request;
import play.mvc.Http.Response;
import play.mvc.results.Redirect;
import play.vfs.VirtualFile;
import java.io.File;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Stack;
import javax.sql.DataSource;
/**
* Handles migration of data.
*
* Does only support the default DBConfig
*/
public class Evolutions extends PlayPlugin {
/**
* Indicates if evolutions is disabled in application.conf ("evolutions.enabled" property)
*/
private boolean disabled = false;
protected static DataSource getDatasource() {
DBConfig dbConfig = DB.getDBConfig(DBConfig.defaultDbConfigName, true);
if (dbConfig==null) {
return null;
}
return dbConfig.getDatasource();
}
public static void main(String[] args) throws SQLException {
/** Check that evolutions are enabled **/
if (!evolutionsDirectory.exists()) {
System.out.println("~ Evolutions are not enabled. Create a db/evolutions directory to create your first 1.sql evolution script.");
System.out.println("~");
return;
}
/** Start the DB plugin **/
Play.id = System.getProperty("play.id");
Play.applicationPath = new File(System.getProperty("application.path"));
Play.guessFrameworkPath();
Play.readConfiguration();
Play.javaPath = new ArrayList<VirtualFile>();
Play.classes = new ApplicationClasses();
Play.classloader = new ApplicationClassloader();
Logger.init();
Logger.setUp("ERROR");
new DBPlugin().onApplicationStart();
/** Connected **/
System.out.println("~ Connected to " + getDatasource().getConnection().getMetaData().getURL());
/** Sumary **/
Evolution database = listDatabaseEvolutions().peek();
Evolution application = listApplicationEvolutions().peek();
if ("resolve".equals(System.getProperty("mode"))) {
try {
checkEvolutionsState();
System.out.println("~");
System.out.println("~ Nothing to resolve...");
System.out.println("~");
return;
} catch (InconsistentDatabase e) {
resolve(e.revision);
System.out.println("~");
System.out.println("~ Revision " + e.revision + " has been resolved;");
System.out.println("~");
} catch (InvalidDatabaseRevision e) {
// see later
}
}
/** Check inconsistency **/
try {
checkEvolutionsState();
} catch (InconsistentDatabase e) {
System.out.println("~");
System.out.println("~ Your database is in an inconsistent state!");
System.out.println("~");
System.out.println("~ While applying this script part:");
System.out.println("");
System.out.println(e.evolutionScript);
System.out.println("");
System.out.println("~ The following error occured:");
System.out.println("");
System.out.println(e.error);
System.out.println("");
System.out.println("~ Please correct it manually, and mark it resolved by running `play evolutions:resolve`");
System.out.println("~");
return;
} catch (InvalidDatabaseRevision e) {
// see later
}
System.out.print("~ Application revision is " + application.revision + " [" + application.hash.substring(0, 7) + "]");
System.out.println(" and Database revision is " + database.revision + " [" + database.hash.substring(0, 7) + "]");
System.out.println("~");
/** Evolution script **/
List<Evolution> evolutions = getEvolutionScript();
if (evolutions.isEmpty()) {
System.out.println("~ Your database is up to date");
System.out.println("~");
} else {
if ("apply".equals(System.getProperty("mode"))) {
System.out.println("~ Applying evolutions:");
System.out.println("");
System.out.println("# ------------------------------------------------------------------------------");
System.out.println("");
System.out.println(toHumanReadableScript(evolutions));
System.out.println("");
System.out.println("# ------------------------------------------------------------------------------");
System.out.println("");
if (applyScript(true)) {
System.out.println("~");
System.out.println("~ Evolutions script successfully applied!");
System.out.println("~");
} else {
System.out.println("~");
System.out.println("~ Can't apply evolutions...");
System.out.println("~");
+ System.exit(-1);
}
} else if ("markApplied".equals(System.getProperty("mode"))) {
if (applyScript(false)) {
System.out.println("~ Evolutions script marked as applied!");
System.out.println("~");
} else {
System.out.println("~ Can't apply evolutions...");
System.out.println("~");
+ System.exit(-1);
}
} else {
System.out.println("~ Your database needs evolutions!");
System.out.println("");
System.out.println("# ------------------------------------------------------------------------------");
System.out.println("");
System.out.println(toHumanReadableScript(evolutions));
System.out.println("");
System.out.println("# ------------------------------------------------------------------------------");
System.out.println("");
System.out.println("~ Run `play evolutions:apply` to automatically apply this script to the database");
System.out.println("~ or apply it yourself and mark it done using `play evolutions:markApplied`");
System.out.println("~");
}
}
}
static File evolutionsDirectory = Play.getFile("db/evolutions");
@Override
public boolean rawInvocation(Request request, Response response) throws Exception {
// Mark an evolution as resolved
if (Play.mode.isDev() && request.method.equals("POST") && request.url.matches("^/@evolutions/force/[0-9]+$")) {
int revision = Integer.parseInt(request.url.substring(request.url.lastIndexOf("/") + 1));
resolve(revision);
new Redirect("/").apply(request, response);
return true;
}
// Apply the current evolution script
if (Play.mode.isDev() && request.method.equals("POST") && request.url.equals("/@evolutions/apply")) {
applyScript(true);
new Redirect("/").apply(request, response);
return true;
}
return super.rawInvocation(request, response);
}
@Override
public void beforeInvocation() {
if(disabled || Play.mode.isProd()) {
return;
}
try {
checkEvolutionsState();
} catch (InvalidDatabaseRevision e) {
if ("mem".equals(Play.configuration.getProperty("db")) && listDatabaseEvolutions().peek().revision == 0) {
Logger.info("Automatically applying evolutions in in-memory database");
applyScript(true);
} else {
throw e;
}
}
}
@Override
public void onApplicationStart() {
disabled = "false".equals(Play.configuration.getProperty("evolutions.enabled", "true"));
if (! disabled && Play.mode.isProd()) {
try {
checkEvolutionsState();
} catch (InvalidDatabaseRevision e) {
Logger.warn("");
Logger.warn("Your database is not up to date.");
Logger.warn("Use `play evolutions` command to manage database evolutions.");
throw e;
}
}
}
public static synchronized void resolve(int revision) {
try {
execute("update play_evolutions set state = 'applied' where state = 'applying_up' and id = " + revision);
execute("delete from play_evolutions where state = 'applying_down' and id = " + revision);
} catch (Exception e) {
throw new UnexpectedException(e);
}
}
public static synchronized boolean applyScript(boolean runScript) {
try {
Connection connection = getNewConnection();
int applying = -1;
try {
for (Evolution evolution : getEvolutionScript()) {
applying = evolution.revision;
// Insert into logs
if (evolution.applyUp) {
PreparedStatement ps = connection.prepareStatement("insert into play_evolutions values(?, ?, ?, ?, ?, ?, ?)");
ps.setInt(1, evolution.revision);
ps.setString(2, evolution.hash);
ps.setDate(3, new Date(System.currentTimeMillis()));
ps.setString(4, evolution.sql_up);
ps.setString(5, evolution.sql_down);
ps.setString(6, "applying_up");
ps.setString(7, "");
ps.execute();
} else {
execute("update play_evolutions set state = 'applying_down' where id = " + evolution.revision);
}
// Execute script
if (runScript) {
for (CharSequence sql : new SQLSplitter((evolution.applyUp ? evolution.sql_up : evolution.sql_down))) {
final String s = sql.toString().trim();
if (StringUtils.isEmpty(s)) {
continue;
}
execute(s);
}
}
// Insert into logs
if (evolution.applyUp) {
execute("update play_evolutions set state = 'applied' where id = " + evolution.revision);
} else {
execute("delete from play_evolutions where id = " + evolution.revision);
}
}
return true;
} catch (Exception e) {
String message = e.getMessage();
if (e instanceof SQLException) {
SQLException ex = (SQLException) e;
message += " [ERROR:" + ex.getErrorCode() + ", SQLSTATE:" + ex.getSQLState() + "]";
}
PreparedStatement ps = connection.prepareStatement("update play_evolutions set last_problem = ? where id = ?");
ps.setString(1, message);
ps.setInt(2, applying);
ps.execute();
closeConnection(connection);
Logger.error(e, "Can't apply evolution");
return false;
}
} catch (Exception e) {
throw new UnexpectedException(e);
}
}
public static String toHumanReadableScript(List<Evolution> evolutionScript) {
// Construct the script
StringBuilder sql = new StringBuilder();
boolean containsDown = false;
for (Evolution evolution : evolutionScript) {
if (!evolution.applyUp) {
containsDown = true;
}
sql.append("# --- Rev:").append(evolution.revision).append(",").append(evolution.applyUp ? "Ups" : "Downs").append(" - ").append(evolution.hash.substring(0, 7)).append("\n");
sql.append("\n");
sql.append(evolution.applyUp ? evolution.sql_up : evolution.sql_down);
sql.append("\n\n");
}
if (containsDown) {
sql.insert(0, "# !!! WARNING! This script contains DOWNS evolutions that are likely destructives\n\n");
}
return sql.toString().trim();
}
public synchronized static void checkEvolutionsState() {
if (getDatasource() != null && evolutionsDirectory.exists()) {
List<Evolution> evolutionScript = getEvolutionScript();
Connection connection = null;
try {
connection = getNewConnection();
ResultSet rs = connection.createStatement().executeQuery("select id, hash, apply_script, revert_script, state, last_problem from play_evolutions where state like 'applying_%'");
if (rs.next()) {
int revision = rs.getInt("id");
String state = rs.getString("state");
String hash = rs.getString("hash").substring(0, 7);
String script = "";
if (state.equals("applying_up")) {
script = rs.getString("apply_script");
} else {
script = rs.getString("revert_script");
}
script = "# --- Rev:" + revision + "," + (state.equals("applying_up") ? "Ups" : "Downs") + " - " + hash + "\n\n" + script;
String error = rs.getString("last_problem");
throw new InconsistentDatabase(script, error, revision);
}
} catch (SQLException e) {
throw new UnexpectedException(e);
} finally {
closeConnection(connection);
}
if (!evolutionScript.isEmpty()) {
throw new InvalidDatabaseRevision(toHumanReadableScript(evolutionScript));
}
}
}
public synchronized static List<Evolution> getEvolutionScript() {
Stack<Evolution> app = listApplicationEvolutions();
Stack<Evolution> db = listDatabaseEvolutions();
List<Evolution> downs = new ArrayList<Evolution>();
List<Evolution> ups = new ArrayList<Evolution>();
// Apply non conflicting evolutions (ups and downs)
while (db.peek().revision != app.peek().revision) {
if (db.peek().revision > app.peek().revision) {
downs.add(db.pop());
} else {
ups.add(app.pop());
}
}
// Revert conflicting to fork node
while (db.peek().revision == app.peek().revision && !(db.peek().hash.equals(app.peek().hash))) {
downs.add(db.pop());
ups.add(app.pop());
}
// Ups need to be applied earlier first
Collections.reverse(ups);
List<Evolution> script = new ArrayList<Evolution>();
script.addAll(downs);
script.addAll(ups);
return script;
}
public synchronized static Stack<Evolution> listApplicationEvolutions() {
Stack<Evolution> evolutions = new Stack<Evolution>();
evolutions.add(new Evolution(0, "", "", true));
if (evolutionsDirectory.exists()) {
for (File evolution : evolutionsDirectory.listFiles()) {
if (evolution.getName().matches("^[0-9]+[.]sql$")) {
if (Logger.isTraceEnabled()) {
Logger.trace("Loading evolution %s", evolution);
}
int version = Integer.parseInt(evolution.getName().substring(0, evolution.getName().indexOf(".")));
String sql = IO.readContentAsString(evolution);
StringBuffer sql_up = new StringBuffer();
StringBuffer sql_down = new StringBuffer();
StringBuffer current = new StringBuffer();
for (String line : sql.split("\r?\n")) {
if (line.trim().matches("^#.*[!]Ups")) {
current = sql_up;
} else if (line.trim().matches("^#.*[!]Downs")) {
current = sql_down;
} else if (line.trim().startsWith("#")) {
// skip
} else if (!StringUtils.isEmpty(line.trim())) {
current.append(line).append("\n");
}
}
evolutions.add(new Evolution(version, sql_up.toString(), sql_down.toString(), true));
}
}
Collections.sort(evolutions);
}
return evolutions;
}
public synchronized static Stack<Evolution> listDatabaseEvolutions() {
Stack<Evolution> evolutions = new Stack<Evolution>();
evolutions.add(new Evolution(0, "", "", false));
Connection connection = null;
try {
connection = getNewConnection();
String tableName = "play_evolutions";
boolean tableExists = true;
ResultSet rs = connection.getMetaData().getTables(null, null, tableName, null);
if (!rs.next()) {
// Table in lowercase does not exist
// oracle gives table names in upper case
tableName = tableName.toUpperCase();
Logger.trace("Checking " + tableName);
rs.close();
rs = connection.getMetaData().getTables(null, null, tableName, null);
// Does it exist?
if (!rs.next() ) {
// did not find it in uppercase either
tableExists = false;
}
}
// Do we have a
if (tableExists) {
ResultSet databaseEvolutions = connection.createStatement().executeQuery("select id, hash, apply_script, revert_script from play_evolutions");
while (databaseEvolutions.next()) {
Evolution evolution = new Evolution(databaseEvolutions.getInt(1), databaseEvolutions.getString(3), databaseEvolutions.getString(4), false);
evolutions.add(evolution);
}
} else {
// If you are having problems with the default datatype text (clob for Oracle), you can
// specify your own datatype using the 'evolution.PLAY_EVOLUTIONS.textType'-property
String textDataType = Play.configuration.getProperty("evolution.PLAY_EVOLUTIONS.textType");
if (textDataType == null) {
if (isOracleDialectInUse()) {
textDataType = "clob";
} else {
textDataType = "text";
}
}
execute("create table play_evolutions (id int not null primary key, hash varchar(255) not null, applied_at timestamp not null, apply_script " + textDataType + ", revert_script " + textDataType + ", state varchar(255), last_problem " + textDataType + ")");
}
} catch (SQLException e) {
Logger.error(e, "SQL error while checking play evolutions");
} finally {
closeConnection(connection);
}
Collections.sort(evolutions);
return evolutions;
}
private synchronized static boolean isOracleDialectInUse() {
boolean isOracle = false;
String jpaDialect = Play.configuration.getProperty("jpa.dialect");
if (jpaDialect != null) {
try {
Class<?> dialectClass = Play.classloader.loadClass(jpaDialect);
// Oracle 8i dialect is the base class for oracle dialects (at least for now)
isOracle = org.hibernate.dialect.Oracle8iDialect.class.isAssignableFrom(dialectClass);
} catch (ClassNotFoundException e) {
// swallow
Logger.warn("jpa.dialect class %s not found", jpaDialect);
}
}
return isOracle;
}
public static class Evolution implements Comparable<Evolution> {
int revision;
String sql_up;
String sql_down;
String hash;
boolean applyUp;
public Evolution(int revision, String sql_up, String sql_down, boolean applyUp) {
this.revision = revision;
this.sql_down = sql_down;
this.sql_up = sql_up;
this.hash = Codec.hexSHA1(sql_up + sql_down);
this.applyUp = applyUp;
}
public int compareTo(Evolution o) {
return this.revision - o.revision;
}
@Override
public boolean equals(Object obj) {
return (obj instanceof Evolution) && ((Evolution) obj).revision == this.revision;
}
@Override
public int hashCode() {
return revision;
}
}
// JDBC Utils
static void execute(String sql) throws SQLException {
Connection connection = null;
try {
connection = getNewConnection();
connection.createStatement().execute(sql);
} catch (SQLException e) {
throw e;
} finally {
closeConnection(connection);
}
}
static Connection getNewConnection() throws SQLException {
Connection connection = getDatasource().getConnection();
connection.setAutoCommit(true); // Yes we want auto-commit
return connection;
}
static void closeConnection(Connection connection) {
try {
if (connection != null) {
connection.close();
}
} catch (Exception e) {
throw new UnexpectedException(e);
}
}
// Exceptions
public static class InvalidDatabaseRevision extends PlayException {
String evolutionScript;
public InvalidDatabaseRevision(String evolutionScript) {
this.evolutionScript = evolutionScript;
}
@Override
public String getErrorTitle() {
return "Your database needs evolution!";
}
@Override
public String getErrorDescription() {
return "An SQL script will be run on your database.";
}
@Override
public String getMoreHTML() {
return "<h3>This SQL script must be run:</h3><pre style=\"background:#fff; border:1px solid #ccc; padding: 5px\">" + evolutionScript + "</pre><form action='/@evolutions/apply' method='POST'><input type='submit' value='Apply evolutions'></form>";
}
}
public static class InconsistentDatabase extends PlayException {
String evolutionScript;
String error;
int revision;
public InconsistentDatabase(String evolutionScript, String error, int revision) {
this.evolutionScript = evolutionScript;
this.error = error;
this.revision = revision;
}
@Override
public String getErrorTitle() {
return "Your database is in an inconsistent state!";
}
@Override
public String getErrorDescription() {
return "An evolution has not been applied properly. Please check the problem and resolve it manually before marking it as resolved.";
}
@Override
public String getMoreHTML() {
return "<h3>This SQL script has been run, and there was a problem:</h3><pre style=\"background:#fff; border:1px solid #ccc; padding: 5px\">" + evolutionScript + "</pre><h4>This error has been thrown:</h4><pre style=\"background:#fff; border:1px solid #ccc; color: #c00; padding: 5px\">" + error + "</pre><form action='/@evolutions/force/" + revision + "' method='POST'><input type='submit' value='Mark it resolved'></form>";
}
}
}
| false | true | public static void main(String[] args) throws SQLException {
/** Check that evolutions are enabled **/
if (!evolutionsDirectory.exists()) {
System.out.println("~ Evolutions are not enabled. Create a db/evolutions directory to create your first 1.sql evolution script.");
System.out.println("~");
return;
}
/** Start the DB plugin **/
Play.id = System.getProperty("play.id");
Play.applicationPath = new File(System.getProperty("application.path"));
Play.guessFrameworkPath();
Play.readConfiguration();
Play.javaPath = new ArrayList<VirtualFile>();
Play.classes = new ApplicationClasses();
Play.classloader = new ApplicationClassloader();
Logger.init();
Logger.setUp("ERROR");
new DBPlugin().onApplicationStart();
/** Connected **/
System.out.println("~ Connected to " + getDatasource().getConnection().getMetaData().getURL());
/** Sumary **/
Evolution database = listDatabaseEvolutions().peek();
Evolution application = listApplicationEvolutions().peek();
if ("resolve".equals(System.getProperty("mode"))) {
try {
checkEvolutionsState();
System.out.println("~");
System.out.println("~ Nothing to resolve...");
System.out.println("~");
return;
} catch (InconsistentDatabase e) {
resolve(e.revision);
System.out.println("~");
System.out.println("~ Revision " + e.revision + " has been resolved;");
System.out.println("~");
} catch (InvalidDatabaseRevision e) {
// see later
}
}
/** Check inconsistency **/
try {
checkEvolutionsState();
} catch (InconsistentDatabase e) {
System.out.println("~");
System.out.println("~ Your database is in an inconsistent state!");
System.out.println("~");
System.out.println("~ While applying this script part:");
System.out.println("");
System.out.println(e.evolutionScript);
System.out.println("");
System.out.println("~ The following error occured:");
System.out.println("");
System.out.println(e.error);
System.out.println("");
System.out.println("~ Please correct it manually, and mark it resolved by running `play evolutions:resolve`");
System.out.println("~");
return;
} catch (InvalidDatabaseRevision e) {
// see later
}
System.out.print("~ Application revision is " + application.revision + " [" + application.hash.substring(0, 7) + "]");
System.out.println(" and Database revision is " + database.revision + " [" + database.hash.substring(0, 7) + "]");
System.out.println("~");
/** Evolution script **/
List<Evolution> evolutions = getEvolutionScript();
if (evolutions.isEmpty()) {
System.out.println("~ Your database is up to date");
System.out.println("~");
} else {
if ("apply".equals(System.getProperty("mode"))) {
System.out.println("~ Applying evolutions:");
System.out.println("");
System.out.println("# ------------------------------------------------------------------------------");
System.out.println("");
System.out.println(toHumanReadableScript(evolutions));
System.out.println("");
System.out.println("# ------------------------------------------------------------------------------");
System.out.println("");
if (applyScript(true)) {
System.out.println("~");
System.out.println("~ Evolutions script successfully applied!");
System.out.println("~");
} else {
System.out.println("~");
System.out.println("~ Can't apply evolutions...");
System.out.println("~");
}
} else if ("markApplied".equals(System.getProperty("mode"))) {
if (applyScript(false)) {
System.out.println("~ Evolutions script marked as applied!");
System.out.println("~");
} else {
System.out.println("~ Can't apply evolutions...");
System.out.println("~");
}
} else {
System.out.println("~ Your database needs evolutions!");
System.out.println("");
System.out.println("# ------------------------------------------------------------------------------");
System.out.println("");
System.out.println(toHumanReadableScript(evolutions));
System.out.println("");
System.out.println("# ------------------------------------------------------------------------------");
System.out.println("");
System.out.println("~ Run `play evolutions:apply` to automatically apply this script to the database");
System.out.println("~ or apply it yourself and mark it done using `play evolutions:markApplied`");
System.out.println("~");
}
}
}
| public static void main(String[] args) throws SQLException {
/** Check that evolutions are enabled **/
if (!evolutionsDirectory.exists()) {
System.out.println("~ Evolutions are not enabled. Create a db/evolutions directory to create your first 1.sql evolution script.");
System.out.println("~");
return;
}
/** Start the DB plugin **/
Play.id = System.getProperty("play.id");
Play.applicationPath = new File(System.getProperty("application.path"));
Play.guessFrameworkPath();
Play.readConfiguration();
Play.javaPath = new ArrayList<VirtualFile>();
Play.classes = new ApplicationClasses();
Play.classloader = new ApplicationClassloader();
Logger.init();
Logger.setUp("ERROR");
new DBPlugin().onApplicationStart();
/** Connected **/
System.out.println("~ Connected to " + getDatasource().getConnection().getMetaData().getURL());
/** Sumary **/
Evolution database = listDatabaseEvolutions().peek();
Evolution application = listApplicationEvolutions().peek();
if ("resolve".equals(System.getProperty("mode"))) {
try {
checkEvolutionsState();
System.out.println("~");
System.out.println("~ Nothing to resolve...");
System.out.println("~");
return;
} catch (InconsistentDatabase e) {
resolve(e.revision);
System.out.println("~");
System.out.println("~ Revision " + e.revision + " has been resolved;");
System.out.println("~");
} catch (InvalidDatabaseRevision e) {
// see later
}
}
/** Check inconsistency **/
try {
checkEvolutionsState();
} catch (InconsistentDatabase e) {
System.out.println("~");
System.out.println("~ Your database is in an inconsistent state!");
System.out.println("~");
System.out.println("~ While applying this script part:");
System.out.println("");
System.out.println(e.evolutionScript);
System.out.println("");
System.out.println("~ The following error occured:");
System.out.println("");
System.out.println(e.error);
System.out.println("");
System.out.println("~ Please correct it manually, and mark it resolved by running `play evolutions:resolve`");
System.out.println("~");
return;
} catch (InvalidDatabaseRevision e) {
// see later
}
System.out.print("~ Application revision is " + application.revision + " [" + application.hash.substring(0, 7) + "]");
System.out.println(" and Database revision is " + database.revision + " [" + database.hash.substring(0, 7) + "]");
System.out.println("~");
/** Evolution script **/
List<Evolution> evolutions = getEvolutionScript();
if (evolutions.isEmpty()) {
System.out.println("~ Your database is up to date");
System.out.println("~");
} else {
if ("apply".equals(System.getProperty("mode"))) {
System.out.println("~ Applying evolutions:");
System.out.println("");
System.out.println("# ------------------------------------------------------------------------------");
System.out.println("");
System.out.println(toHumanReadableScript(evolutions));
System.out.println("");
System.out.println("# ------------------------------------------------------------------------------");
System.out.println("");
if (applyScript(true)) {
System.out.println("~");
System.out.println("~ Evolutions script successfully applied!");
System.out.println("~");
} else {
System.out.println("~");
System.out.println("~ Can't apply evolutions...");
System.out.println("~");
System.exit(-1);
}
} else if ("markApplied".equals(System.getProperty("mode"))) {
if (applyScript(false)) {
System.out.println("~ Evolutions script marked as applied!");
System.out.println("~");
} else {
System.out.println("~ Can't apply evolutions...");
System.out.println("~");
System.exit(-1);
}
} else {
System.out.println("~ Your database needs evolutions!");
System.out.println("");
System.out.println("# ------------------------------------------------------------------------------");
System.out.println("");
System.out.println(toHumanReadableScript(evolutions));
System.out.println("");
System.out.println("# ------------------------------------------------------------------------------");
System.out.println("");
System.out.println("~ Run `play evolutions:apply` to automatically apply this script to the database");
System.out.println("~ or apply it yourself and mark it done using `play evolutions:markApplied`");
System.out.println("~");
}
}
}
|
diff --git a/src/java/fedora/server/utilities/ServerUtility.java b/src/java/fedora/server/utilities/ServerUtility.java
index 981824401..2d24c068c 100644
--- a/src/java/fedora/server/utilities/ServerUtility.java
+++ b/src/java/fedora/server/utilities/ServerUtility.java
@@ -1,183 +1,194 @@
package fedora.server.utilities;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.util.Properties;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import fedora.common.Constants;
import fedora.common.http.WebClient;
import fedora.server.config.ServerConfiguration;
import fedora.server.config.ServerConfigurationParser;
import fedora.server.errors.GeneralException;
public class ServerUtility {
/** Logger for this class. */
private static final Logger LOG = Logger.getLogger(
ServerUtility.class.getName());
public static final String HTTP = "http";
public static final String HTTPS = "https";
public static final String FEDORA_SERVER_HOST = "fedoraServerHost";
public static final String FEDORA_SERVER_PORT = "fedoraServerPort";
public static final String FEDORA_REDIRECT_PORT = "fedoraRedirectPort";
private static ServerConfiguration CONFIG;
static {
String fedoraHome = Constants.FEDORA_HOME;
if (fedoraHome == null) {
LOG.warn("FEDORA_HOME not set; unable to initialize");
} else {
File fcfgFile = new File(fedoraHome, "server/config/fedora.fcfg");
try {
CONFIG = new ServerConfigurationParser(
new FileInputStream(fcfgFile)).parse();
} catch (IOException e) {
LOG.warn("Unable to read server configuration from "
+ fcfgFile.getPath(), e);
}
}
}
/**
* Tell whether the server is running by pinging it as a client.
*/
public static boolean pingServer(String protocol, String user,
String pass) {
try {
getServerResponse(protocol, user, pass, "/describe");
return true;
} catch (Exception e) {
LOG.debug("Assuming the server isn't running because "
+ "describe request failed", e);
return false;
}
}
/**
* Get the baseURL of the Fedora server from the host and port configured.
*
* It will look like http://localhost:8080/fedora
*/
public static String getBaseURL(String protocol) {
String port;
if (protocol.equals("http")) {
port = CONFIG.getParameter(FEDORA_SERVER_PORT).getValue();
} else if (protocol.equals("https")) {
port = CONFIG.getParameter(FEDORA_REDIRECT_PORT).getValue();
} else {
throw new RuntimeException("Unrecogonized protocol: " + protocol);
}
return protocol + "://"
+ CONFIG.getParameter(FEDORA_SERVER_HOST).getValue() + ":"
+ port + "/fedora";
}
/**
* Signals for the server to reload its policies.
*/
public static void reloadPolicies(String protocol, String user,
String pass)
throws IOException {
getServerResponse(protocol, user, pass,
"/management/control?action=reloadPolicies");
}
/**
* Hits the given Fedora Server URL and returns the response
* as a String. Throws an IOException if the response code is not 200(OK).
*/
private static String getServerResponse(String protocol, String user,
String pass, String path)
throws IOException {
String url = getBaseURL(protocol) + path;
LOG.info("Getting URL: " + url);
UsernamePasswordCredentials creds =
new UsernamePasswordCredentials(user, pass);
return new WebClient().getResponseAsString(url, true, creds);
}
/**
* Tell whether the given URL appears to be referring to somewhere
* within the Fedora webapp.
*/
public static boolean isURLFedoraServer(String url) {
String fedoraServerHost = CONFIG.getParameter(FEDORA_SERVER_HOST).getValue();
String fedoraServerPort = CONFIG.getParameter(FEDORA_SERVER_PORT).getValue();
String fedoraServerRedirectPort = CONFIG.getParameter(FEDORA_REDIRECT_PORT).getValue();
// Check for URLs that are callbacks to the Fedora server
if (url.startsWith("http://"+fedoraServerHost+":"+fedoraServerPort+"/fedora/") ||
url.startsWith("http://"+fedoraServerHost+"/fedora/") ||
url.startsWith("https://"+fedoraServerHost+":"+fedoraServerRedirectPort+"/fedora/") ||
- url.startsWith("https://"+fedoraServerHost+"/fedora/") ) {
+ url.startsWith("https://"+fedoraServerHost+"/fedora/")
+ // This is an ugly hack to fix backend security bug when authentication enabled
+ // for api-a. The getDS target is intentionally unsecure to allow backend services
+ // that cannot handle authentication or ssl a callback channel. If not excluded
+ // here, it can result in the incorrect assignment of fedoraRole=fedoraInternalCall-1
+ // elsewhere in the code to be associated with the getDS target. Additional
+ // refactoring is needed to eliminate the need for this hack.
+ &&
+ !(url.startsWith("http://"+fedoraServerHost+":"+fedoraServerPort+"/fedora/getDS?") ||
+ url.startsWith("http://"+fedoraServerHost+"/fedora/getDS?") ||
+ url.startsWith("https://"+fedoraServerHost+":"+fedoraServerRedirectPort+"/fedora/getDS?") ||
+ url.startsWith("https://"+fedoraServerHost+"/fedora/getDS?")) ) {
LOG.debug("URL was Fedora-to-Fedora callback: "+url);
return true;
} else {
LOG.debug("URL was Non-Fedora callback: "+url);
return false;
}
}
/**
* Initializes logging to use Log4J and to send WARN messages to STDOUT for
* command-line use.
*/
private static void initLogging() {
// send all log4j output to STDOUT and configure levels
Properties props = new Properties();
props.setProperty("log4j.appender.STDOUT",
"org.apache.log4j.ConsoleAppender");
props.setProperty("log4j.appender.STDOUT.layout",
"org.apache.log4j.PatternLayout");
props.setProperty("log4j.appender.STDOUT.layout.ConversionPattern",
"%p: %m%n");
props.setProperty("log4j.rootLogger", "WARN, STDOUT");
PropertyConfigurator.configure(props);
// tell commons-logging to use Log4J
final String pfx = "org.apache.commons.logging.";
System.setProperty(pfx + "LogFactory", pfx + "impl.Log4jFactory");
System.setProperty(pfx + "Log", pfx + "impl.Log4JLogger");
}
/**
* Command-line entry point to reload policies.
*
* Takes 3 args: protocol user pass
*/
public static void main(String[] args) {
initLogging();
if (args.length == 3) {
try {
reloadPolicies(args[0], args[1], args[2]);
System.out.println("SUCCESS: Policies have been reloaded");
System.exit(0);
} catch (Throwable th) {
th.printStackTrace();
System.err.println("ERROR: Reloading policies failed; see above");
System.exit(1);
}
} else {
System.err.println("ERROR: Three arguments required: "
+ "http|https username password");
System.exit(1);
}
}
}
| true | true | public static boolean isURLFedoraServer(String url) {
String fedoraServerHost = CONFIG.getParameter(FEDORA_SERVER_HOST).getValue();
String fedoraServerPort = CONFIG.getParameter(FEDORA_SERVER_PORT).getValue();
String fedoraServerRedirectPort = CONFIG.getParameter(FEDORA_REDIRECT_PORT).getValue();
// Check for URLs that are callbacks to the Fedora server
if (url.startsWith("http://"+fedoraServerHost+":"+fedoraServerPort+"/fedora/") ||
url.startsWith("http://"+fedoraServerHost+"/fedora/") ||
url.startsWith("https://"+fedoraServerHost+":"+fedoraServerRedirectPort+"/fedora/") ||
url.startsWith("https://"+fedoraServerHost+"/fedora/") ) {
LOG.debug("URL was Fedora-to-Fedora callback: "+url);
return true;
} else {
LOG.debug("URL was Non-Fedora callback: "+url);
return false;
}
}
| public static boolean isURLFedoraServer(String url) {
String fedoraServerHost = CONFIG.getParameter(FEDORA_SERVER_HOST).getValue();
String fedoraServerPort = CONFIG.getParameter(FEDORA_SERVER_PORT).getValue();
String fedoraServerRedirectPort = CONFIG.getParameter(FEDORA_REDIRECT_PORT).getValue();
// Check for URLs that are callbacks to the Fedora server
if (url.startsWith("http://"+fedoraServerHost+":"+fedoraServerPort+"/fedora/") ||
url.startsWith("http://"+fedoraServerHost+"/fedora/") ||
url.startsWith("https://"+fedoraServerHost+":"+fedoraServerRedirectPort+"/fedora/") ||
url.startsWith("https://"+fedoraServerHost+"/fedora/")
// This is an ugly hack to fix backend security bug when authentication enabled
// for api-a. The getDS target is intentionally unsecure to allow backend services
// that cannot handle authentication or ssl a callback channel. If not excluded
// here, it can result in the incorrect assignment of fedoraRole=fedoraInternalCall-1
// elsewhere in the code to be associated with the getDS target. Additional
// refactoring is needed to eliminate the need for this hack.
&&
!(url.startsWith("http://"+fedoraServerHost+":"+fedoraServerPort+"/fedora/getDS?") ||
url.startsWith("http://"+fedoraServerHost+"/fedora/getDS?") ||
url.startsWith("https://"+fedoraServerHost+":"+fedoraServerRedirectPort+"/fedora/getDS?") ||
url.startsWith("https://"+fedoraServerHost+"/fedora/getDS?")) ) {
LOG.debug("URL was Fedora-to-Fedora callback: "+url);
return true;
} else {
LOG.debug("URL was Non-Fedora callback: "+url);
return false;
}
}
|
diff --git a/musique-core/src/main/java/com/tulskiy/musique/audio/player/PlayingThread.java b/musique-core/src/main/java/com/tulskiy/musique/audio/player/PlayingThread.java
index 828dd86..6e30cb7 100644
--- a/musique-core/src/main/java/com/tulskiy/musique/audio/player/PlayingThread.java
+++ b/musique-core/src/main/java/com/tulskiy/musique/audio/player/PlayingThread.java
@@ -1,183 +1,183 @@
/*
* Copyright (c) 2008, 2009, 2010, 2011 Denis Tulskiy
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* version 3 along with this work. If not, see <http://www.gnu.org/licenses/>.
*/
package com.tulskiy.musique.audio.player;
import com.tulskiy.musique.audio.player.io.AudioOutput;
import com.tulskiy.musique.audio.player.io.Buffer;
import com.tulskiy.musique.playlist.Track;
import com.tulskiy.musique.util.AudioMath;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.LineUnavailableException;
import java.util.logging.Level;
import java.util.logging.Logger;
import static com.tulskiy.musique.audio.player.PlayerEvent.PlayerEventCode;
/**
* Author: Denis Tulskiy
* Date: 1/15/11
*/
public class PlayingThread extends Actor implements Runnable {
public static final Logger logger = Logger.getLogger("musique");
private static final int BUFFER_SIZE = AudioOutput.BUFFER_SIZE;
private AudioFormat format;
private Player player;
private Buffer buffer;
private final Object lock = new Object();
private AudioOutput output = new AudioOutput();
private Track currentTrack;
private long currentByte;
private boolean active = false;
private double playbackTime;
private long playbackBytes;
public PlayingThread(Player player, Buffer buffer) {
this.player = player;
this.buffer = buffer;
}
@Override
public void process(Message message) {
switch (message) {
case PAUSE:
setState(!active);
break;
case PLAY:
setState(true);
break;
case STOP:
stop();
break;
}
}
private void stop() {
output.flush();
setState(false);
output.close();
updatePlaybackTime();
player.fireEvent(PlayerEventCode.STOPPED);
}
private void setState(boolean newState) {
if (active != newState) {
active = newState;
synchronized (lock) {
lock.notifyAll();
}
}
}
@SuppressWarnings({"InfiniteLoopStatement"})
@Override
public void run() {
byte[] buf = new byte[BUFFER_SIZE];
while (true) {
synchronized (lock) {
try {
while (!active) {
player.fireEvent(PlayerEventCode.PAUSED);
output.stop();
System.gc();
lock.wait();
}
output.start();
player.fireEvent(PlayerEventCode.PLAYING_STARTED);
- while (active) {
+ out : while (active) {
int len = buffer.read(buf, 0, BUFFER_SIZE);
while (len == -1) {
if (!openNext()) {
stop();
- break;
+ break out;
}
len = buffer.read(buf, 0, BUFFER_SIZE);
}
currentByte += len;
playbackBytes += len;
output.write(buf, 0, len);
}
} catch (Exception e) {
logger.log(Level.WARNING, "Exception while playing. Stopping now", e);
currentTrack = null;
stop();
}
}
}
}
private boolean openNext() {
try {
logger.fine("Getting next track");
Buffer.NextEntry nextEntry = buffer.pollNextTrack();
if (nextEntry.track == null) {
return false;
}
currentTrack = nextEntry.track;
if (nextEntry.forced) {
output.flush();
}
format = nextEntry.format;
output.init(format);
if (nextEntry.startSample >= 0) {
currentByte = AudioMath.samplesToBytes(nextEntry.startSample, format.getFrameSize());
player.fireEvent(PlayerEventCode.SEEK_FINISHED);
} else {
currentByte = 0;
updatePlaybackTime();
player.fireEvent(PlayerEventCode.FILE_OPENED);
}
return true;
} catch (Exception e) {
logger.log(Level.WARNING, "Could not open next track", e);
return false;
}
}
private void updatePlaybackTime() {
if (format != null) {
playbackTime = AudioMath.bytesToMillis(
playbackBytes, format);
}
playbackBytes = 0;
}
public Track getCurrentTrack() {
return currentTrack;
}
public AudioOutput getOutput() {
return output;
}
public boolean isActive() {
return active;
}
public long getCurrentSample() {
if (format != null) {
return AudioMath.bytesToSamples(currentByte, format.getFrameSize());
} else return 0;
}
public double getPlaybackTime() {
return playbackTime;
}
}
| false | true | public void run() {
byte[] buf = new byte[BUFFER_SIZE];
while (true) {
synchronized (lock) {
try {
while (!active) {
player.fireEvent(PlayerEventCode.PAUSED);
output.stop();
System.gc();
lock.wait();
}
output.start();
player.fireEvent(PlayerEventCode.PLAYING_STARTED);
while (active) {
int len = buffer.read(buf, 0, BUFFER_SIZE);
while (len == -1) {
if (!openNext()) {
stop();
break;
}
len = buffer.read(buf, 0, BUFFER_SIZE);
}
currentByte += len;
playbackBytes += len;
output.write(buf, 0, len);
}
} catch (Exception e) {
logger.log(Level.WARNING, "Exception while playing. Stopping now", e);
currentTrack = null;
stop();
}
}
}
}
| public void run() {
byte[] buf = new byte[BUFFER_SIZE];
while (true) {
synchronized (lock) {
try {
while (!active) {
player.fireEvent(PlayerEventCode.PAUSED);
output.stop();
System.gc();
lock.wait();
}
output.start();
player.fireEvent(PlayerEventCode.PLAYING_STARTED);
out : while (active) {
int len = buffer.read(buf, 0, BUFFER_SIZE);
while (len == -1) {
if (!openNext()) {
stop();
break out;
}
len = buffer.read(buf, 0, BUFFER_SIZE);
}
currentByte += len;
playbackBytes += len;
output.write(buf, 0, len);
}
} catch (Exception e) {
logger.log(Level.WARNING, "Exception while playing. Stopping now", e);
currentTrack = null;
stop();
}
}
}
}
|
diff --git a/dspace/src/org/dspace/app/webui/servlet/BitstreamServlet.java b/dspace/src/org/dspace/app/webui/servlet/BitstreamServlet.java
index 86be18da8..09a70ffb7 100644
--- a/dspace/src/org/dspace/app/webui/servlet/BitstreamServlet.java
+++ b/dspace/src/org/dspace/app/webui/servlet/BitstreamServlet.java
@@ -1,204 +1,209 @@
/*
* BitstreamServlet.java
*
* Version: $Revision$
*
* Date: $Date$
*
* Copyright (c) 2002-2005, Hewlett-Packard Company and Massachusetts
* Institute of Technology. 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 Hewlett-Packard Company nor the name of the
* Massachusetts Institute of Technology nor the names of their
* 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
* HOLDERS 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.dspace.app.webui.servlet;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.dspace.app.webui.util.JSPManager;
import org.dspace.authorize.AuthorizeException;
import org.dspace.content.Bitstream;
import org.dspace.content.Bundle;
import org.dspace.content.Item;
import org.dspace.core.Constants;
import org.dspace.core.Context;
import org.dspace.core.LogManager;
import org.dspace.core.Utils;
import org.dspace.handle.HandleManager;
/**
* Servlet for retrieving bitstreams. The bits are simply piped to the user.
* <P>
* <code>/bitstream/handle/sequence_id/filename</code>
*
* @author Robert Tansley
* @version $Revision$
*/
public class BitstreamServlet extends DSpaceServlet
{
/** log4j category */
private static Logger log = Logger.getLogger(BitstreamServlet.class);
protected void doDSGet(Context context, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException,
SQLException, AuthorizeException
{
Bitstream bitstream = null;
boolean isWithdrawn = false;
// Get the ID from the URL
String idString = request.getPathInfo();
String handle = "";
String sequence = "";
if (idString != null)
{
// Parse 'handle' and 'sequence' (bitstream seq. number) out
// of remaining URL path, which is typically of the format:
// {handle}/{sequence}/{bitstream-name}
// But since the bitstream name MAY have any number of "/"s in
// it, and the handle is guaranteed to have one slash, we
// scan from the start to pick out handle and sequence:
// Remove leading slash if any:
if (idString.startsWith("/"))
{
idString = idString.substring(1);
}
// skip first slash within handle
int slashIndex = idString.indexOf('/');
if (slashIndex != -1)
{
slashIndex = idString.indexOf('/', slashIndex + 1);
if (slashIndex != -1)
{
handle = idString.substring(0, slashIndex);
int slash2 = idString.indexOf('/', slashIndex + 1);
if (slash2 != -1)
sequence = idString.substring(slashIndex+1,slash2);
else
sequence = idString.substring(slashIndex+1);
}
else
handle = idString;
}
// Find the corresponding bitstream
try
{
Item item = (Item) HandleManager.resolveToObject(context,
handle);
if (item == null)
{
log.info(LogManager.getHeader(context, "invalid_id",
"path=" + handle));
JSPManager
.showInvalidIDError(request, response, handle, -1);
return;
}
// determine whether the item the bitstream belongs to has been withdrawn
isWithdrawn = item.isWithdrawn();
int sid = Integer.parseInt(sequence);
boolean found = false;
Bundle[] bundles = item.getBundles();
for (int i = 0; (i < bundles.length) && !found; i++)
{
Bitstream[] bitstreams = bundles[i].getBitstreams();
for (int k = 0; (k < bitstreams.length) && !found; k++)
{
if (sid == bitstreams[k].getSequenceID())
{
bitstream = bitstreams[k];
found = true;
}
}
}
}
catch (NumberFormatException nfe)
{
// Invalid ID - this will be dealt with below
}
+ catch (ClassCastException cce)
+ {
+ // Asking for a bitstream from a collection or community
+ // - this will be dealt with below
+ }
}
if (!isWithdrawn)
{
// Did we get a bitstream?
if (bitstream != null)
{
log.info(LogManager.getHeader(context, "view_bitstream",
"bitstream_id=" + bitstream.getID()));
// Set the response MIME type
response.setContentType(bitstream.getFormat().getMIMEType());
// Response length
response.setHeader("Content-Length", String.valueOf(bitstream
.getSize()));
// Pipe the bits
InputStream is = bitstream.retrieve();
Utils.bufferedCopy(is, response.getOutputStream());
is.close();
response.getOutputStream().flush();
}
// display the tombstone instead of the bitstream if the item is withdrawn
else
{
// No bitstream - we got an invalid ID
log.info(LogManager.getHeader(context, "view_bitstream",
"invalid_bitstream_id=" + idString));
JSPManager.showInvalidIDError(request, response, idString,
Constants.BITSTREAM);
}
}
else
{
log.info(LogManager.getHeader(context, "view_bitstream", "item has been withdrawn"));
JSPManager.showJSP(request, response, "/tombstone.jsp");
}
}
}
| true | true | protected void doDSGet(Context context, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException,
SQLException, AuthorizeException
{
Bitstream bitstream = null;
boolean isWithdrawn = false;
// Get the ID from the URL
String idString = request.getPathInfo();
String handle = "";
String sequence = "";
if (idString != null)
{
// Parse 'handle' and 'sequence' (bitstream seq. number) out
// of remaining URL path, which is typically of the format:
// {handle}/{sequence}/{bitstream-name}
// But since the bitstream name MAY have any number of "/"s in
// it, and the handle is guaranteed to have one slash, we
// scan from the start to pick out handle and sequence:
// Remove leading slash if any:
if (idString.startsWith("/"))
{
idString = idString.substring(1);
}
// skip first slash within handle
int slashIndex = idString.indexOf('/');
if (slashIndex != -1)
{
slashIndex = idString.indexOf('/', slashIndex + 1);
if (slashIndex != -1)
{
handle = idString.substring(0, slashIndex);
int slash2 = idString.indexOf('/', slashIndex + 1);
if (slash2 != -1)
sequence = idString.substring(slashIndex+1,slash2);
else
sequence = idString.substring(slashIndex+1);
}
else
handle = idString;
}
// Find the corresponding bitstream
try
{
Item item = (Item) HandleManager.resolveToObject(context,
handle);
if (item == null)
{
log.info(LogManager.getHeader(context, "invalid_id",
"path=" + handle));
JSPManager
.showInvalidIDError(request, response, handle, -1);
return;
}
// determine whether the item the bitstream belongs to has been withdrawn
isWithdrawn = item.isWithdrawn();
int sid = Integer.parseInt(sequence);
boolean found = false;
Bundle[] bundles = item.getBundles();
for (int i = 0; (i < bundles.length) && !found; i++)
{
Bitstream[] bitstreams = bundles[i].getBitstreams();
for (int k = 0; (k < bitstreams.length) && !found; k++)
{
if (sid == bitstreams[k].getSequenceID())
{
bitstream = bitstreams[k];
found = true;
}
}
}
}
catch (NumberFormatException nfe)
{
// Invalid ID - this will be dealt with below
}
}
if (!isWithdrawn)
{
// Did we get a bitstream?
if (bitstream != null)
{
log.info(LogManager.getHeader(context, "view_bitstream",
"bitstream_id=" + bitstream.getID()));
// Set the response MIME type
response.setContentType(bitstream.getFormat().getMIMEType());
// Response length
response.setHeader("Content-Length", String.valueOf(bitstream
.getSize()));
// Pipe the bits
InputStream is = bitstream.retrieve();
Utils.bufferedCopy(is, response.getOutputStream());
is.close();
response.getOutputStream().flush();
}
// display the tombstone instead of the bitstream if the item is withdrawn
else
{
// No bitstream - we got an invalid ID
log.info(LogManager.getHeader(context, "view_bitstream",
"invalid_bitstream_id=" + idString));
JSPManager.showInvalidIDError(request, response, idString,
Constants.BITSTREAM);
}
}
else
{
log.info(LogManager.getHeader(context, "view_bitstream", "item has been withdrawn"));
JSPManager.showJSP(request, response, "/tombstone.jsp");
}
}
| protected void doDSGet(Context context, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException,
SQLException, AuthorizeException
{
Bitstream bitstream = null;
boolean isWithdrawn = false;
// Get the ID from the URL
String idString = request.getPathInfo();
String handle = "";
String sequence = "";
if (idString != null)
{
// Parse 'handle' and 'sequence' (bitstream seq. number) out
// of remaining URL path, which is typically of the format:
// {handle}/{sequence}/{bitstream-name}
// But since the bitstream name MAY have any number of "/"s in
// it, and the handle is guaranteed to have one slash, we
// scan from the start to pick out handle and sequence:
// Remove leading slash if any:
if (idString.startsWith("/"))
{
idString = idString.substring(1);
}
// skip first slash within handle
int slashIndex = idString.indexOf('/');
if (slashIndex != -1)
{
slashIndex = idString.indexOf('/', slashIndex + 1);
if (slashIndex != -1)
{
handle = idString.substring(0, slashIndex);
int slash2 = idString.indexOf('/', slashIndex + 1);
if (slash2 != -1)
sequence = idString.substring(slashIndex+1,slash2);
else
sequence = idString.substring(slashIndex+1);
}
else
handle = idString;
}
// Find the corresponding bitstream
try
{
Item item = (Item) HandleManager.resolveToObject(context,
handle);
if (item == null)
{
log.info(LogManager.getHeader(context, "invalid_id",
"path=" + handle));
JSPManager
.showInvalidIDError(request, response, handle, -1);
return;
}
// determine whether the item the bitstream belongs to has been withdrawn
isWithdrawn = item.isWithdrawn();
int sid = Integer.parseInt(sequence);
boolean found = false;
Bundle[] bundles = item.getBundles();
for (int i = 0; (i < bundles.length) && !found; i++)
{
Bitstream[] bitstreams = bundles[i].getBitstreams();
for (int k = 0; (k < bitstreams.length) && !found; k++)
{
if (sid == bitstreams[k].getSequenceID())
{
bitstream = bitstreams[k];
found = true;
}
}
}
}
catch (NumberFormatException nfe)
{
// Invalid ID - this will be dealt with below
}
catch (ClassCastException cce)
{
// Asking for a bitstream from a collection or community
// - this will be dealt with below
}
}
if (!isWithdrawn)
{
// Did we get a bitstream?
if (bitstream != null)
{
log.info(LogManager.getHeader(context, "view_bitstream",
"bitstream_id=" + bitstream.getID()));
// Set the response MIME type
response.setContentType(bitstream.getFormat().getMIMEType());
// Response length
response.setHeader("Content-Length", String.valueOf(bitstream
.getSize()));
// Pipe the bits
InputStream is = bitstream.retrieve();
Utils.bufferedCopy(is, response.getOutputStream());
is.close();
response.getOutputStream().flush();
}
// display the tombstone instead of the bitstream if the item is withdrawn
else
{
// No bitstream - we got an invalid ID
log.info(LogManager.getHeader(context, "view_bitstream",
"invalid_bitstream_id=" + idString));
JSPManager.showInvalidIDError(request, response, idString,
Constants.BITSTREAM);
}
}
else
{
log.info(LogManager.getHeader(context, "view_bitstream", "item has been withdrawn"));
JSPManager.showJSP(request, response, "/tombstone.jsp");
}
}
|
diff --git a/moho-impl/src/main/java/com/voxeo/moho/cpa/CallProgressAnalyzer.java b/moho-impl/src/main/java/com/voxeo/moho/cpa/CallProgressAnalyzer.java
index 5dc5f25e..8720544c 100644
--- a/moho-impl/src/main/java/com/voxeo/moho/cpa/CallProgressAnalyzer.java
+++ b/moho-impl/src/main/java/com/voxeo/moho/cpa/CallProgressAnalyzer.java
@@ -1,223 +1,223 @@
package com.voxeo.moho.cpa;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import org.apache.log4j.Logger;
import com.voxeo.moho.Call;
import com.voxeo.moho.State;
import com.voxeo.moho.common.event.MohoCPAEvent;
import com.voxeo.moho.event.CPAEvent.Type;
import com.voxeo.moho.event.InputDetectedEvent;
import com.voxeo.moho.event.Observer;
import com.voxeo.moho.media.Input;
import com.voxeo.moho.media.input.EnergyGrammar;
import com.voxeo.moho.media.input.Grammar;
import com.voxeo.moho.media.input.InputCommand;
import com.voxeo.moho.media.input.SignalGrammar;
import com.voxeo.moho.media.input.SignalGrammar.Signal;
public class CallProgressAnalyzer implements Observer {
private Logger log = Logger.getLogger(CallProgressAnalyzer.class);
/**
* <p>
* The 'cpa-maxtime' parameter is the "measuring stick" used to determine
* 'human' or 'machine' events. If the duration of voice activity is less than
* the value of 'cpa-maxtime', the called party is considered to be 'human.'
* If voice activity exceeds the 'cpa-maxtime' value, your application has
* likely called a 'machine'.
* <p>
* The recommended value for this parameter is between 4000 and 6000ms.
*/
protected long voxeo_cpa_max_time = 4000;
/**
* <p>
* The 'cpa-maxsilence' parameter is used to identify the end of voice
* activity. When activity begins, CPA will measure the duration until a
* period of silence greater than the value of 'cpa-maxsilence' is detected.
* Armed with start and end timestamps, CPA can then calculate the total
* duration of voice activity.
* <p>
* A value of 800 to 1200ms is suggested for this parameter.
*/
protected long voxeo_cpa_final_silence = 1000;
/**
* <p>
* The 'cpa-min-speech-duration' parameter is used to identify the minimum
* duration of energy.
* <p>
* A value of (x)ms to (y)ms is suggested for this parameter.
*/
protected long voxeo_cpa_min_speech_duration = 80;
/**
* <p>
* The 'cpa-min-volume' parameter is used to identify the threshold of what is
* considered to be energy vs silence.
* <p>
* A value of (x)db to (y)db is suggested for this parameter.
*/
protected int voxeo_cpa_min_volume = -24;
protected Map<Call, ProgressStatus> _status = new ConcurrentHashMap<Call, ProgressStatus>();
public CallProgressAnalyzer() {
}
public void setMaxTime(final long voxeo_cpa_max_time) {
this.voxeo_cpa_max_time = voxeo_cpa_max_time;
}
public long getMaxTime() {
return this.voxeo_cpa_max_time;
}
public void setFinalSilence(final long voxeo_cpa_final_silence) {
this.voxeo_cpa_final_silence = voxeo_cpa_final_silence;
}
public long getFinalSilence() {
return this.voxeo_cpa_final_silence;
}
public void setMinSpeechDuration(final long voxeo_cpa_min_speech_duration) {
this.voxeo_cpa_min_speech_duration = voxeo_cpa_min_speech_duration;
}
public long getMinSpeechDuration() {
return this.voxeo_cpa_min_speech_duration;
}
public void setMinVolume(final int voxeo_cpa_min_volume) {
this.voxeo_cpa_min_volume = voxeo_cpa_min_volume;
}
public int getMinVolume() {
return this.voxeo_cpa_min_volume;
}
public void start(final Call call, Signal... signals) {
start(call, -1, -1, false, signals);
}
/**
* @param call
* @param runtime
* Maximum time duration for detection.
* @param timeout
* Maximum time limit for first media.
* @param autoreset
* Indicating whether detection will contine on receiving
* end-of-speech event
* @param signals
*/
public void start(final Call call, final long runtime, final long timeout, final boolean autoreset, Signal... signals) {
call.addObserver(this);
final Grammar[] grammars = new Grammar[(signals == null || signals.length == 0) ? 2 : signals.length + 2];
grammars[0] = new EnergyGrammar(true, false, false);
grammars[1] = new EnergyGrammar(false, true, false);
if (signals != null && signals.length > 0) {
for (int i = 0; i < signals.length; i++) {
grammars[i + 2] = new SignalGrammar(signals[i], false);
}
}
final InputCommand cmd = new InputCommand(grammars);
if (runtime > 0) {
cmd.setMaxTimeout(runtime);
}
if (timeout > 0) {
cmd.setInitialTimeout(timeout);
}
cmd.setAutoRest(autoreset);
cmd.setEnergyParameters(voxeo_cpa_final_silence, null, null, voxeo_cpa_min_speech_duration, voxeo_cpa_min_volume);
log.info("Starting " + this + "[max_time:" + voxeo_cpa_max_time + ", final_silence:" + voxeo_cpa_final_silence
+ ", min_speech:" + voxeo_cpa_min_speech_duration + ", min_volume:" + voxeo_cpa_min_volume + ", runtime:"
+ runtime + ", timeout:" + timeout + ", autoreset:" + autoreset + ", signals=" + toString(signals) + "] on "
+ call);
final Input<Call> input = call.input(cmd);
_status.put(call, new ProgressStatus(call, input));
}
public void stop(final Call call) {
ProgressStatus status = _status.remove(call);
if (status != null) {
log.info("Stopping " + this + " on " + call);
status._input.stop();
call.removeObserver(this);
}
}
@State
public void onInputDetected(final InputDetectedEvent<Call> event) {
final Call call = event.getSource();
final ProgressStatus status = _status.get(call);
if (status == null) {
return;
}
log.info(event);
if (event.isStartOfSpeech()) {
status._lastStartOfSpeech = System.currentTimeMillis();
}
else if (event.isEndOfSpeech()) {
status._lastEndOfSpeech = System.currentTimeMillis();
- ++status._retries;
- long duration = status._lastEndOfSpeech - status._lastStartOfSpeech;
+ status._retries = +1;
+ long duration = status._lastEndOfSpeech - status._lastStartOfSpeech - voxeo_cpa_final_silence;
if (duration < voxeo_cpa_max_time) {
call.dispatch(new MohoCPAEvent<Call>(event.getSource(), Type.HUMAN_DETECTED, duration, status._retries));
}
else {
call.dispatch(new MohoCPAEvent<Call>(event.getSource(), Type.MACHINE_DETECTED, duration, status._retries));
}
status.reset();
}
else if (event.getSignal() != null) {
call.dispatch(new MohoCPAEvent<Call>(event.getSource(), Type.MACHINE_DETECTED, event.getSignal()));
}
}
private String toString(final Signal[] signals) {
if (signals == null || signals.length == 0) {
return null;
}
final StringBuilder sbuf = new StringBuilder();
sbuf.append("[");
for (final Signal s : signals) {
sbuf.append(s);
sbuf.append(",");
}
sbuf.replace(sbuf.length() - 1, sbuf.length(), "]");
return sbuf.toString();
}
protected class ProgressStatus {
protected int _retries = 0;
protected long _lastStartOfSpeech = 0;
protected long _lastEndOfSpeech = 0;
protected final Input<Call> _input;
protected final Call _call;
public ProgressStatus(final Call call, final Input<Call> input) {
_input = input;
_call = call;
}
public void reset() {
this._lastStartOfSpeech = 0;
this._lastEndOfSpeech = 0;
}
}
}
| true | true | public void onInputDetected(final InputDetectedEvent<Call> event) {
final Call call = event.getSource();
final ProgressStatus status = _status.get(call);
if (status == null) {
return;
}
log.info(event);
if (event.isStartOfSpeech()) {
status._lastStartOfSpeech = System.currentTimeMillis();
}
else if (event.isEndOfSpeech()) {
status._lastEndOfSpeech = System.currentTimeMillis();
++status._retries;
long duration = status._lastEndOfSpeech - status._lastStartOfSpeech;
if (duration < voxeo_cpa_max_time) {
call.dispatch(new MohoCPAEvent<Call>(event.getSource(), Type.HUMAN_DETECTED, duration, status._retries));
}
else {
call.dispatch(new MohoCPAEvent<Call>(event.getSource(), Type.MACHINE_DETECTED, duration, status._retries));
}
status.reset();
}
else if (event.getSignal() != null) {
call.dispatch(new MohoCPAEvent<Call>(event.getSource(), Type.MACHINE_DETECTED, event.getSignal()));
}
}
| public void onInputDetected(final InputDetectedEvent<Call> event) {
final Call call = event.getSource();
final ProgressStatus status = _status.get(call);
if (status == null) {
return;
}
log.info(event);
if (event.isStartOfSpeech()) {
status._lastStartOfSpeech = System.currentTimeMillis();
}
else if (event.isEndOfSpeech()) {
status._lastEndOfSpeech = System.currentTimeMillis();
status._retries = +1;
long duration = status._lastEndOfSpeech - status._lastStartOfSpeech - voxeo_cpa_final_silence;
if (duration < voxeo_cpa_max_time) {
call.dispatch(new MohoCPAEvent<Call>(event.getSource(), Type.HUMAN_DETECTED, duration, status._retries));
}
else {
call.dispatch(new MohoCPAEvent<Call>(event.getSource(), Type.MACHINE_DETECTED, duration, status._retries));
}
status.reset();
}
else if (event.getSignal() != null) {
call.dispatch(new MohoCPAEvent<Call>(event.getSource(), Type.MACHINE_DETECTED, event.getSignal()));
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.