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/alchemy-midlet/src/alchemy/evm/EtherFunction.java b/alchemy-midlet/src/alchemy/evm/EtherFunction.java
index 04d3715..d6442ba 100644
--- a/alchemy-midlet/src/alchemy/evm/EtherFunction.java
+++ b/alchemy-midlet/src/alchemy/evm/EtherFunction.java
@@ -1,952 +1,953 @@
/*
* This file is a part of Alchemy OS project.
* Copyright (C) 2011-2013, Sergey Basalaev <[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 alchemy.evm;
import alchemy.core.AlchemyException;
import alchemy.core.Context;
import alchemy.core.Function;
import alchemy.core.Int;
/**
* Ether Virtual Machine.
* @author Sergey Basalaev
*/
class EtherFunction extends Function {
private final int stacksize;
private final int localsize;
private final byte[] bcode;
private final char[] dbgtable;
private final char[] errtable;
private final Object[] cpool;
private final String libname;
public EtherFunction(String libname, String funcname, Object[] cpool, int stacksize, int localsize, byte[] code, char[] dbgtable, char[] errtable) {
super(funcname);
this.libname = libname;
this.stacksize = stacksize;
this.localsize = localsize;
this.bcode = code;
this.cpool = cpool;
this.dbgtable = dbgtable;
this.errtable = errtable;
}
public Object exec(Context c, Object[] args) throws AlchemyException {
//initializing
final Object[] stack = new Object[stacksize];
int head = -1;
final byte[] code = this.bcode;
Object[] locals;
if (args.length == localsize) {
locals = args;
} else {
locals = new Object[localsize];
System.arraycopy(args, 0, locals, 0, args.length);
}
int ct = 0;
while (true) {
try {
int instr = code[ct];
ct++;
switch (instr) {
// CONSTANTS
case Opcodes.ACONST_NULL: {
head++;
stack[head] = null;
break;
}
case Opcodes.ICONST_M1: {
head++;
stack[head] = Int.M_ONE;
break;
}
case Opcodes.ICONST_0: {
head++;
stack[head] = Int.ZERO;
break;
}
case Opcodes.ICONST_1: {
head++;
stack[head] = Int.ONE;
break;
}
case Opcodes.ICONST_2: {
head++;
stack[head] = Int.toInt(2);
break;
}
case Opcodes.ICONST_3: {
head++;
stack[head] = Int.toInt(3);
break;
}
case Opcodes.ICONST_4: {
head++;
stack[head] = Int.toInt(4);
break;
}
case Opcodes.ICONST_5: {
head++;
stack[head] = Int.toInt(5);
break;
}
case Opcodes.LCONST_0: {
head++;
stack[head] = Lval(0l);
break;
}
case Opcodes.LCONST_1: {
head++;
stack[head] = Lval(1l);
break;
}
case Opcodes.FCONST_0: {
head++;
stack[head] = Fval(0f);
break;
}
case Opcodes.FCONST_1: {
head++;
stack[head] = Fval(1f);
break;
}
case Opcodes.FCONST_2: {
head++;
stack[head] = Fval(2f);
break;
}
case Opcodes.DCONST_0: {
head++;
stack[head] = Dval(0d);
break;
}
case Opcodes.DCONST_1: {
head++;
stack[head] = Dval(1d);
break;
}
//CONVERSIONS
case Opcodes.I2L: {
stack[head] = Lval(ival(stack[head]));
break;
}
case Opcodes.I2F: {
stack[head] = Fval(ival(stack[head]));
break;
}
case Opcodes.I2D: {
stack[head] = Dval(ival(stack[head]));
break;
}
case Opcodes.L2F: {
stack[head] = Fval(lval(stack[head]));
break;
}
case Opcodes.L2D: {
stack[head] = Dval(lval(stack[head]));
break;
}
case Opcodes.L2I: {
stack[head] = Ival((int)lval(stack[head]));
break;
}
case Opcodes.F2D: {
stack[head] = Dval(fval(stack[head]));
break;
}
case Opcodes.F2I: {
stack[head] = Ival((int)fval(stack[head]));
break;
}
case Opcodes.F2L: {
stack[head] = Lval((long)fval(stack[head]));
break;
}
case Opcodes.D2I: {
stack[head] = Ival((int)dval(stack[head]));
break;
}
case Opcodes.D2L: {
stack[head] = Lval((long)dval(stack[head]));
break;
}
case Opcodes.D2F: {
stack[head] = Fval((float)dval(stack[head]));
break;
}
case Opcodes.I2C: {
stack[head] = Int.toInt((char)ival(stack[head]));
break;
}
case Opcodes.I2B: {
stack[head] = Int.toInt((byte)ival(stack[head]));
break;
}
case Opcodes.I2S: {
stack[head] = Int.toInt((short)ival(stack[head]));
break;
}
//INTEGER ARITHMETICS
case Opcodes.IADD: {
head--;
stack[head] = Ival(ival(stack[head]) + ival(stack[head+1]));
break;
}
case Opcodes.ISUB: {
head--;
stack[head] = Ival(ival(stack[head]) - ival(stack[head+1]));
break;
}
case Opcodes.IMUL: {
head--;
stack[head] = Ival(ival(stack[head]) * ival(stack[head+1]));
break;
}
case Opcodes.IDIV: {
head--;
stack[head] = Ival(ival(stack[head]) / ival(stack[head+1]));
break;
}
case Opcodes.IMOD: {
head--;
stack[head] = Ival(ival(stack[head]) % ival(stack[head+1]));
break;
}
case Opcodes.INEG: {
stack[head] = Ival(-ival(stack[head]));
break;
}
case Opcodes.ICMP: {
head--;
int itmp = ival(stack[head]) - ival(stack[head+1]);
stack[head] = (itmp > 0) ? Int.ONE : (itmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
case Opcodes.ISHL: {
head--;
stack[head] = Ival(ival(stack[head]) << ival(stack[head+1]));
break;
}
case Opcodes.ISHR: {
head--;
stack[head] = Ival(ival(stack[head]) >> ival(stack[head+1]));
break;
}
case Opcodes.IUSHR: {
head--;
stack[head] = Ival(ival(stack[head]) >>> ival(stack[head+1]));
break;
}
case Opcodes.IAND: {
head--;
stack[head] = Ival(ival(stack[head]) & ival(stack[head+1]));
break;
}
case Opcodes.IOR: {
head--;
stack[head] = Ival(ival(stack[head]) | ival(stack[head+1]));
break;
}
case Opcodes.IXOR: {
head--;
stack[head] = Ival(ival(stack[head]) ^ ival(stack[head+1]));
break;
}
//LONG ARITHMETICS
case Opcodes.LADD: {
head--;
stack[head] = Lval(lval(stack[head]) + lval(stack[head+1]));
break;
}
case Opcodes.LSUB: {
head--;
stack[head] = Lval(lval(stack[head]) - lval(stack[head+1]));
break;
}
case Opcodes.LMUL: {
head--;
stack[head] = Lval(lval(stack[head]) * lval(stack[head+1]));
break;
}
case Opcodes.LDIV: {
head--;
stack[head] = Lval(lval(stack[head]) / lval(stack[head+1]));
break;
}
case Opcodes.LMOD: {
head--;
stack[head] = Lval(lval(stack[head]) % lval(stack[head+1]));
break;
}
case Opcodes.LNEG: {
stack[head] = Lval(-lval(stack[head]));
break;
}
case Opcodes.LCMP: {
head--;
long ltmp = lval(stack[head]) - lval(stack[head+1]);
stack[head] = (ltmp > 0L) ? Int.ONE : (ltmp == 0L ? Int.ZERO : Int.M_ONE);
break;
}
case Opcodes.LSHL: {
head--;
stack[head] = Lval(lval(stack[head]) << ival(stack[head+1]));
break;
}
case Opcodes.LSHR: {
head--;
stack[head] = Lval(lval(stack[head]) >> ival(stack[head+1]));
break;
}
case Opcodes.LUSHR: {
head--;
stack[head] = Lval(lval(stack[head]) >>> ival(stack[head+1]));
break;
}
case Opcodes.LAND: {
head--;
stack[head] = Lval(lval(stack[head]) & lval(stack[head+1]));
break;
}
case Opcodes.LOR: {
head--;
stack[head] = Lval(lval(stack[head]) | lval(stack[head+1]));
break;
}
case Opcodes.LXOR: {
head--;
stack[head] = Lval(lval(stack[head]) ^ lval(stack[head+1]));
break;
}
//FLOAT ARITHMETICS
case Opcodes.FADD: {
head--;
stack[head] = Fval(fval(stack[head]) + fval(stack[head+1]));
break;
}
case Opcodes.FSUB: {
head--;
stack[head] = Fval(fval(stack[head]) - fval(stack[head+1]));
break;
}
case Opcodes.FMUL: {
head--;
stack[head] = Fval(fval(stack[head]) * fval(stack[head+1]));
break;
}
case Opcodes.FDIV: {
head--;
stack[head] = Fval(fval(stack[head]) / fval(stack[head+1]));
break;
}
case Opcodes.FMOD: {
head--;
stack[head] = Fval(fval(stack[head]) % fval(stack[head+1]));
break;
}
case Opcodes.FNEG: {
stack[head] = Fval(-fval(stack[head]));
break;
}
case Opcodes.FCMP: {
head--;
float ftmp = fval(stack[head]) - fval(stack[head+1]);
stack[head] = (ftmp > 0) ? Int.ONE : (ftmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
//DOUBLE ARITHMETICS
case Opcodes.DADD: {
head--;
stack[head] = Dval(dval(stack[head]) + dval(stack[head+1]));
break;
}
case Opcodes.DSUB: {
head--;
stack[head] = Dval(dval(stack[head]) - dval(stack[head+1]));
break;
}
case Opcodes.DMUL: {
head--;
stack[head] = Dval(dval(stack[head]) * dval(stack[head+1]));
break;
}
case Opcodes.DDIV: {
head--;
stack[head] = Dval(dval(stack[head]) / dval(stack[head+1]));
break;
}
case Opcodes.DMOD: {
head--;
stack[head] = Dval(dval(stack[head]) % dval(stack[head+1]));
break;
}
case Opcodes.DNEG: {
stack[head] = Dval(-dval(stack[head]));
break;
}
case Opcodes.DCMP: {
head--;
double dtmp = dval(stack[head]) - dval(stack[head+1]);
stack[head] = (dtmp > 0) ? Int.ONE : (dtmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
//LOCALS LOADERS AND SAVERS
case Opcodes.LOAD_0:
case Opcodes.LOAD_1:
case Opcodes.LOAD_2:
case Opcodes.LOAD_3:
case Opcodes.LOAD_4:
case Opcodes.LOAD_5:
case Opcodes.LOAD_6:
case Opcodes.LOAD_7: {
head++;
stack[head] = locals[instr & 7];
break;
}
case Opcodes.LOAD: { //load <ubyte>
head++;
stack[head] = locals[code[ct] & 0xff];
ct++;
break;
}
//variable savers
case Opcodes.STORE_0:
case Opcodes.STORE_1:
case Opcodes.STORE_2:
case Opcodes.STORE_3:
case Opcodes.STORE_4:
case Opcodes.STORE_5:
case Opcodes.STORE_6:
case Opcodes.STORE_7: {
locals[instr & 7] = stack[head];
head--;
break;
}
case Opcodes.STORE: { //store <ubyte>
locals[code[ct] & 0xff] = stack[head];
ct++;
head--;
break;
}
//BRANCHING
case Opcodes.IFEQ: { //ifeq <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) == 0) ct = itmp;
head--;
break;
}
case Opcodes.IFNE: { //ifne <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) != 0) ct = itmp;
head--;
break;
}
case Opcodes.IFLT: { //iflt <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) < 0) ct = itmp;
head--;
break;
}
case Opcodes.IFGE: { //ifge <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) >= 0) ct = itmp;
head--;
break;
}
case Opcodes.IFGT: { //ifgt <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) > 0) ct = itmp;
head--;
break;
}
case Opcodes.IFLE: { //ifle <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) <= 0) ct = itmp;
head--;
break;
}
case Opcodes.GOTO: { //goto <ushort>
ct = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
break;
}
case Opcodes.IFNULL: { //ifnull <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (stack[head] == null) ct = itmp;
head--;
break;
}
case Opcodes.IFNNULL: { //ifnnull <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (stack[head] != null) ct = itmp;
head--;
break;
}
case Opcodes.IF_ICMPLT: { //if_icmplt <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head-1]) < ival(stack[head])) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ICMPGE: { //if_icmpge <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head-1]) >= ival(stack[head])) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ICMPGT: { //if_icmpgt <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head-1]) > ival(stack[head])) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ICMPLE: { //if_icmple <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head-1]) <= ival(stack[head])) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ACMPEQ: { //if_acmpeq <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (stack[head-1] != null
? stack[head-1].equals(stack[head])
: stack[head] == null) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ACMPNE: { //if_acmpne <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (stack[head-1] != null
? !stack[head-1].equals(stack[head])
: stack[head] != null) ct = itmp;
head -= 2;
break;
}
case Opcodes.JSR: { //jsr <ushort>
head++;
stack[head] = Ival(ct+2);
ct = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
break;
}
case Opcodes.RET: { //ret
ct = ival(stack[head]);
head--;
break;
}
//FUNCTION CALLS
case Opcodes.CALL_0:
case Opcodes.CALL_1:
case Opcodes.CALL_2:
case Opcodes.CALL_3:
case Opcodes.CALL_4:
case Opcodes.CALL_5:
case Opcodes.CALL_6:
case Opcodes.CALL_7:
case Opcodes.CALV_0:
case Opcodes.CALV_1:
case Opcodes.CALV_2:
case Opcodes.CALV_3:
case Opcodes.CALV_4:
case Opcodes.CALV_5:
case Opcodes.CALV_6:
case Opcodes.CALV_7: {
int paramlen = instr & 7;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
stack[head] = ((Function)stack[head]).exec(c, params);
if ((instr & 8) != 0) head--;
break;
}
case Opcodes.CALL: {//call <ubyte>
int paramlen = code[ct] & 0xff;
ct++;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
stack[head] = ((Function)stack[head]).exec(c, params);
break;
}
case Opcodes.CALV: {//calv <ubyte>
int paramlen = code[ct] & 0xff;
ct++;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
((Function)stack[head]).exec(c, params);
head--;
break;
}
//ARRAY INSTRUCTIONS
case Opcodes.NEWAA: {
stack[head] = new Object[ival(stack[head])];
break;
}
case Opcodes.NEWBA: {
stack[head] = new byte[ival(stack[head])];
break;
}
case Opcodes.NEWCA: {
stack[head] = new char[ival(stack[head])];
break;
}
case Opcodes.NEWZA: {
stack[head] = new boolean[ival(stack[head])];
break;
}
case Opcodes.NEWSA: {
stack[head] = new short[ival(stack[head])];
break;
}
case Opcodes.NEWIA: {
stack[head] = new int[ival(stack[head])];
break;
}
case Opcodes.NEWLA: {
stack[head] = new long[ival(stack[head])];
break;
}
case Opcodes.NEWFA: {
stack[head] = new float[ival(stack[head])];
break;
}
case Opcodes.NEWDA: {
stack[head] = new double[ival(stack[head])];
break;
}
case Opcodes.AALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = ((Object[])stack[head])[at];
break;
}
case Opcodes.BALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((byte[])stack[head])[at] );
break;
}
case Opcodes.CALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((char[])stack[head])[at] );
break;
}
case Opcodes.ZALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((boolean[])stack[head])[at] );
break;
}
case Opcodes.SALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((short[])stack[head])[at] );
break;
}
case Opcodes.IALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((int[])stack[head])[at] );
break;
}
case Opcodes.LALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Lval( ((long[])stack[head])[at] );
break;
}
case Opcodes.FALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Fval( ((float[])stack[head])[at] );
break;
}
case Opcodes.DALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Dval( ((double[])stack[head])[at] );
break;
}
case Opcodes.AASTORE: {
Object val = stack[head];
int at = ival(stack[head-1]);
Object[] array = (Object[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.BASTORE: {
int val = ival(stack[head]);
int at = ival(stack[head-1]);
byte[] array = (byte[])stack[head-2];
array[at] = (byte)val;
head -= 3;
break;
}
case Opcodes.CASTORE: {
char val = (char) ival(stack[head]);
int at = ival(stack[head-1]);
char[] array = (char[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.ZASTORE: {
boolean val = bval(stack[head]);
int at = ival(stack[head-1]);
boolean[] array = (boolean[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.SASTORE: {
short val = (short)ival(stack[head]);
int at = ival(stack[head-1]);
short[] array = (short[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.IASTORE: {
int val = ival(stack[head]);
int at = ival(stack[head-1]);
int[] array = (int[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.FASTORE: {
float val = fval(stack[head]);
int at = ival(stack[head-1]);
float[] array = (float[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.DASTORE: {
double val = dval(stack[head]);
int at = ival(stack[head-1]);
double[] array = (double[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.AALEN: {
stack[head] = Ival(((Object[])stack[head]).length);
break;
}
case Opcodes.BALEN: {
stack[head] = Ival(((byte[])stack[head]).length);
break;
}
case Opcodes.CALEN: {
stack[head] = Ival(((char[])stack[head]).length);
break;
}
case Opcodes.ZALEN: {
stack[head] = Ival(((boolean[])stack[head]).length);
break;
}
case Opcodes.SALEN: {
stack[head] = Ival(((short[])stack[head]).length);
break;
}
case Opcodes.IALEN: {
stack[head] = Ival(((int[])stack[head]).length);
break;
}
case Opcodes.LALEN: {
stack[head] = Ival(((long[])stack[head]).length);
break;
}
case Opcodes.FALEN: {
stack[head] = Ival(((float[])stack[head]).length);
break;
}
case Opcodes.DALEN: {
stack[head] = Ival(((double[])stack[head]).length);
break;
}
//SWITCH BRANCHING
case Opcodes.TABLESWITCH: {
int dflt = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
ct += 2;
int min = (code[ct] << 24)
| ((code[ct+1] & 0xff) << 16)
| ((code[ct+2] & 0xff) << 8)
| (code[ct+3] & 0xff);
ct += 4;
int max = (code[ct] << 24)
| ((code[ct+1] & 0xff) << 16)
| ((code[ct+2] & 0xff) << 8)
| (code[ct+3] & 0xff);
ct += 4;
int val = ival(stack[head]);
head--;
if (val >= min && val <= max) {
ct += (val-min)*2;
ct = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
} else {
ct = dflt;
}
break;
}
case Opcodes.LOOKUPSWITCH: {
int dflt = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
ct += 2;
int count = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
ct += 2;
int val = ival(stack[head]);
head--;
boolean matched = false;
for (int i=0; i<count && !matched; i++) {
int cand = (code[ct] << 24)
| ((code[ct+1] & 0xff) << 16)
| ((code[ct+2] & 0xff) << 8)
| (code[ct+3] & 0xff);
ct += 4;
if (val == cand) {
ct = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
matched = true;
} else {
ct += 2;
}
}
if (!matched) ct = dflt;
break;
}
//OTHERS
case Opcodes.ACMP: {
head--;
boolean eq = (stack[head] == null) ? stack[head+1] == null : stack[head].equals(stack[head+1]);
stack[head] = Ival(!eq);
break;
}
case Opcodes.RET_NULL:
return null;
case Opcodes.RETURN:
return stack[head];
case Opcodes.DUP: {
stack[head+1] = stack[head];
head++;
break;
}
case Opcodes.DUP2: {
- stack[head+2] = stack[head+1] = stack[head];
+ stack[head+2] = stack[head];
+ stack[head+1] = stack[head-1];
head += 2;
break;
}
case Opcodes.SWAP: {
Object atmp = stack[head-1];
stack[head-1] = stack[head];
stack[head] = atmp;
break;
}
case Opcodes.LDC: { //ldc <ushort>
head++;
stack[head] = cpool[((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff)];
ct += 2;
break;
}
case Opcodes.POP: {
head--;
break;
}
case Opcodes.BIPUSH: { //bipush <byte>
head++;
stack[head] = Ival(code[ct]);
ct++;
break;
}
case Opcodes.SIPUSH: { //sipush <short>
head++;
stack[head] = Ival((code[ct] << 8) | (code[ct+1]& 0xff));
ct += 2;
break;
}
case Opcodes.IINC: { //iinc <ubyte> <byte>
int idx = code[ct] & 0xff;
ct++;
int inc = code[ct] & 0xff;
ct++;
locals[idx] = Int.toInt(((Int)locals[idx]).value + inc);
}
} /* the big switch */
} catch (Throwable e) {
// the instruction on which error occured
ct--;
// filling exception with debug info
AlchemyException ae = (e instanceof AlchemyException) ? (AlchemyException)e : new AlchemyException(e);
if (dbgtable != null) {
int srcline = 0;
for (int i=1; i<dbgtable.length; i += 2) {
if (dbgtable[i+1] <= ct) srcline = dbgtable[i];
}
ae.addTraceElement(this, cpool[dbgtable[0]]+":"+srcline);
} else {
ae.addTraceElement(this, "+"+ct);
}
// catching or rethrowing
int jumpto = -1;
if (errtable != null) {
for (int i=0; i < errtable.length && jumpto < 0; i += 4)
if (ct >= errtable[i] && ct <= errtable[i+1]) {
jumpto = errtable[i+2];
head = errtable[i+3];
}
}
if (jumpto >= 0) {
stack[head] = ae;
ct = jumpto;
} else {
throw ae;
}
}
} /* the great while */
}
public String toString() {
if (libname != null) return libname+':'+signature;
else return signature;
}
}
| true | true | public Object exec(Context c, Object[] args) throws AlchemyException {
//initializing
final Object[] stack = new Object[stacksize];
int head = -1;
final byte[] code = this.bcode;
Object[] locals;
if (args.length == localsize) {
locals = args;
} else {
locals = new Object[localsize];
System.arraycopy(args, 0, locals, 0, args.length);
}
int ct = 0;
while (true) {
try {
int instr = code[ct];
ct++;
switch (instr) {
// CONSTANTS
case Opcodes.ACONST_NULL: {
head++;
stack[head] = null;
break;
}
case Opcodes.ICONST_M1: {
head++;
stack[head] = Int.M_ONE;
break;
}
case Opcodes.ICONST_0: {
head++;
stack[head] = Int.ZERO;
break;
}
case Opcodes.ICONST_1: {
head++;
stack[head] = Int.ONE;
break;
}
case Opcodes.ICONST_2: {
head++;
stack[head] = Int.toInt(2);
break;
}
case Opcodes.ICONST_3: {
head++;
stack[head] = Int.toInt(3);
break;
}
case Opcodes.ICONST_4: {
head++;
stack[head] = Int.toInt(4);
break;
}
case Opcodes.ICONST_5: {
head++;
stack[head] = Int.toInt(5);
break;
}
case Opcodes.LCONST_0: {
head++;
stack[head] = Lval(0l);
break;
}
case Opcodes.LCONST_1: {
head++;
stack[head] = Lval(1l);
break;
}
case Opcodes.FCONST_0: {
head++;
stack[head] = Fval(0f);
break;
}
case Opcodes.FCONST_1: {
head++;
stack[head] = Fval(1f);
break;
}
case Opcodes.FCONST_2: {
head++;
stack[head] = Fval(2f);
break;
}
case Opcodes.DCONST_0: {
head++;
stack[head] = Dval(0d);
break;
}
case Opcodes.DCONST_1: {
head++;
stack[head] = Dval(1d);
break;
}
//CONVERSIONS
case Opcodes.I2L: {
stack[head] = Lval(ival(stack[head]));
break;
}
case Opcodes.I2F: {
stack[head] = Fval(ival(stack[head]));
break;
}
case Opcodes.I2D: {
stack[head] = Dval(ival(stack[head]));
break;
}
case Opcodes.L2F: {
stack[head] = Fval(lval(stack[head]));
break;
}
case Opcodes.L2D: {
stack[head] = Dval(lval(stack[head]));
break;
}
case Opcodes.L2I: {
stack[head] = Ival((int)lval(stack[head]));
break;
}
case Opcodes.F2D: {
stack[head] = Dval(fval(stack[head]));
break;
}
case Opcodes.F2I: {
stack[head] = Ival((int)fval(stack[head]));
break;
}
case Opcodes.F2L: {
stack[head] = Lval((long)fval(stack[head]));
break;
}
case Opcodes.D2I: {
stack[head] = Ival((int)dval(stack[head]));
break;
}
case Opcodes.D2L: {
stack[head] = Lval((long)dval(stack[head]));
break;
}
case Opcodes.D2F: {
stack[head] = Fval((float)dval(stack[head]));
break;
}
case Opcodes.I2C: {
stack[head] = Int.toInt((char)ival(stack[head]));
break;
}
case Opcodes.I2B: {
stack[head] = Int.toInt((byte)ival(stack[head]));
break;
}
case Opcodes.I2S: {
stack[head] = Int.toInt((short)ival(stack[head]));
break;
}
//INTEGER ARITHMETICS
case Opcodes.IADD: {
head--;
stack[head] = Ival(ival(stack[head]) + ival(stack[head+1]));
break;
}
case Opcodes.ISUB: {
head--;
stack[head] = Ival(ival(stack[head]) - ival(stack[head+1]));
break;
}
case Opcodes.IMUL: {
head--;
stack[head] = Ival(ival(stack[head]) * ival(stack[head+1]));
break;
}
case Opcodes.IDIV: {
head--;
stack[head] = Ival(ival(stack[head]) / ival(stack[head+1]));
break;
}
case Opcodes.IMOD: {
head--;
stack[head] = Ival(ival(stack[head]) % ival(stack[head+1]));
break;
}
case Opcodes.INEG: {
stack[head] = Ival(-ival(stack[head]));
break;
}
case Opcodes.ICMP: {
head--;
int itmp = ival(stack[head]) - ival(stack[head+1]);
stack[head] = (itmp > 0) ? Int.ONE : (itmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
case Opcodes.ISHL: {
head--;
stack[head] = Ival(ival(stack[head]) << ival(stack[head+1]));
break;
}
case Opcodes.ISHR: {
head--;
stack[head] = Ival(ival(stack[head]) >> ival(stack[head+1]));
break;
}
case Opcodes.IUSHR: {
head--;
stack[head] = Ival(ival(stack[head]) >>> ival(stack[head+1]));
break;
}
case Opcodes.IAND: {
head--;
stack[head] = Ival(ival(stack[head]) & ival(stack[head+1]));
break;
}
case Opcodes.IOR: {
head--;
stack[head] = Ival(ival(stack[head]) | ival(stack[head+1]));
break;
}
case Opcodes.IXOR: {
head--;
stack[head] = Ival(ival(stack[head]) ^ ival(stack[head+1]));
break;
}
//LONG ARITHMETICS
case Opcodes.LADD: {
head--;
stack[head] = Lval(lval(stack[head]) + lval(stack[head+1]));
break;
}
case Opcodes.LSUB: {
head--;
stack[head] = Lval(lval(stack[head]) - lval(stack[head+1]));
break;
}
case Opcodes.LMUL: {
head--;
stack[head] = Lval(lval(stack[head]) * lval(stack[head+1]));
break;
}
case Opcodes.LDIV: {
head--;
stack[head] = Lval(lval(stack[head]) / lval(stack[head+1]));
break;
}
case Opcodes.LMOD: {
head--;
stack[head] = Lval(lval(stack[head]) % lval(stack[head+1]));
break;
}
case Opcodes.LNEG: {
stack[head] = Lval(-lval(stack[head]));
break;
}
case Opcodes.LCMP: {
head--;
long ltmp = lval(stack[head]) - lval(stack[head+1]);
stack[head] = (ltmp > 0L) ? Int.ONE : (ltmp == 0L ? Int.ZERO : Int.M_ONE);
break;
}
case Opcodes.LSHL: {
head--;
stack[head] = Lval(lval(stack[head]) << ival(stack[head+1]));
break;
}
case Opcodes.LSHR: {
head--;
stack[head] = Lval(lval(stack[head]) >> ival(stack[head+1]));
break;
}
case Opcodes.LUSHR: {
head--;
stack[head] = Lval(lval(stack[head]) >>> ival(stack[head+1]));
break;
}
case Opcodes.LAND: {
head--;
stack[head] = Lval(lval(stack[head]) & lval(stack[head+1]));
break;
}
case Opcodes.LOR: {
head--;
stack[head] = Lval(lval(stack[head]) | lval(stack[head+1]));
break;
}
case Opcodes.LXOR: {
head--;
stack[head] = Lval(lval(stack[head]) ^ lval(stack[head+1]));
break;
}
//FLOAT ARITHMETICS
case Opcodes.FADD: {
head--;
stack[head] = Fval(fval(stack[head]) + fval(stack[head+1]));
break;
}
case Opcodes.FSUB: {
head--;
stack[head] = Fval(fval(stack[head]) - fval(stack[head+1]));
break;
}
case Opcodes.FMUL: {
head--;
stack[head] = Fval(fval(stack[head]) * fval(stack[head+1]));
break;
}
case Opcodes.FDIV: {
head--;
stack[head] = Fval(fval(stack[head]) / fval(stack[head+1]));
break;
}
case Opcodes.FMOD: {
head--;
stack[head] = Fval(fval(stack[head]) % fval(stack[head+1]));
break;
}
case Opcodes.FNEG: {
stack[head] = Fval(-fval(stack[head]));
break;
}
case Opcodes.FCMP: {
head--;
float ftmp = fval(stack[head]) - fval(stack[head+1]);
stack[head] = (ftmp > 0) ? Int.ONE : (ftmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
//DOUBLE ARITHMETICS
case Opcodes.DADD: {
head--;
stack[head] = Dval(dval(stack[head]) + dval(stack[head+1]));
break;
}
case Opcodes.DSUB: {
head--;
stack[head] = Dval(dval(stack[head]) - dval(stack[head+1]));
break;
}
case Opcodes.DMUL: {
head--;
stack[head] = Dval(dval(stack[head]) * dval(stack[head+1]));
break;
}
case Opcodes.DDIV: {
head--;
stack[head] = Dval(dval(stack[head]) / dval(stack[head+1]));
break;
}
case Opcodes.DMOD: {
head--;
stack[head] = Dval(dval(stack[head]) % dval(stack[head+1]));
break;
}
case Opcodes.DNEG: {
stack[head] = Dval(-dval(stack[head]));
break;
}
case Opcodes.DCMP: {
head--;
double dtmp = dval(stack[head]) - dval(stack[head+1]);
stack[head] = (dtmp > 0) ? Int.ONE : (dtmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
//LOCALS LOADERS AND SAVERS
case Opcodes.LOAD_0:
case Opcodes.LOAD_1:
case Opcodes.LOAD_2:
case Opcodes.LOAD_3:
case Opcodes.LOAD_4:
case Opcodes.LOAD_5:
case Opcodes.LOAD_6:
case Opcodes.LOAD_7: {
head++;
stack[head] = locals[instr & 7];
break;
}
case Opcodes.LOAD: { //load <ubyte>
head++;
stack[head] = locals[code[ct] & 0xff];
ct++;
break;
}
//variable savers
case Opcodes.STORE_0:
case Opcodes.STORE_1:
case Opcodes.STORE_2:
case Opcodes.STORE_3:
case Opcodes.STORE_4:
case Opcodes.STORE_5:
case Opcodes.STORE_6:
case Opcodes.STORE_7: {
locals[instr & 7] = stack[head];
head--;
break;
}
case Opcodes.STORE: { //store <ubyte>
locals[code[ct] & 0xff] = stack[head];
ct++;
head--;
break;
}
//BRANCHING
case Opcodes.IFEQ: { //ifeq <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) == 0) ct = itmp;
head--;
break;
}
case Opcodes.IFNE: { //ifne <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) != 0) ct = itmp;
head--;
break;
}
case Opcodes.IFLT: { //iflt <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) < 0) ct = itmp;
head--;
break;
}
case Opcodes.IFGE: { //ifge <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) >= 0) ct = itmp;
head--;
break;
}
case Opcodes.IFGT: { //ifgt <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) > 0) ct = itmp;
head--;
break;
}
case Opcodes.IFLE: { //ifle <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) <= 0) ct = itmp;
head--;
break;
}
case Opcodes.GOTO: { //goto <ushort>
ct = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
break;
}
case Opcodes.IFNULL: { //ifnull <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (stack[head] == null) ct = itmp;
head--;
break;
}
case Opcodes.IFNNULL: { //ifnnull <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (stack[head] != null) ct = itmp;
head--;
break;
}
case Opcodes.IF_ICMPLT: { //if_icmplt <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head-1]) < ival(stack[head])) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ICMPGE: { //if_icmpge <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head-1]) >= ival(stack[head])) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ICMPGT: { //if_icmpgt <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head-1]) > ival(stack[head])) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ICMPLE: { //if_icmple <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head-1]) <= ival(stack[head])) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ACMPEQ: { //if_acmpeq <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (stack[head-1] != null
? stack[head-1].equals(stack[head])
: stack[head] == null) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ACMPNE: { //if_acmpne <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (stack[head-1] != null
? !stack[head-1].equals(stack[head])
: stack[head] != null) ct = itmp;
head -= 2;
break;
}
case Opcodes.JSR: { //jsr <ushort>
head++;
stack[head] = Ival(ct+2);
ct = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
break;
}
case Opcodes.RET: { //ret
ct = ival(stack[head]);
head--;
break;
}
//FUNCTION CALLS
case Opcodes.CALL_0:
case Opcodes.CALL_1:
case Opcodes.CALL_2:
case Opcodes.CALL_3:
case Opcodes.CALL_4:
case Opcodes.CALL_5:
case Opcodes.CALL_6:
case Opcodes.CALL_7:
case Opcodes.CALV_0:
case Opcodes.CALV_1:
case Opcodes.CALV_2:
case Opcodes.CALV_3:
case Opcodes.CALV_4:
case Opcodes.CALV_5:
case Opcodes.CALV_6:
case Opcodes.CALV_7: {
int paramlen = instr & 7;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
stack[head] = ((Function)stack[head]).exec(c, params);
if ((instr & 8) != 0) head--;
break;
}
case Opcodes.CALL: {//call <ubyte>
int paramlen = code[ct] & 0xff;
ct++;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
stack[head] = ((Function)stack[head]).exec(c, params);
break;
}
case Opcodes.CALV: {//calv <ubyte>
int paramlen = code[ct] & 0xff;
ct++;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
((Function)stack[head]).exec(c, params);
head--;
break;
}
//ARRAY INSTRUCTIONS
case Opcodes.NEWAA: {
stack[head] = new Object[ival(stack[head])];
break;
}
case Opcodes.NEWBA: {
stack[head] = new byte[ival(stack[head])];
break;
}
case Opcodes.NEWCA: {
stack[head] = new char[ival(stack[head])];
break;
}
case Opcodes.NEWZA: {
stack[head] = new boolean[ival(stack[head])];
break;
}
case Opcodes.NEWSA: {
stack[head] = new short[ival(stack[head])];
break;
}
case Opcodes.NEWIA: {
stack[head] = new int[ival(stack[head])];
break;
}
case Opcodes.NEWLA: {
stack[head] = new long[ival(stack[head])];
break;
}
case Opcodes.NEWFA: {
stack[head] = new float[ival(stack[head])];
break;
}
case Opcodes.NEWDA: {
stack[head] = new double[ival(stack[head])];
break;
}
case Opcodes.AALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = ((Object[])stack[head])[at];
break;
}
case Opcodes.BALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((byte[])stack[head])[at] );
break;
}
case Opcodes.CALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((char[])stack[head])[at] );
break;
}
case Opcodes.ZALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((boolean[])stack[head])[at] );
break;
}
case Opcodes.SALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((short[])stack[head])[at] );
break;
}
case Opcodes.IALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((int[])stack[head])[at] );
break;
}
case Opcodes.LALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Lval( ((long[])stack[head])[at] );
break;
}
case Opcodes.FALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Fval( ((float[])stack[head])[at] );
break;
}
case Opcodes.DALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Dval( ((double[])stack[head])[at] );
break;
}
case Opcodes.AASTORE: {
Object val = stack[head];
int at = ival(stack[head-1]);
Object[] array = (Object[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.BASTORE: {
int val = ival(stack[head]);
int at = ival(stack[head-1]);
byte[] array = (byte[])stack[head-2];
array[at] = (byte)val;
head -= 3;
break;
}
case Opcodes.CASTORE: {
char val = (char) ival(stack[head]);
int at = ival(stack[head-1]);
char[] array = (char[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.ZASTORE: {
boolean val = bval(stack[head]);
int at = ival(stack[head-1]);
boolean[] array = (boolean[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.SASTORE: {
short val = (short)ival(stack[head]);
int at = ival(stack[head-1]);
short[] array = (short[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.IASTORE: {
int val = ival(stack[head]);
int at = ival(stack[head-1]);
int[] array = (int[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.FASTORE: {
float val = fval(stack[head]);
int at = ival(stack[head-1]);
float[] array = (float[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.DASTORE: {
double val = dval(stack[head]);
int at = ival(stack[head-1]);
double[] array = (double[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.AALEN: {
stack[head] = Ival(((Object[])stack[head]).length);
break;
}
case Opcodes.BALEN: {
stack[head] = Ival(((byte[])stack[head]).length);
break;
}
case Opcodes.CALEN: {
stack[head] = Ival(((char[])stack[head]).length);
break;
}
case Opcodes.ZALEN: {
stack[head] = Ival(((boolean[])stack[head]).length);
break;
}
case Opcodes.SALEN: {
stack[head] = Ival(((short[])stack[head]).length);
break;
}
case Opcodes.IALEN: {
stack[head] = Ival(((int[])stack[head]).length);
break;
}
case Opcodes.LALEN: {
stack[head] = Ival(((long[])stack[head]).length);
break;
}
case Opcodes.FALEN: {
stack[head] = Ival(((float[])stack[head]).length);
break;
}
case Opcodes.DALEN: {
stack[head] = Ival(((double[])stack[head]).length);
break;
}
//SWITCH BRANCHING
case Opcodes.TABLESWITCH: {
int dflt = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
ct += 2;
int min = (code[ct] << 24)
| ((code[ct+1] & 0xff) << 16)
| ((code[ct+2] & 0xff) << 8)
| (code[ct+3] & 0xff);
ct += 4;
int max = (code[ct] << 24)
| ((code[ct+1] & 0xff) << 16)
| ((code[ct+2] & 0xff) << 8)
| (code[ct+3] & 0xff);
ct += 4;
int val = ival(stack[head]);
head--;
if (val >= min && val <= max) {
ct += (val-min)*2;
ct = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
} else {
ct = dflt;
}
break;
}
case Opcodes.LOOKUPSWITCH: {
int dflt = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
ct += 2;
int count = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
ct += 2;
int val = ival(stack[head]);
head--;
boolean matched = false;
for (int i=0; i<count && !matched; i++) {
int cand = (code[ct] << 24)
| ((code[ct+1] & 0xff) << 16)
| ((code[ct+2] & 0xff) << 8)
| (code[ct+3] & 0xff);
ct += 4;
if (val == cand) {
ct = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
matched = true;
} else {
ct += 2;
}
}
if (!matched) ct = dflt;
break;
}
//OTHERS
case Opcodes.ACMP: {
head--;
boolean eq = (stack[head] == null) ? stack[head+1] == null : stack[head].equals(stack[head+1]);
stack[head] = Ival(!eq);
break;
}
case Opcodes.RET_NULL:
return null;
case Opcodes.RETURN:
return stack[head];
case Opcodes.DUP: {
stack[head+1] = stack[head];
head++;
break;
}
case Opcodes.DUP2: {
stack[head+2] = stack[head+1] = stack[head];
head += 2;
break;
}
case Opcodes.SWAP: {
Object atmp = stack[head-1];
stack[head-1] = stack[head];
stack[head] = atmp;
break;
}
case Opcodes.LDC: { //ldc <ushort>
head++;
stack[head] = cpool[((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff)];
ct += 2;
break;
}
case Opcodes.POP: {
head--;
break;
}
case Opcodes.BIPUSH: { //bipush <byte>
head++;
stack[head] = Ival(code[ct]);
ct++;
break;
}
case Opcodes.SIPUSH: { //sipush <short>
head++;
stack[head] = Ival((code[ct] << 8) | (code[ct+1]& 0xff));
ct += 2;
break;
}
case Opcodes.IINC: { //iinc <ubyte> <byte>
int idx = code[ct] & 0xff;
ct++;
int inc = code[ct] & 0xff;
ct++;
locals[idx] = Int.toInt(((Int)locals[idx]).value + inc);
}
} /* the big switch */
} catch (Throwable e) {
// the instruction on which error occured
ct--;
// filling exception with debug info
AlchemyException ae = (e instanceof AlchemyException) ? (AlchemyException)e : new AlchemyException(e);
if (dbgtable != null) {
int srcline = 0;
for (int i=1; i<dbgtable.length; i += 2) {
if (dbgtable[i+1] <= ct) srcline = dbgtable[i];
}
ae.addTraceElement(this, cpool[dbgtable[0]]+":"+srcline);
} else {
ae.addTraceElement(this, "+"+ct);
}
// catching or rethrowing
int jumpto = -1;
if (errtable != null) {
for (int i=0; i < errtable.length && jumpto < 0; i += 4)
if (ct >= errtable[i] && ct <= errtable[i+1]) {
jumpto = errtable[i+2];
head = errtable[i+3];
}
}
if (jumpto >= 0) {
stack[head] = ae;
ct = jumpto;
} else {
throw ae;
}
}
} /* the great while */
}
| public Object exec(Context c, Object[] args) throws AlchemyException {
//initializing
final Object[] stack = new Object[stacksize];
int head = -1;
final byte[] code = this.bcode;
Object[] locals;
if (args.length == localsize) {
locals = args;
} else {
locals = new Object[localsize];
System.arraycopy(args, 0, locals, 0, args.length);
}
int ct = 0;
while (true) {
try {
int instr = code[ct];
ct++;
switch (instr) {
// CONSTANTS
case Opcodes.ACONST_NULL: {
head++;
stack[head] = null;
break;
}
case Opcodes.ICONST_M1: {
head++;
stack[head] = Int.M_ONE;
break;
}
case Opcodes.ICONST_0: {
head++;
stack[head] = Int.ZERO;
break;
}
case Opcodes.ICONST_1: {
head++;
stack[head] = Int.ONE;
break;
}
case Opcodes.ICONST_2: {
head++;
stack[head] = Int.toInt(2);
break;
}
case Opcodes.ICONST_3: {
head++;
stack[head] = Int.toInt(3);
break;
}
case Opcodes.ICONST_4: {
head++;
stack[head] = Int.toInt(4);
break;
}
case Opcodes.ICONST_5: {
head++;
stack[head] = Int.toInt(5);
break;
}
case Opcodes.LCONST_0: {
head++;
stack[head] = Lval(0l);
break;
}
case Opcodes.LCONST_1: {
head++;
stack[head] = Lval(1l);
break;
}
case Opcodes.FCONST_0: {
head++;
stack[head] = Fval(0f);
break;
}
case Opcodes.FCONST_1: {
head++;
stack[head] = Fval(1f);
break;
}
case Opcodes.FCONST_2: {
head++;
stack[head] = Fval(2f);
break;
}
case Opcodes.DCONST_0: {
head++;
stack[head] = Dval(0d);
break;
}
case Opcodes.DCONST_1: {
head++;
stack[head] = Dval(1d);
break;
}
//CONVERSIONS
case Opcodes.I2L: {
stack[head] = Lval(ival(stack[head]));
break;
}
case Opcodes.I2F: {
stack[head] = Fval(ival(stack[head]));
break;
}
case Opcodes.I2D: {
stack[head] = Dval(ival(stack[head]));
break;
}
case Opcodes.L2F: {
stack[head] = Fval(lval(stack[head]));
break;
}
case Opcodes.L2D: {
stack[head] = Dval(lval(stack[head]));
break;
}
case Opcodes.L2I: {
stack[head] = Ival((int)lval(stack[head]));
break;
}
case Opcodes.F2D: {
stack[head] = Dval(fval(stack[head]));
break;
}
case Opcodes.F2I: {
stack[head] = Ival((int)fval(stack[head]));
break;
}
case Opcodes.F2L: {
stack[head] = Lval((long)fval(stack[head]));
break;
}
case Opcodes.D2I: {
stack[head] = Ival((int)dval(stack[head]));
break;
}
case Opcodes.D2L: {
stack[head] = Lval((long)dval(stack[head]));
break;
}
case Opcodes.D2F: {
stack[head] = Fval((float)dval(stack[head]));
break;
}
case Opcodes.I2C: {
stack[head] = Int.toInt((char)ival(stack[head]));
break;
}
case Opcodes.I2B: {
stack[head] = Int.toInt((byte)ival(stack[head]));
break;
}
case Opcodes.I2S: {
stack[head] = Int.toInt((short)ival(stack[head]));
break;
}
//INTEGER ARITHMETICS
case Opcodes.IADD: {
head--;
stack[head] = Ival(ival(stack[head]) + ival(stack[head+1]));
break;
}
case Opcodes.ISUB: {
head--;
stack[head] = Ival(ival(stack[head]) - ival(stack[head+1]));
break;
}
case Opcodes.IMUL: {
head--;
stack[head] = Ival(ival(stack[head]) * ival(stack[head+1]));
break;
}
case Opcodes.IDIV: {
head--;
stack[head] = Ival(ival(stack[head]) / ival(stack[head+1]));
break;
}
case Opcodes.IMOD: {
head--;
stack[head] = Ival(ival(stack[head]) % ival(stack[head+1]));
break;
}
case Opcodes.INEG: {
stack[head] = Ival(-ival(stack[head]));
break;
}
case Opcodes.ICMP: {
head--;
int itmp = ival(stack[head]) - ival(stack[head+1]);
stack[head] = (itmp > 0) ? Int.ONE : (itmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
case Opcodes.ISHL: {
head--;
stack[head] = Ival(ival(stack[head]) << ival(stack[head+1]));
break;
}
case Opcodes.ISHR: {
head--;
stack[head] = Ival(ival(stack[head]) >> ival(stack[head+1]));
break;
}
case Opcodes.IUSHR: {
head--;
stack[head] = Ival(ival(stack[head]) >>> ival(stack[head+1]));
break;
}
case Opcodes.IAND: {
head--;
stack[head] = Ival(ival(stack[head]) & ival(stack[head+1]));
break;
}
case Opcodes.IOR: {
head--;
stack[head] = Ival(ival(stack[head]) | ival(stack[head+1]));
break;
}
case Opcodes.IXOR: {
head--;
stack[head] = Ival(ival(stack[head]) ^ ival(stack[head+1]));
break;
}
//LONG ARITHMETICS
case Opcodes.LADD: {
head--;
stack[head] = Lval(lval(stack[head]) + lval(stack[head+1]));
break;
}
case Opcodes.LSUB: {
head--;
stack[head] = Lval(lval(stack[head]) - lval(stack[head+1]));
break;
}
case Opcodes.LMUL: {
head--;
stack[head] = Lval(lval(stack[head]) * lval(stack[head+1]));
break;
}
case Opcodes.LDIV: {
head--;
stack[head] = Lval(lval(stack[head]) / lval(stack[head+1]));
break;
}
case Opcodes.LMOD: {
head--;
stack[head] = Lval(lval(stack[head]) % lval(stack[head+1]));
break;
}
case Opcodes.LNEG: {
stack[head] = Lval(-lval(stack[head]));
break;
}
case Opcodes.LCMP: {
head--;
long ltmp = lval(stack[head]) - lval(stack[head+1]);
stack[head] = (ltmp > 0L) ? Int.ONE : (ltmp == 0L ? Int.ZERO : Int.M_ONE);
break;
}
case Opcodes.LSHL: {
head--;
stack[head] = Lval(lval(stack[head]) << ival(stack[head+1]));
break;
}
case Opcodes.LSHR: {
head--;
stack[head] = Lval(lval(stack[head]) >> ival(stack[head+1]));
break;
}
case Opcodes.LUSHR: {
head--;
stack[head] = Lval(lval(stack[head]) >>> ival(stack[head+1]));
break;
}
case Opcodes.LAND: {
head--;
stack[head] = Lval(lval(stack[head]) & lval(stack[head+1]));
break;
}
case Opcodes.LOR: {
head--;
stack[head] = Lval(lval(stack[head]) | lval(stack[head+1]));
break;
}
case Opcodes.LXOR: {
head--;
stack[head] = Lval(lval(stack[head]) ^ lval(stack[head+1]));
break;
}
//FLOAT ARITHMETICS
case Opcodes.FADD: {
head--;
stack[head] = Fval(fval(stack[head]) + fval(stack[head+1]));
break;
}
case Opcodes.FSUB: {
head--;
stack[head] = Fval(fval(stack[head]) - fval(stack[head+1]));
break;
}
case Opcodes.FMUL: {
head--;
stack[head] = Fval(fval(stack[head]) * fval(stack[head+1]));
break;
}
case Opcodes.FDIV: {
head--;
stack[head] = Fval(fval(stack[head]) / fval(stack[head+1]));
break;
}
case Opcodes.FMOD: {
head--;
stack[head] = Fval(fval(stack[head]) % fval(stack[head+1]));
break;
}
case Opcodes.FNEG: {
stack[head] = Fval(-fval(stack[head]));
break;
}
case Opcodes.FCMP: {
head--;
float ftmp = fval(stack[head]) - fval(stack[head+1]);
stack[head] = (ftmp > 0) ? Int.ONE : (ftmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
//DOUBLE ARITHMETICS
case Opcodes.DADD: {
head--;
stack[head] = Dval(dval(stack[head]) + dval(stack[head+1]));
break;
}
case Opcodes.DSUB: {
head--;
stack[head] = Dval(dval(stack[head]) - dval(stack[head+1]));
break;
}
case Opcodes.DMUL: {
head--;
stack[head] = Dval(dval(stack[head]) * dval(stack[head+1]));
break;
}
case Opcodes.DDIV: {
head--;
stack[head] = Dval(dval(stack[head]) / dval(stack[head+1]));
break;
}
case Opcodes.DMOD: {
head--;
stack[head] = Dval(dval(stack[head]) % dval(stack[head+1]));
break;
}
case Opcodes.DNEG: {
stack[head] = Dval(-dval(stack[head]));
break;
}
case Opcodes.DCMP: {
head--;
double dtmp = dval(stack[head]) - dval(stack[head+1]);
stack[head] = (dtmp > 0) ? Int.ONE : (dtmp == 0 ? Int.ZERO : Int.M_ONE);
break;
}
//LOCALS LOADERS AND SAVERS
case Opcodes.LOAD_0:
case Opcodes.LOAD_1:
case Opcodes.LOAD_2:
case Opcodes.LOAD_3:
case Opcodes.LOAD_4:
case Opcodes.LOAD_5:
case Opcodes.LOAD_6:
case Opcodes.LOAD_7: {
head++;
stack[head] = locals[instr & 7];
break;
}
case Opcodes.LOAD: { //load <ubyte>
head++;
stack[head] = locals[code[ct] & 0xff];
ct++;
break;
}
//variable savers
case Opcodes.STORE_0:
case Opcodes.STORE_1:
case Opcodes.STORE_2:
case Opcodes.STORE_3:
case Opcodes.STORE_4:
case Opcodes.STORE_5:
case Opcodes.STORE_6:
case Opcodes.STORE_7: {
locals[instr & 7] = stack[head];
head--;
break;
}
case Opcodes.STORE: { //store <ubyte>
locals[code[ct] & 0xff] = stack[head];
ct++;
head--;
break;
}
//BRANCHING
case Opcodes.IFEQ: { //ifeq <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) == 0) ct = itmp;
head--;
break;
}
case Opcodes.IFNE: { //ifne <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) != 0) ct = itmp;
head--;
break;
}
case Opcodes.IFLT: { //iflt <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) < 0) ct = itmp;
head--;
break;
}
case Opcodes.IFGE: { //ifge <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) >= 0) ct = itmp;
head--;
break;
}
case Opcodes.IFGT: { //ifgt <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) > 0) ct = itmp;
head--;
break;
}
case Opcodes.IFLE: { //ifle <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head]) <= 0) ct = itmp;
head--;
break;
}
case Opcodes.GOTO: { //goto <ushort>
ct = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
break;
}
case Opcodes.IFNULL: { //ifnull <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (stack[head] == null) ct = itmp;
head--;
break;
}
case Opcodes.IFNNULL: { //ifnnull <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (stack[head] != null) ct = itmp;
head--;
break;
}
case Opcodes.IF_ICMPLT: { //if_icmplt <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head-1]) < ival(stack[head])) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ICMPGE: { //if_icmpge <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head-1]) >= ival(stack[head])) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ICMPGT: { //if_icmpgt <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head-1]) > ival(stack[head])) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ICMPLE: { //if_icmple <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (ival(stack[head-1]) <= ival(stack[head])) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ACMPEQ: { //if_acmpeq <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (stack[head-1] != null
? stack[head-1].equals(stack[head])
: stack[head] == null) ct = itmp;
head -= 2;
break;
}
case Opcodes.IF_ACMPNE: { //if_acmpne <ushort>
int itmp = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
ct += 2;
if (stack[head-1] != null
? !stack[head-1].equals(stack[head])
: stack[head] != null) ct = itmp;
head -= 2;
break;
}
case Opcodes.JSR: { //jsr <ushort>
head++;
stack[head] = Ival(ct+2);
ct = (code[ct] & 0xff) << 8 | (code[ct+1] & 0xff);
break;
}
case Opcodes.RET: { //ret
ct = ival(stack[head]);
head--;
break;
}
//FUNCTION CALLS
case Opcodes.CALL_0:
case Opcodes.CALL_1:
case Opcodes.CALL_2:
case Opcodes.CALL_3:
case Opcodes.CALL_4:
case Opcodes.CALL_5:
case Opcodes.CALL_6:
case Opcodes.CALL_7:
case Opcodes.CALV_0:
case Opcodes.CALV_1:
case Opcodes.CALV_2:
case Opcodes.CALV_3:
case Opcodes.CALV_4:
case Opcodes.CALV_5:
case Opcodes.CALV_6:
case Opcodes.CALV_7: {
int paramlen = instr & 7;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
stack[head] = ((Function)stack[head]).exec(c, params);
if ((instr & 8) != 0) head--;
break;
}
case Opcodes.CALL: {//call <ubyte>
int paramlen = code[ct] & 0xff;
ct++;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
stack[head] = ((Function)stack[head]).exec(c, params);
break;
}
case Opcodes.CALV: {//calv <ubyte>
int paramlen = code[ct] & 0xff;
ct++;
Object[] params = new Object[paramlen];
head -= paramlen;
System.arraycopy(stack, head+1, params, 0, paramlen);
((Function)stack[head]).exec(c, params);
head--;
break;
}
//ARRAY INSTRUCTIONS
case Opcodes.NEWAA: {
stack[head] = new Object[ival(stack[head])];
break;
}
case Opcodes.NEWBA: {
stack[head] = new byte[ival(stack[head])];
break;
}
case Opcodes.NEWCA: {
stack[head] = new char[ival(stack[head])];
break;
}
case Opcodes.NEWZA: {
stack[head] = new boolean[ival(stack[head])];
break;
}
case Opcodes.NEWSA: {
stack[head] = new short[ival(stack[head])];
break;
}
case Opcodes.NEWIA: {
stack[head] = new int[ival(stack[head])];
break;
}
case Opcodes.NEWLA: {
stack[head] = new long[ival(stack[head])];
break;
}
case Opcodes.NEWFA: {
stack[head] = new float[ival(stack[head])];
break;
}
case Opcodes.NEWDA: {
stack[head] = new double[ival(stack[head])];
break;
}
case Opcodes.AALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = ((Object[])stack[head])[at];
break;
}
case Opcodes.BALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((byte[])stack[head])[at] );
break;
}
case Opcodes.CALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((char[])stack[head])[at] );
break;
}
case Opcodes.ZALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((boolean[])stack[head])[at] );
break;
}
case Opcodes.SALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((short[])stack[head])[at] );
break;
}
case Opcodes.IALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Ival( ((int[])stack[head])[at] );
break;
}
case Opcodes.LALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Lval( ((long[])stack[head])[at] );
break;
}
case Opcodes.FALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Fval( ((float[])stack[head])[at] );
break;
}
case Opcodes.DALOAD: {
int at = ival(stack[head]);
head--;
stack[head] = Dval( ((double[])stack[head])[at] );
break;
}
case Opcodes.AASTORE: {
Object val = stack[head];
int at = ival(stack[head-1]);
Object[] array = (Object[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.BASTORE: {
int val = ival(stack[head]);
int at = ival(stack[head-1]);
byte[] array = (byte[])stack[head-2];
array[at] = (byte)val;
head -= 3;
break;
}
case Opcodes.CASTORE: {
char val = (char) ival(stack[head]);
int at = ival(stack[head-1]);
char[] array = (char[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.ZASTORE: {
boolean val = bval(stack[head]);
int at = ival(stack[head-1]);
boolean[] array = (boolean[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.SASTORE: {
short val = (short)ival(stack[head]);
int at = ival(stack[head-1]);
short[] array = (short[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.IASTORE: {
int val = ival(stack[head]);
int at = ival(stack[head-1]);
int[] array = (int[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.FASTORE: {
float val = fval(stack[head]);
int at = ival(stack[head-1]);
float[] array = (float[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.DASTORE: {
double val = dval(stack[head]);
int at = ival(stack[head-1]);
double[] array = (double[])stack[head-2];
array[at] = val;
head -= 3;
break;
}
case Opcodes.AALEN: {
stack[head] = Ival(((Object[])stack[head]).length);
break;
}
case Opcodes.BALEN: {
stack[head] = Ival(((byte[])stack[head]).length);
break;
}
case Opcodes.CALEN: {
stack[head] = Ival(((char[])stack[head]).length);
break;
}
case Opcodes.ZALEN: {
stack[head] = Ival(((boolean[])stack[head]).length);
break;
}
case Opcodes.SALEN: {
stack[head] = Ival(((short[])stack[head]).length);
break;
}
case Opcodes.IALEN: {
stack[head] = Ival(((int[])stack[head]).length);
break;
}
case Opcodes.LALEN: {
stack[head] = Ival(((long[])stack[head]).length);
break;
}
case Opcodes.FALEN: {
stack[head] = Ival(((float[])stack[head]).length);
break;
}
case Opcodes.DALEN: {
stack[head] = Ival(((double[])stack[head]).length);
break;
}
//SWITCH BRANCHING
case Opcodes.TABLESWITCH: {
int dflt = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
ct += 2;
int min = (code[ct] << 24)
| ((code[ct+1] & 0xff) << 16)
| ((code[ct+2] & 0xff) << 8)
| (code[ct+3] & 0xff);
ct += 4;
int max = (code[ct] << 24)
| ((code[ct+1] & 0xff) << 16)
| ((code[ct+2] & 0xff) << 8)
| (code[ct+3] & 0xff);
ct += 4;
int val = ival(stack[head]);
head--;
if (val >= min && val <= max) {
ct += (val-min)*2;
ct = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
} else {
ct = dflt;
}
break;
}
case Opcodes.LOOKUPSWITCH: {
int dflt = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
ct += 2;
int count = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
ct += 2;
int val = ival(stack[head]);
head--;
boolean matched = false;
for (int i=0; i<count && !matched; i++) {
int cand = (code[ct] << 24)
| ((code[ct+1] & 0xff) << 16)
| ((code[ct+2] & 0xff) << 8)
| (code[ct+3] & 0xff);
ct += 4;
if (val == cand) {
ct = ((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff);
matched = true;
} else {
ct += 2;
}
}
if (!matched) ct = dflt;
break;
}
//OTHERS
case Opcodes.ACMP: {
head--;
boolean eq = (stack[head] == null) ? stack[head+1] == null : stack[head].equals(stack[head+1]);
stack[head] = Ival(!eq);
break;
}
case Opcodes.RET_NULL:
return null;
case Opcodes.RETURN:
return stack[head];
case Opcodes.DUP: {
stack[head+1] = stack[head];
head++;
break;
}
case Opcodes.DUP2: {
stack[head+2] = stack[head];
stack[head+1] = stack[head-1];
head += 2;
break;
}
case Opcodes.SWAP: {
Object atmp = stack[head-1];
stack[head-1] = stack[head];
stack[head] = atmp;
break;
}
case Opcodes.LDC: { //ldc <ushort>
head++;
stack[head] = cpool[((code[ct] & 0xff) << 8) | (code[ct+1] & 0xff)];
ct += 2;
break;
}
case Opcodes.POP: {
head--;
break;
}
case Opcodes.BIPUSH: { //bipush <byte>
head++;
stack[head] = Ival(code[ct]);
ct++;
break;
}
case Opcodes.SIPUSH: { //sipush <short>
head++;
stack[head] = Ival((code[ct] << 8) | (code[ct+1]& 0xff));
ct += 2;
break;
}
case Opcodes.IINC: { //iinc <ubyte> <byte>
int idx = code[ct] & 0xff;
ct++;
int inc = code[ct] & 0xff;
ct++;
locals[idx] = Int.toInt(((Int)locals[idx]).value + inc);
}
} /* the big switch */
} catch (Throwable e) {
// the instruction on which error occured
ct--;
// filling exception with debug info
AlchemyException ae = (e instanceof AlchemyException) ? (AlchemyException)e : new AlchemyException(e);
if (dbgtable != null) {
int srcline = 0;
for (int i=1; i<dbgtable.length; i += 2) {
if (dbgtable[i+1] <= ct) srcline = dbgtable[i];
}
ae.addTraceElement(this, cpool[dbgtable[0]]+":"+srcline);
} else {
ae.addTraceElement(this, "+"+ct);
}
// catching or rethrowing
int jumpto = -1;
if (errtable != null) {
for (int i=0; i < errtable.length && jumpto < 0; i += 4)
if (ct >= errtable[i] && ct <= errtable[i+1]) {
jumpto = errtable[i+2];
head = errtable[i+3];
}
}
if (jumpto >= 0) {
stack[head] = ae;
ct = jumpto;
} else {
throw ae;
}
}
} /* the great while */
}
|
diff --git a/src/main/java/com/janrain/backplane2/server/AuthorizationRequest.java b/src/main/java/com/janrain/backplane2/server/AuthorizationRequest.java
index 1a85975..2df452f 100644
--- a/src/main/java/com/janrain/backplane2/server/AuthorizationRequest.java
+++ b/src/main/java/com/janrain/backplane2/server/AuthorizationRequest.java
@@ -1,105 +1,106 @@
package com.janrain.backplane2.server;
import com.janrain.commons.supersimpledb.message.AbstractMessage;
import com.janrain.commons.supersimpledb.message.MessageField;
import org.apache.commons.lang.StringUtils;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.EnumSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
/**
* @author Johnny Bufu
*/
public class AuthorizationRequest extends AbstractMessage {
// - PUBLIC
/**
* Empty default constructor for AWS to use
*/
public AuthorizationRequest() { }
public AuthorizationRequest(String cookie, String configuredRedirectUri, Map parameterMap) {
Map<String,String> data = new LinkedHashMap<String, String>();
+ data.put(Field.COOKIE.getFieldName(), cookie);
for(Field f: EnumSet.allOf(Field.class)) {
Object value = parameterMap.get(f.getFieldName().toLowerCase());
- if (value instanceof String && StringUtils.isNotEmpty((String) value)) {
- data.put(f.getFieldName(), (String) value);
+ if ( value != null && ((String[]) value).length > 0 && StringUtils.isNotEmpty(((String[])value)[0])) {
+ data.put(f.getFieldName(), ((String[])value)[0]);
}
}
if(StringUtils.isEmpty(get(Field.REDIRECT_URI))) {
data.put(Field.REDIRECT_URI.getFieldName(), configuredRedirectUri);
}
super.init(cookie, data);
}
@Override
public String getIdValue() {
return get(Field.COOKIE);
}
@Override
public Set<? extends MessageField> getFields() {
return EnumSet.allOf(Field.class);
}
public static enum Field implements MessageField {
// - PUBLIC
COOKIE,
CLIENT_ID,
RESPONSE_TYPE {
@Override
public void validate(String value) throws RuntimeException {
super.validate(value);
if (! "authorization_code".equals(value)) {
throw new IllegalArgumentException("Unsupported OAuth2 response_type: " + value);
}
}
},
REDIRECT_URI {
@Override
public void validate(String value) throws RuntimeException {
super.validate(value);
try {
new URL(value);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("Invalid redirect_uri value: " + e.getMessage());
}
}
},
SCOPE(false),
STATE(false);
@Override
public String getFieldName() {
return name();
}
@Override
public boolean isRequired() {
return required;
}
@Override
public void validate(String value) throws RuntimeException {
if (isRequired()) validateNotNull(name(), value);
}
// - PRIVATE
private final boolean required;
private Field() {
this(true);
}
private Field(boolean requried) {
this.required = requried;
}
}
}
| false | true | public AuthorizationRequest(String cookie, String configuredRedirectUri, Map parameterMap) {
Map<String,String> data = new LinkedHashMap<String, String>();
for(Field f: EnumSet.allOf(Field.class)) {
Object value = parameterMap.get(f.getFieldName().toLowerCase());
if (value instanceof String && StringUtils.isNotEmpty((String) value)) {
data.put(f.getFieldName(), (String) value);
}
}
if(StringUtils.isEmpty(get(Field.REDIRECT_URI))) {
data.put(Field.REDIRECT_URI.getFieldName(), configuredRedirectUri);
}
super.init(cookie, data);
}
| public AuthorizationRequest(String cookie, String configuredRedirectUri, Map parameterMap) {
Map<String,String> data = new LinkedHashMap<String, String>();
data.put(Field.COOKIE.getFieldName(), cookie);
for(Field f: EnumSet.allOf(Field.class)) {
Object value = parameterMap.get(f.getFieldName().toLowerCase());
if ( value != null && ((String[]) value).length > 0 && StringUtils.isNotEmpty(((String[])value)[0])) {
data.put(f.getFieldName(), ((String[])value)[0]);
}
}
if(StringUtils.isEmpty(get(Field.REDIRECT_URI))) {
data.put(Field.REDIRECT_URI.getFieldName(), configuredRedirectUri);
}
super.init(cookie, data);
}
|
diff --git a/activemq-broker/src/main/java/org/apache/activemq/broker/BrokerService.java b/activemq-broker/src/main/java/org/apache/activemq/broker/BrokerService.java
index 51270592a..6f6f7522e 100644
--- a/activemq-broker/src/main/java/org/apache/activemq/broker/BrokerService.java
+++ b/activemq-broker/src/main/java/org/apache/activemq/broker/BrokerService.java
@@ -1,2898 +1,2898 @@
/**
* 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.activemq.broker;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.UnknownHostException;
import java.security.Provider;
import java.security.Security;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import org.apache.activemq.ActiveMQConnectionMetaData;
import org.apache.activemq.ConfigurationException;
import org.apache.activemq.Service;
import org.apache.activemq.advisory.AdvisoryBroker;
import org.apache.activemq.broker.cluster.ConnectionSplitBroker;
import org.apache.activemq.broker.jmx.*;
import org.apache.activemq.broker.region.CompositeDestinationInterceptor;
import org.apache.activemq.broker.region.Destination;
import org.apache.activemq.broker.region.DestinationFactory;
import org.apache.activemq.broker.region.DestinationFactoryImpl;
import org.apache.activemq.broker.region.DestinationInterceptor;
import org.apache.activemq.broker.region.RegionBroker;
import org.apache.activemq.broker.region.policy.PolicyMap;
import org.apache.activemq.broker.region.virtual.MirroredQueue;
import org.apache.activemq.broker.region.virtual.VirtualDestination;
import org.apache.activemq.broker.region.virtual.VirtualDestinationInterceptor;
import org.apache.activemq.broker.region.virtual.VirtualTopic;
import org.apache.activemq.broker.scheduler.JobSchedulerStore;
import org.apache.activemq.broker.scheduler.SchedulerBroker;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.BrokerId;
import org.apache.activemq.command.ProducerInfo;
import org.apache.activemq.filter.DestinationFilter;
import org.apache.activemq.network.ConnectionFilter;
import org.apache.activemq.network.DiscoveryNetworkConnector;
import org.apache.activemq.network.NetworkConnector;
import org.apache.activemq.network.jms.JmsConnector;
import org.apache.activemq.openwire.OpenWireFormat;
import org.apache.activemq.proxy.ProxyConnector;
import org.apache.activemq.security.MessageAuthorizationPolicy;
import org.apache.activemq.selector.SelectorParser;
import org.apache.activemq.store.JournaledStore;
import org.apache.activemq.store.PListStore;
import org.apache.activemq.store.PersistenceAdapter;
import org.apache.activemq.store.PersistenceAdapterFactory;
import org.apache.activemq.store.memory.MemoryPersistenceAdapter;
import org.apache.activemq.thread.Scheduler;
import org.apache.activemq.thread.TaskRunnerFactory;
import org.apache.activemq.transport.TransportFactorySupport;
import org.apache.activemq.transport.TransportServer;
import org.apache.activemq.transport.vm.VMTransportFactory;
import org.apache.activemq.usage.SystemUsage;
import org.apache.activemq.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
/**
* Manages the lifecycle of an ActiveMQ Broker. A BrokerService consists of a
* number of transport connectors, network connectors and a bunch of properties
* which can be used to configure the broker as its lazily created.
*
*
* @org.apache.xbean.XBean
*/
public class BrokerService implements Service {
public static final String DEFAULT_PORT = "61616";
public static final String LOCAL_HOST_NAME;
public static final String BROKER_VERSION;
public static final String DEFAULT_BROKER_NAME = "localhost";
public static final int DEFAULT_MAX_FILE_LENGTH = 1024 * 1024 * 32;
private static final Logger LOG = LoggerFactory.getLogger(BrokerService.class);
private static final long serialVersionUID = 7353129142305630237L;
private boolean useJmx = true;
private boolean enableStatistics = true;
private boolean persistent = true;
private boolean populateJMSXUserID;
private boolean useAuthenticatedPrincipalForJMSXUserID;
private boolean populateUserNameInMBeans;
private long mbeanInvocationTimeout = 0;
private boolean useShutdownHook = true;
private boolean useLoggingForShutdownErrors;
private boolean shutdownOnMasterFailure;
private boolean shutdownOnSlaveFailure;
private boolean waitForSlave;
private long waitForSlaveTimeout = 600000L;
private boolean passiveSlave;
private String brokerName = DEFAULT_BROKER_NAME;
private File dataDirectoryFile;
private File tmpDataDirectory;
private Broker broker;
private BrokerView adminView;
private ManagementContext managementContext;
private ObjectName brokerObjectName;
private TaskRunnerFactory taskRunnerFactory;
private TaskRunnerFactory persistenceTaskRunnerFactory;
private SystemUsage systemUsage;
private SystemUsage producerSystemUsage;
private SystemUsage consumerSystemUsaage;
private PersistenceAdapter persistenceAdapter;
private PersistenceAdapterFactory persistenceFactory;
protected DestinationFactory destinationFactory;
private MessageAuthorizationPolicy messageAuthorizationPolicy;
private final List<TransportConnector> transportConnectors = new CopyOnWriteArrayList<TransportConnector>();
private final List<NetworkConnector> networkConnectors = new CopyOnWriteArrayList<NetworkConnector>();
private final List<ProxyConnector> proxyConnectors = new CopyOnWriteArrayList<ProxyConnector>();
private final List<JmsConnector> jmsConnectors = new CopyOnWriteArrayList<JmsConnector>();
private final List<Service> services = new ArrayList<Service>();
private transient Thread shutdownHook;
private String[] transportConnectorURIs;
private String[] networkConnectorURIs;
private JmsConnector[] jmsBridgeConnectors; // these are Jms to Jms bridges
// to other jms messaging systems
private boolean deleteAllMessagesOnStartup;
private boolean advisorySupport = true;
private URI vmConnectorURI;
private String defaultSocketURIString;
private PolicyMap destinationPolicy;
private final AtomicBoolean started = new AtomicBoolean(false);
private final AtomicBoolean stopped = new AtomicBoolean(false);
private final AtomicBoolean stopping = new AtomicBoolean(false);
private BrokerPlugin[] plugins;
private boolean keepDurableSubsActive = true;
private boolean useVirtualTopics = true;
private boolean useMirroredQueues = false;
private boolean useTempMirroredQueues = true;
private BrokerId brokerId;
private DestinationInterceptor[] destinationInterceptors;
private ActiveMQDestination[] destinations;
private PListStore tempDataStore;
private int persistenceThreadPriority = Thread.MAX_PRIORITY;
private boolean useLocalHostBrokerName;
private final CountDownLatch stoppedLatch = new CountDownLatch(1);
private final CountDownLatch startedLatch = new CountDownLatch(1);
private boolean supportFailOver;
private Broker regionBroker;
private int producerSystemUsagePortion = 60;
private int consumerSystemUsagePortion = 40;
private boolean splitSystemUsageForProducersConsumers;
private boolean monitorConnectionSplits = false;
private int taskRunnerPriority = Thread.NORM_PRIORITY;
private boolean dedicatedTaskRunner;
private boolean cacheTempDestinations = false;// useful for failover
private int timeBeforePurgeTempDestinations = 5000;
private final List<Runnable> shutdownHooks = new ArrayList<Runnable>();
private boolean systemExitOnShutdown;
private int systemExitOnShutdownExitCode;
private SslContext sslContext;
private boolean forceStart = false;
private IOExceptionHandler ioExceptionHandler;
private boolean schedulerSupport = false;
private File schedulerDirectoryFile;
private Scheduler scheduler;
private ThreadPoolExecutor executor;
private int schedulePeriodForDestinationPurge= 0;
private int maxPurgedDestinationsPerSweep = 0;
private BrokerContext brokerContext;
private boolean networkConnectorStartAsync = false;
private boolean allowTempAutoCreationOnSend;
private JobSchedulerStore jobSchedulerStore;
private long offlineDurableSubscriberTimeout = -1;
private long offlineDurableSubscriberTaskSchedule = 300000;
private DestinationFilter virtualConsumerDestinationFilter;
private final Object persistenceAdapterLock = new Object();
private Throwable startException = null;
private boolean startAsync = false;
private Date startDate;
private boolean slave = true;
private boolean restartAllowed = true;
private boolean restartRequested = false;
private int storeOpenWireVersion = OpenWireFormat.DEFAULT_VERSION;
static {
try {
ClassLoader loader = BrokerService.class.getClassLoader();
Class<?> clazz = loader.loadClass("org.bouncycastle.jce.provider.BouncyCastleProvider");
Provider bouncycastle = (Provider) clazz.newInstance();
Security.insertProviderAt(bouncycastle, 2);
LOG.info("Loaded the Bouncy Castle security provider.");
} catch(Throwable e) {
// No BouncyCastle found so we use the default Java Security Provider
}
String localHostName = "localhost";
try {
localHostName = InetAddressUtil.getLocalHostName();
} catch (UnknownHostException e) {
LOG.error("Failed to resolve localhost");
}
LOCAL_HOST_NAME = localHostName;
InputStream in = null;
String version = null;
if ((in = BrokerService.class.getResourceAsStream("/org/apache/activemq/version.txt")) != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
try {
version = reader.readLine();
} catch(Exception e) {
}
}
BROKER_VERSION = version;
}
@Override
public String toString() {
return "BrokerService[" + getBrokerName() + "]";
}
private String getBrokerVersion() {
String version = ActiveMQConnectionMetaData.PROVIDER_VERSION;
if (version == null) {
version = BROKER_VERSION;
}
return version;
}
/**
* Adds a new transport connector for the given bind address
*
* @return the newly created and added transport connector
* @throws Exception
*/
public TransportConnector addConnector(String bindAddress) throws Exception {
return addConnector(new URI(bindAddress));
}
/**
* Adds a new transport connector for the given bind address
*
* @return the newly created and added transport connector
* @throws Exception
*/
public TransportConnector addConnector(URI bindAddress) throws Exception {
return addConnector(createTransportConnector(bindAddress));
}
/**
* Adds a new transport connector for the given TransportServer transport
*
* @return the newly created and added transport connector
* @throws Exception
*/
public TransportConnector addConnector(TransportServer transport) throws Exception {
return addConnector(new TransportConnector(transport));
}
/**
* Adds a new transport connector
*
* @return the transport connector
* @throws Exception
*/
public TransportConnector addConnector(TransportConnector connector) throws Exception {
transportConnectors.add(connector);
return connector;
}
/**
* Stops and removes a transport connector from the broker.
*
* @param connector
* @return true if the connector has been previously added to the broker
* @throws Exception
*/
public boolean removeConnector(TransportConnector connector) throws Exception {
boolean rc = transportConnectors.remove(connector);
if (rc) {
unregisterConnectorMBean(connector);
}
return rc;
}
/**
* Adds a new network connector using the given discovery address
*
* @return the newly created and added network connector
* @throws Exception
*/
public NetworkConnector addNetworkConnector(String discoveryAddress) throws Exception {
return addNetworkConnector(new URI(discoveryAddress));
}
/**
* Adds a new proxy connector using the given bind address
*
* @return the newly created and added network connector
* @throws Exception
*/
public ProxyConnector addProxyConnector(String bindAddress) throws Exception {
return addProxyConnector(new URI(bindAddress));
}
/**
* Adds a new network connector using the given discovery address
*
* @return the newly created and added network connector
* @throws Exception
*/
public NetworkConnector addNetworkConnector(URI discoveryAddress) throws Exception {
NetworkConnector connector = new DiscoveryNetworkConnector(discoveryAddress);
return addNetworkConnector(connector);
}
/**
* Adds a new proxy connector using the given bind address
*
* @return the newly created and added network connector
* @throws Exception
*/
public ProxyConnector addProxyConnector(URI bindAddress) throws Exception {
ProxyConnector connector = new ProxyConnector();
connector.setBind(bindAddress);
connector.setRemote(new URI("fanout:multicast://default"));
return addProxyConnector(connector);
}
/**
* Adds a new network connector to connect this broker to a federated
* network
*/
public NetworkConnector addNetworkConnector(NetworkConnector connector) throws Exception {
connector.setBrokerService(this);
URI uri = getVmConnectorURI();
Map<String, String> map = new HashMap<String, String>(URISupport.parseParameters(uri));
map.put("network", "true");
uri = URISupport.createURIWithQuery(uri, URISupport.createQueryString(map));
connector.setLocalUri(uri);
// Set a connection filter so that the connector does not establish loop
// back connections.
connector.setConnectionFilter(new ConnectionFilter() {
@Override
public boolean connectTo(URI location) {
List<TransportConnector> transportConnectors = getTransportConnectors();
for (Iterator<TransportConnector> iter = transportConnectors.iterator(); iter.hasNext();) {
try {
TransportConnector tc = iter.next();
if (location.equals(tc.getConnectUri())) {
return false;
}
} catch (Throwable e) {
}
}
return true;
}
});
networkConnectors.add(connector);
return connector;
}
/**
* Removes the given network connector without stopping it. The caller
* should call {@link NetworkConnector#stop()} to close the connector
*/
public boolean removeNetworkConnector(NetworkConnector connector) {
boolean answer = networkConnectors.remove(connector);
if (answer) {
unregisterNetworkConnectorMBean(connector);
}
return answer;
}
public ProxyConnector addProxyConnector(ProxyConnector connector) throws Exception {
URI uri = getVmConnectorURI();
connector.setLocalUri(uri);
proxyConnectors.add(connector);
if (isUseJmx()) {
registerProxyConnectorMBean(connector);
}
return connector;
}
public JmsConnector addJmsConnector(JmsConnector connector) throws Exception {
connector.setBrokerService(this);
jmsConnectors.add(connector);
if (isUseJmx()) {
registerJmsConnectorMBean(connector);
}
return connector;
}
public JmsConnector removeJmsConnector(JmsConnector connector) {
if (jmsConnectors.remove(connector)) {
return connector;
}
return null;
}
public void masterFailed() {
if (shutdownOnMasterFailure) {
LOG.error("The Master has failed ... shutting down");
try {
stop();
} catch (Exception e) {
LOG.error("Failed to stop for master failure", e);
}
} else {
LOG.warn("Master Failed - starting all connectors");
try {
startAllConnectors();
broker.nowMasterBroker();
} catch (Exception e) {
LOG.error("Failed to startAllConnectors", e);
}
}
}
public String getUptime() {
// compute and log uptime
if (startDate == null) {
return "not started";
}
long delta = new Date().getTime() - startDate.getTime();
return TimeUtils.printDuration(delta);
}
public boolean isStarted() {
return started.get() && startedLatch.getCount() == 0;
}
/**
* Forces a start of the broker.
* By default a BrokerService instance that was
* previously stopped using BrokerService.stop() cannot be restarted
* using BrokerService.start().
* This method enforces a restart.
* It is not recommended to force a restart of the broker and will not work
* for most but some very trivial broker configurations.
* For restarting a broker instance we recommend to first call stop() on
* the old instance and then recreate a new BrokerService instance.
*
* @param force - if true enforces a restart.
* @throws Exception
*/
public void start(boolean force) throws Exception {
forceStart = force;
stopped.set(false);
started.set(false);
start();
}
// Service interface
// -------------------------------------------------------------------------
protected boolean shouldAutostart() {
return true;
}
/**
*
* @throws Exception
* @org. apache.xbean.InitMethod
*/
@PostConstruct
public void autoStart() throws Exception {
if(shouldAutostart()) {
start();
}
}
@Override
public void start() throws Exception {
if (stopped.get() || !started.compareAndSet(false, true)) {
// lets just ignore redundant start() calls
// as its way too easy to not be completely sure if start() has been
// called or not with the gazillion of different configuration
// mechanisms
// throw new IllegalStateException("Already started.");
return;
}
stopping.set(false);
startDate = new Date();
MDC.put("activemq.broker", brokerName);
try {
if (systemExitOnShutdown && useShutdownHook) {
throw new ConfigurationException("'useShutdownHook' property cannot be be used with 'systemExitOnShutdown', please turn it off (useShutdownHook=false)");
}
processHelperProperties();
if (isUseJmx()) {
// need to remove MDC during starting JMX, as that would otherwise causes leaks, as spawned threads inheirt the MDC and
// we cannot cleanup clear that during shutdown of the broker.
MDC.remove("activemq.broker");
try {
startManagementContext();
for (NetworkConnector connector : getNetworkConnectors()) {
registerNetworkConnectorMBean(connector);
}
} finally {
MDC.put("activemq.broker", brokerName);
}
}
// in jvm master slave, lets not publish over existing broker till we get the lock
final BrokerRegistry brokerRegistry = BrokerRegistry.getInstance();
if (brokerRegistry.lookup(getBrokerName()) == null) {
brokerRegistry.bind(getBrokerName(), BrokerService.this);
}
startPersistenceAdapter(startAsync);
startBroker(startAsync);
brokerRegistry.bind(getBrokerName(), BrokerService.this);
} catch (Exception e) {
LOG.error("Failed to start Apache ActiveMQ (" + getBrokerName() + ", " + brokerId + "). Reason: " + e, e);
try {
if (!stopped.get()) {
stop();
}
} catch (Exception ex) {
LOG.warn("Failed to stop broker after failure in start. This exception will be ignored.", ex);
}
throw e;
} finally {
MDC.remove("activemq.broker");
}
}
private void startPersistenceAdapter(boolean async) throws Exception {
if (async) {
new Thread("Persistence Adapter Starting Thread") {
@Override
public void run() {
try {
doStartPersistenceAdapter();
} catch (Throwable e) {
startException = e;
} finally {
synchronized (persistenceAdapterLock) {
persistenceAdapterLock.notifyAll();
}
}
}
}.start();
} else {
doStartPersistenceAdapter();
}
}
private void doStartPersistenceAdapter() throws Exception {
getPersistenceAdapter().setUsageManager(getProducerSystemUsage());
getPersistenceAdapter().setBrokerName(getBrokerName());
LOG.info("Using Persistence Adapter: " + getPersistenceAdapter());
if (deleteAllMessagesOnStartup) {
deleteAllMessages();
}
getPersistenceAdapter().start();
}
private void startBroker(boolean async) throws Exception {
if (async) {
new Thread("Broker Starting Thread") {
@Override
public void run() {
try {
synchronized (persistenceAdapterLock) {
persistenceAdapterLock.wait();
}
doStartBroker();
} catch (Throwable t) {
startException = t;
}
}
}.start();
} else {
doStartBroker();
}
}
private void doStartBroker() throws Exception {
if (startException != null) {
return;
}
startDestinations();
addShutdownHook();
broker = getBroker();
brokerId = broker.getBrokerId();
// need to log this after creating the broker so we have its id and name
if (LOG.isInfoEnabled()) {
LOG.info("Apache ActiveMQ " + getBrokerVersion() + " ("
+ getBrokerName() + ", " + brokerId + ") is starting");
}
broker.start();
if (isUseJmx()) {
if (getManagementContext().isCreateConnector() && !getManagementContext().isConnectorStarted()) {
// try to restart management context
// typical for slaves that use the same ports as master
managementContext.stop();
startManagementContext();
}
ManagedRegionBroker managedBroker = (ManagedRegionBroker) regionBroker;
managedBroker.setContextBroker(broker);
adminView.setBroker(managedBroker);
}
if (ioExceptionHandler == null) {
setIoExceptionHandler(new DefaultIOExceptionHandler());
}
startAllConnectors();
if (LOG.isInfoEnabled()) {
LOG.info("Apache ActiveMQ " + getBrokerVersion() + " ("
+ getBrokerName() + ", " + brokerId + ") started");
LOG.info("For help or more information please see: http://activemq.apache.org");
}
getBroker().brokerServiceStarted();
checkSystemUsageLimits();
startedLatch.countDown();
getBroker().nowMasterBroker();
}
/**
*
* @throws Exception
* @org.apache .xbean.DestroyMethod
*/
@Override
@PreDestroy
public void stop() throws Exception {
if (!stopping.compareAndSet(false, true)) {
LOG.trace("Broker already stopping/stopped");
return;
}
MDC.put("activemq.broker", brokerName);
if (systemExitOnShutdown) {
new Thread() {
@Override
public void run() {
System.exit(systemExitOnShutdownExitCode);
}
}.start();
}
if (LOG.isInfoEnabled()) {
LOG.info("Apache ActiveMQ " + getBrokerVersion() + " ("
+ getBrokerName() + ", " + brokerId + ") is shutting down");
}
removeShutdownHook();
if (this.scheduler != null) {
this.scheduler.stop();
this.scheduler = null;
}
ServiceStopper stopper = new ServiceStopper();
if (services != null) {
for (Service service : services) {
stopper.stop(service);
}
}
stopAllConnectors(stopper);
this.slave = true;
// remove any VMTransports connected
// this has to be done after services are stopped,
// to avoid timing issue with discovery (spinning up a new instance)
BrokerRegistry.getInstance().unbind(getBrokerName());
VMTransportFactory.stopped(getBrokerName());
if (broker != null) {
stopper.stop(broker);
broker = null;
}
if (jobSchedulerStore != null) {
jobSchedulerStore.stop();
jobSchedulerStore = null;
}
if (tempDataStore != null) {
tempDataStore.stop();
tempDataStore = null;
}
try {
stopper.stop(persistenceAdapter);
persistenceAdapter = null;
if (isUseJmx()) {
stopper.stop(getManagementContext());
managementContext = null;
}
// Clear SelectorParser cache to free memory
SelectorParser.clearCache();
} finally {
started.set(false);
stopped.set(true);
stoppedLatch.countDown();
}
if (this.taskRunnerFactory != null) {
this.taskRunnerFactory.shutdown();
this.taskRunnerFactory = null;
}
if (this.executor != null) {
ThreadPoolUtils.shutdownNow(executor);
this.executor = null;
}
this.destinationInterceptors = null;
this.destinationFactory = null;
if (LOG.isInfoEnabled()) {
if (startDate != null) {
LOG.info("Apache ActiveMQ " + getBrokerVersion() + " ("
+ getBrokerName() + ", " + brokerId + ") uptime " + getUptime());
}
LOG.info("Apache ActiveMQ " + getBrokerVersion() + " ("
+ getBrokerName() + ", " + brokerId + ") is shutdown");
}
synchronized (shutdownHooks) {
for (Runnable hook : shutdownHooks) {
try {
hook.run();
} catch (Throwable e) {
stopper.onException(hook, e);
}
}
}
MDC.remove("activemq.broker");
// and clear start date
startDate = null;
stopper.throwFirstException();
}
public boolean checkQueueSize(String queueName) {
long count = 0;
long queueSize = 0;
Map<ActiveMQDestination, Destination> destinationMap = regionBroker.getDestinationMap();
for (Map.Entry<ActiveMQDestination, Destination> entry : destinationMap.entrySet()) {
if (entry.getKey().isQueue()) {
if (entry.getValue().getName().matches(queueName)) {
queueSize = entry.getValue().getDestinationStatistics().getMessages().getCount();
count += queueSize;
if (queueSize > 0) {
LOG.info("Queue has pending message:" + entry.getValue().getName() + " queueSize is:"
+ queueSize);
}
}
}
}
return count == 0;
}
/**
* This method (both connectorName and queueName are using regex to match)
* 1. stop the connector (supposed the user input the connector which the
* clients connect to) 2. to check whether there is any pending message on
* the queues defined by queueName 3. supposedly, after stop the connector,
* client should failover to other broker and pending messages should be
* forwarded. if no pending messages, the method finally call stop to stop
* the broker.
*
* @param connectorName
* @param queueName
* @param timeout
* @param pollInterval
* @throws Exception
*/
public void stopGracefully(String connectorName, String queueName, long timeout, long pollInterval) throws Exception {
if (isUseJmx()) {
if (connectorName == null || queueName == null || timeout <= 0) {
throw new Exception(
"connectorName and queueName cannot be null and timeout should be >0 for stopGracefully.");
}
if (pollInterval <= 0) {
pollInterval = 30;
}
LOG.info("Stop gracefully with connectorName:" + connectorName + " queueName:" + queueName + " timeout:"
+ timeout + " pollInterval:" + pollInterval);
TransportConnector connector;
for (int i = 0; i < transportConnectors.size(); i++) {
connector = transportConnectors.get(i);
if (connector != null && connector.getName() != null && connector.getName().matches(connectorName)) {
connector.stop();
}
}
long start = System.currentTimeMillis();
while (System.currentTimeMillis() - start < timeout * 1000) {
// check quesize until it gets zero
if (checkQueueSize(queueName)) {
stop();
break;
} else {
Thread.sleep(pollInterval * 1000);
}
}
if (stopped.get()) {
LOG.info("Successfully stop the broker.");
} else {
LOG.info("There is still pending message on the queue. Please check and stop the broker manually.");
}
}
}
/**
* A helper method to block the caller thread until the broker has been
* stopped
*/
public void waitUntilStopped() {
while (isStarted() && !stopped.get()) {
try {
stoppedLatch.await();
} catch (InterruptedException e) {
// ignore
}
}
}
/**
* A helper method to block the caller thread until the broker has fully started
* @return boolean true if wait succeeded false if broker was not started or was stopped
*/
public boolean waitUntilStarted() {
boolean waitSucceeded = isStarted();
while (!isStarted() && !stopped.get() && !waitSucceeded) {
try {
if (startException != null) {
return waitSucceeded;
}
waitSucceeded = startedLatch.await(100L, TimeUnit.MILLISECONDS);
} catch (InterruptedException ignore) {
}
}
return waitSucceeded;
}
// Properties
// -------------------------------------------------------------------------
/**
* Returns the message broker
*/
public Broker getBroker() throws Exception {
if (broker == null) {
broker = createBroker();
}
return broker;
}
/**
* Returns the administration view of the broker; used to create and destroy
* resources such as queues and topics. Note this method returns null if JMX
* is disabled.
*/
public BrokerView getAdminView() throws Exception {
if (adminView == null) {
// force lazy creation
getBroker();
}
return adminView;
}
public void setAdminView(BrokerView adminView) {
this.adminView = adminView;
}
public String getBrokerName() {
return brokerName;
}
/**
* Sets the name of this broker; which must be unique in the network
*
* @param brokerName
*/
public void setBrokerName(String brokerName) {
if (brokerName == null) {
throw new NullPointerException("The broker name cannot be null");
}
String str = brokerName.replaceAll("[^a-zA-Z0-9\\.\\_\\-\\:]", "_");
if (!str.equals(brokerName)) {
LOG.error("Broker Name: " + brokerName + " contained illegal characters - replaced with " + str);
}
this.brokerName = str.trim();
}
public PersistenceAdapterFactory getPersistenceFactory() {
return persistenceFactory;
}
public File getDataDirectoryFile() {
if (dataDirectoryFile == null) {
dataDirectoryFile = new File(IOHelper.getDefaultDataDirectory());
}
return dataDirectoryFile;
}
public File getBrokerDataDirectory() {
String brokerDir = getBrokerName();
return new File(getDataDirectoryFile(), brokerDir);
}
/**
* Sets the directory in which the data files will be stored by default for
* the JDBC and Journal persistence adaptors.
*
* @param dataDirectory
* the directory to store data files
*/
public void setDataDirectory(String dataDirectory) {
setDataDirectoryFile(new File(dataDirectory));
}
/**
* Sets the directory in which the data files will be stored by default for
* the JDBC and Journal persistence adaptors.
*
* @param dataDirectoryFile
* the directory to store data files
*/
public void setDataDirectoryFile(File dataDirectoryFile) {
this.dataDirectoryFile = dataDirectoryFile;
}
/**
* @return the tmpDataDirectory
*/
public File getTmpDataDirectory() {
if (tmpDataDirectory == null) {
tmpDataDirectory = new File(getBrokerDataDirectory(), "tmp_storage");
}
return tmpDataDirectory;
}
/**
* @param tmpDataDirectory
* the tmpDataDirectory to set
*/
public void setTmpDataDirectory(File tmpDataDirectory) {
this.tmpDataDirectory = tmpDataDirectory;
}
public void setPersistenceFactory(PersistenceAdapterFactory persistenceFactory) {
this.persistenceFactory = persistenceFactory;
}
public void setDestinationFactory(DestinationFactory destinationFactory) {
this.destinationFactory = destinationFactory;
}
public boolean isPersistent() {
return persistent;
}
/**
* Sets whether or not persistence is enabled or disabled.
* @org.apache.xbean.Property propertyEditor="org.apache.activemq.util.BooleanEditor"
*/
public void setPersistent(boolean persistent) {
this.persistent = persistent;
}
public boolean isPopulateJMSXUserID() {
return populateJMSXUserID;
}
/**
* Sets whether or not the broker should populate the JMSXUserID header.
*/
public void setPopulateJMSXUserID(boolean populateJMSXUserID) {
this.populateJMSXUserID = populateJMSXUserID;
}
public SystemUsage getSystemUsage() {
try {
if (systemUsage == null) {
systemUsage = new SystemUsage("Main", getPersistenceAdapter(), getTempDataStore(), getJobSchedulerStore());
systemUsage.setExecutor(getExecutor());
systemUsage.getMemoryUsage().setLimit(1024 * 1024 * 64); // 64 MB
systemUsage.getTempUsage().setLimit(1024L * 1024 * 1024 * 50); // 50 GB
systemUsage.getStoreUsage().setLimit(1024L * 1024 * 1024 * 100); // 100 GB
systemUsage.getJobSchedulerUsage().setLimit(1024L * 1024 * 1000 * 50); // 50 // Gb
addService(this.systemUsage);
}
return systemUsage;
} catch (IOException e) {
LOG.error("Cannot create SystemUsage", e);
throw new RuntimeException("Fatally failed to create SystemUsage" + e.getMessage());
}
}
public void setSystemUsage(SystemUsage memoryManager) {
if (this.systemUsage != null) {
removeService(this.systemUsage);
}
this.systemUsage = memoryManager;
if (this.systemUsage.getExecutor()==null) {
this.systemUsage.setExecutor(getExecutor());
}
addService(this.systemUsage);
}
/**
* @return the consumerUsageManager
* @throws IOException
*/
public SystemUsage getConsumerSystemUsage() throws IOException {
if (this.consumerSystemUsaage == null) {
if (splitSystemUsageForProducersConsumers) {
this.consumerSystemUsaage = new SystemUsage(getSystemUsage(), "Consumer");
float portion = consumerSystemUsagePortion / 100f;
this.consumerSystemUsaage.getMemoryUsage().setUsagePortion(portion);
addService(this.consumerSystemUsaage);
} else {
consumerSystemUsaage = getSystemUsage();
}
}
return this.consumerSystemUsaage;
}
/**
* @param consumerSystemUsaage
* the storeSystemUsage to set
*/
public void setConsumerSystemUsage(SystemUsage consumerSystemUsaage) {
if (this.consumerSystemUsaage != null) {
removeService(this.consumerSystemUsaage);
}
this.consumerSystemUsaage = consumerSystemUsaage;
addService(this.consumerSystemUsaage);
}
/**
* @return the producerUsageManager
* @throws IOException
*/
public SystemUsage getProducerSystemUsage() throws IOException {
if (producerSystemUsage == null) {
if (splitSystemUsageForProducersConsumers) {
producerSystemUsage = new SystemUsage(getSystemUsage(), "Producer");
float portion = producerSystemUsagePortion / 100f;
producerSystemUsage.getMemoryUsage().setUsagePortion(portion);
addService(producerSystemUsage);
} else {
producerSystemUsage = getSystemUsage();
}
}
return producerSystemUsage;
}
/**
* @param producerUsageManager
* the producerUsageManager to set
*/
public void setProducerSystemUsage(SystemUsage producerUsageManager) {
if (this.producerSystemUsage != null) {
removeService(this.producerSystemUsage);
}
this.producerSystemUsage = producerUsageManager;
addService(this.producerSystemUsage);
}
public PersistenceAdapter getPersistenceAdapter() throws IOException {
if (persistenceAdapter == null) {
persistenceAdapter = createPersistenceAdapter();
configureService(persistenceAdapter);
this.persistenceAdapter = registerPersistenceAdapterMBean(persistenceAdapter);
}
return persistenceAdapter;
}
/**
* Sets the persistence adaptor implementation to use for this broker
*
* @throws IOException
*/
public void setPersistenceAdapter(PersistenceAdapter persistenceAdapter) throws IOException {
if (!isPersistent() && ! (persistenceAdapter instanceof MemoryPersistenceAdapter)) {
LOG.warn("persistent=\"false\", ignoring configured persistenceAdapter: " + persistenceAdapter);
return;
}
this.persistenceAdapter = persistenceAdapter;
configureService(this.persistenceAdapter);
this.persistenceAdapter = registerPersistenceAdapterMBean(persistenceAdapter);
}
public TaskRunnerFactory getTaskRunnerFactory() {
if (this.taskRunnerFactory == null) {
this.taskRunnerFactory = new TaskRunnerFactory("ActiveMQ BrokerService["+getBrokerName()+"] Task", getTaskRunnerPriority(), true, 1000,
isDedicatedTaskRunner());
}
return this.taskRunnerFactory;
}
public void setTaskRunnerFactory(TaskRunnerFactory taskRunnerFactory) {
this.taskRunnerFactory = taskRunnerFactory;
}
public TaskRunnerFactory getPersistenceTaskRunnerFactory() {
if (taskRunnerFactory == null) {
persistenceTaskRunnerFactory = new TaskRunnerFactory("Persistence Adaptor Task", persistenceThreadPriority,
true, 1000, isDedicatedTaskRunner());
}
return persistenceTaskRunnerFactory;
}
public void setPersistenceTaskRunnerFactory(TaskRunnerFactory persistenceTaskRunnerFactory) {
this.persistenceTaskRunnerFactory = persistenceTaskRunnerFactory;
}
public boolean isUseJmx() {
return useJmx;
}
public boolean isEnableStatistics() {
return enableStatistics;
}
/**
* Sets whether or not the Broker's services enable statistics or not.
*/
public void setEnableStatistics(boolean enableStatistics) {
this.enableStatistics = enableStatistics;
}
/**
* Sets whether or not the Broker's services should be exposed into JMX or
* not.
* @org.apache.xbean.Property propertyEditor="org.apache.activemq.util.BooleanEditor"
*/
public void setUseJmx(boolean useJmx) {
this.useJmx = useJmx;
}
public ObjectName getBrokerObjectName() throws MalformedObjectNameException {
if (brokerObjectName == null) {
brokerObjectName = createBrokerObjectName();
}
return brokerObjectName;
}
/**
* Sets the JMX ObjectName for this broker
*/
public void setBrokerObjectName(ObjectName brokerObjectName) {
this.brokerObjectName = brokerObjectName;
}
public ManagementContext getManagementContext() {
if (managementContext == null) {
managementContext = new ManagementContext();
}
return managementContext;
}
public void setManagementContext(ManagementContext managementContext) {
this.managementContext = managementContext;
}
public NetworkConnector getNetworkConnectorByName(String connectorName) {
for (NetworkConnector connector : networkConnectors) {
if (connector.getName().equals(connectorName)) {
return connector;
}
}
return null;
}
public String[] getNetworkConnectorURIs() {
return networkConnectorURIs;
}
public void setNetworkConnectorURIs(String[] networkConnectorURIs) {
this.networkConnectorURIs = networkConnectorURIs;
}
public TransportConnector getConnectorByName(String connectorName) {
for (TransportConnector connector : transportConnectors) {
if (connector.getName().equals(connectorName)) {
return connector;
}
}
return null;
}
public Map<String, String> getTransportConnectorURIsAsMap() {
Map<String, String> answer = new HashMap<String, String>();
for (TransportConnector connector : transportConnectors) {
try {
URI uri = connector.getConnectUri();
if (uri != null) {
String scheme = uri.getScheme();
if (scheme != null) {
answer.put(scheme.toLowerCase(Locale.ENGLISH), uri.toString());
}
}
} catch (Exception e) {
LOG.debug("Failed to read URI to build transportURIsAsMap", e);
}
}
return answer;
}
public ProducerBrokerExchange getProducerBrokerExchange(ProducerInfo producerInfo){
ProducerBrokerExchange result = null;
for (TransportConnector connector : transportConnectors) {
for (TransportConnection tc: connector.getConnections()){
result = tc.getProducerBrokerExchangeIfExists(producerInfo);
if (result !=null){
return result;
}
}
}
return result;
}
public String[] getTransportConnectorURIs() {
return transportConnectorURIs;
}
public void setTransportConnectorURIs(String[] transportConnectorURIs) {
this.transportConnectorURIs = transportConnectorURIs;
}
/**
* @return Returns the jmsBridgeConnectors.
*/
public JmsConnector[] getJmsBridgeConnectors() {
return jmsBridgeConnectors;
}
/**
* @param jmsConnectors
* The jmsBridgeConnectors to set.
*/
public void setJmsBridgeConnectors(JmsConnector[] jmsConnectors) {
this.jmsBridgeConnectors = jmsConnectors;
}
public Service[] getServices() {
return services.toArray(new Service[0]);
}
/**
* Sets the services associated with this broker.
*/
public void setServices(Service[] services) {
this.services.clear();
if (services != null) {
for (int i = 0; i < services.length; i++) {
this.services.add(services[i]);
}
}
}
/**
* Adds a new service so that it will be started as part of the broker
* lifecycle
*/
public void addService(Service service) {
services.add(service);
}
public void removeService(Service service) {
services.remove(service);
}
public boolean isUseLoggingForShutdownErrors() {
return useLoggingForShutdownErrors;
}
/**
* Sets whether or not we should use commons-logging when reporting errors
* when shutting down the broker
*/
public void setUseLoggingForShutdownErrors(boolean useLoggingForShutdownErrors) {
this.useLoggingForShutdownErrors = useLoggingForShutdownErrors;
}
public boolean isUseShutdownHook() {
return useShutdownHook;
}
/**
* Sets whether or not we should use a shutdown handler to close down the
* broker cleanly if the JVM is terminated. It is recommended you leave this
* enabled.
*/
public void setUseShutdownHook(boolean useShutdownHook) {
this.useShutdownHook = useShutdownHook;
}
public boolean isAdvisorySupport() {
return advisorySupport;
}
/**
* Allows the support of advisory messages to be disabled for performance
* reasons.
* @org.apache.xbean.Property propertyEditor="org.apache.activemq.util.BooleanEditor"
*/
public void setAdvisorySupport(boolean advisorySupport) {
this.advisorySupport = advisorySupport;
}
public List<TransportConnector> getTransportConnectors() {
return new ArrayList<TransportConnector>(transportConnectors);
}
/**
* Sets the transport connectors which this broker will listen on for new
* clients
*
* @org.apache.xbean.Property
* nestedType="org.apache.activemq.broker.TransportConnector"
*/
public void setTransportConnectors(List<TransportConnector> transportConnectors) throws Exception {
for (TransportConnector connector : transportConnectors) {
addConnector(connector);
}
}
public TransportConnector getTransportConnectorByName(String name){
for (TransportConnector transportConnector : transportConnectors){
if (name.equals(transportConnector.getName())){
return transportConnector;
}
}
return null;
}
public TransportConnector getTransportConnectorByScheme(String scheme){
for (TransportConnector transportConnector : transportConnectors){
if (scheme.equals(transportConnector.getUri().getScheme())){
return transportConnector;
}
}
return null;
}
public List<NetworkConnector> getNetworkConnectors() {
return new ArrayList<NetworkConnector>(networkConnectors);
}
public List<ProxyConnector> getProxyConnectors() {
return new ArrayList<ProxyConnector>(proxyConnectors);
}
/**
* Sets the network connectors which this broker will use to connect to
* other brokers in a federated network
*
* @org.apache.xbean.Property
* nestedType="org.apache.activemq.network.NetworkConnector"
*/
public void setNetworkConnectors(List<?> networkConnectors) throws Exception {
for (Object connector : networkConnectors) {
addNetworkConnector((NetworkConnector) connector);
}
}
/**
* Sets the network connectors which this broker will use to connect to
* other brokers in a federated network
*/
public void setProxyConnectors(List<?> proxyConnectors) throws Exception {
for (Object connector : proxyConnectors) {
addProxyConnector((ProxyConnector) connector);
}
}
public PolicyMap getDestinationPolicy() {
return destinationPolicy;
}
/**
* Sets the destination specific policies available either for exact
* destinations or for wildcard areas of destinations.
*/
public void setDestinationPolicy(PolicyMap policyMap) {
this.destinationPolicy = policyMap;
}
public BrokerPlugin[] getPlugins() {
return plugins;
}
/**
* Sets a number of broker plugins to install such as for security
* authentication or authorization
*/
public void setPlugins(BrokerPlugin[] plugins) {
this.plugins = plugins;
}
public MessageAuthorizationPolicy getMessageAuthorizationPolicy() {
return messageAuthorizationPolicy;
}
/**
* Sets the policy used to decide if the current connection is authorized to
* consume a given message
*/
public void setMessageAuthorizationPolicy(MessageAuthorizationPolicy messageAuthorizationPolicy) {
this.messageAuthorizationPolicy = messageAuthorizationPolicy;
}
/**
* Delete all messages from the persistent store
*
* @throws IOException
*/
public void deleteAllMessages() throws IOException {
getPersistenceAdapter().deleteAllMessages();
}
public boolean isDeleteAllMessagesOnStartup() {
return deleteAllMessagesOnStartup;
}
/**
* Sets whether or not all messages are deleted on startup - mostly only
* useful for testing.
* @org.apache.xbean.Property propertyEditor="org.apache.activemq.util.BooleanEditor"
*/
public void setDeleteAllMessagesOnStartup(boolean deletePersistentMessagesOnStartup) {
this.deleteAllMessagesOnStartup = deletePersistentMessagesOnStartup;
}
public URI getVmConnectorURI() {
if (vmConnectorURI == null) {
try {
vmConnectorURI = new URI("vm://" + getBrokerName().replaceAll("[^a-zA-Z0-9\\.\\_\\-]", "_"));
} catch (URISyntaxException e) {
LOG.error("Badly formed URI from " + getBrokerName(), e);
}
}
return vmConnectorURI;
}
public void setVmConnectorURI(URI vmConnectorURI) {
this.vmConnectorURI = vmConnectorURI;
}
public String getDefaultSocketURIString() {
if (started.get()) {
if (this.defaultSocketURIString == null) {
for (TransportConnector tc:this.transportConnectors) {
String result = null;
try {
result = tc.getPublishableConnectString();
} catch (Exception e) {
LOG.warn("Failed to get the ConnectURI for "+tc,e);
}
if (result != null) {
// find first publishable uri
if (tc.isUpdateClusterClients() || tc.isRebalanceClusterClients()) {
this.defaultSocketURIString = result;
break;
} else {
// or use the first defined
if (this.defaultSocketURIString == null) {
this.defaultSocketURIString = result;
}
}
}
}
}
return this.defaultSocketURIString;
}
return null;
}
/**
* @return Returns the shutdownOnMasterFailure.
*/
public boolean isShutdownOnMasterFailure() {
return shutdownOnMasterFailure;
}
/**
* @param shutdownOnMasterFailure
* The shutdownOnMasterFailure to set.
*/
public void setShutdownOnMasterFailure(boolean shutdownOnMasterFailure) {
this.shutdownOnMasterFailure = shutdownOnMasterFailure;
}
public boolean isKeepDurableSubsActive() {
return keepDurableSubsActive;
}
public void setKeepDurableSubsActive(boolean keepDurableSubsActive) {
this.keepDurableSubsActive = keepDurableSubsActive;
}
public boolean isUseVirtualTopics() {
return useVirtualTopics;
}
/**
* Sets whether or not <a
* href="http://activemq.apache.org/virtual-destinations.html">Virtual
* Topics</a> should be supported by default if they have not been
* explicitly configured.
*/
public void setUseVirtualTopics(boolean useVirtualTopics) {
this.useVirtualTopics = useVirtualTopics;
}
public DestinationInterceptor[] getDestinationInterceptors() {
return destinationInterceptors;
}
public boolean isUseMirroredQueues() {
return useMirroredQueues;
}
/**
* Sets whether or not <a
* href="http://activemq.apache.org/mirrored-queues.html">Mirrored
* Queues</a> should be supported by default if they have not been
* explicitly configured.
*/
public void setUseMirroredQueues(boolean useMirroredQueues) {
this.useMirroredQueues = useMirroredQueues;
}
/**
* Sets the destination interceptors to use
*/
public void setDestinationInterceptors(DestinationInterceptor[] destinationInterceptors) {
this.destinationInterceptors = destinationInterceptors;
}
public ActiveMQDestination[] getDestinations() {
return destinations;
}
/**
* Sets the destinations which should be loaded/created on startup
*/
public void setDestinations(ActiveMQDestination[] destinations) {
this.destinations = destinations;
}
/**
* @return the tempDataStore
*/
public synchronized PListStore getTempDataStore() {
if (tempDataStore == null) {
if (!isPersistent()) {
return null;
}
try {
PersistenceAdapter pa = getPersistenceAdapter();
if( pa!=null && pa instanceof PListStore) {
return (PListStore) pa;
}
} catch (IOException e) {
throw new RuntimeException(e);
}
boolean result = true;
boolean empty = true;
try {
File directory = getTmpDataDirectory();
if (directory.exists() && directory.isDirectory()) {
File[] files = directory.listFiles();
if (files != null && files.length > 0) {
empty = false;
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (!file.isDirectory()) {
result &= file.delete();
}
}
}
}
if (!empty) {
String str = result ? "Successfully deleted" : "Failed to delete";
LOG.info(str + " temporary storage");
}
String clazz = "org.apache.activemq.store.kahadb.plist.PListStoreImpl";
this.tempDataStore = (PListStore) getClass().getClassLoader().loadClass(clazz).newInstance();
this.tempDataStore.setDirectory(getTmpDataDirectory());
configureService(tempDataStore);
this.tempDataStore.start();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return tempDataStore;
}
/**
* @param tempDataStore
* the tempDataStore to set
*/
public void setTempDataStore(PListStore tempDataStore) {
this.tempDataStore = tempDataStore;
configureService(tempDataStore);
try {
tempDataStore.start();
} catch (Exception e) {
RuntimeException exception = new RuntimeException("Failed to start provided temp data store: " + tempDataStore, e);
LOG.error(exception.getLocalizedMessage(), e);
throw exception;
}
}
public int getPersistenceThreadPriority() {
return persistenceThreadPriority;
}
public void setPersistenceThreadPriority(int persistenceThreadPriority) {
this.persistenceThreadPriority = persistenceThreadPriority;
}
/**
* @return the useLocalHostBrokerName
*/
public boolean isUseLocalHostBrokerName() {
return this.useLocalHostBrokerName;
}
/**
* @param useLocalHostBrokerName
* the useLocalHostBrokerName to set
*/
public void setUseLocalHostBrokerName(boolean useLocalHostBrokerName) {
this.useLocalHostBrokerName = useLocalHostBrokerName;
if (useLocalHostBrokerName && !started.get() && brokerName == null || brokerName == DEFAULT_BROKER_NAME) {
brokerName = LOCAL_HOST_NAME;
}
}
/**
* @return the supportFailOver
*/
public boolean isSupportFailOver() {
return this.supportFailOver;
}
/**
* @param supportFailOver
* the supportFailOver to set
*/
public void setSupportFailOver(boolean supportFailOver) {
this.supportFailOver = supportFailOver;
}
/**
* Looks up and lazily creates if necessary the destination for the given
* JMS name
*/
public Destination getDestination(ActiveMQDestination destination) throws Exception {
return getBroker().addDestination(getAdminConnectionContext(), destination,false);
}
public void removeDestination(ActiveMQDestination destination) throws Exception {
getBroker().removeDestination(getAdminConnectionContext(), destination, 0);
}
public int getProducerSystemUsagePortion() {
return producerSystemUsagePortion;
}
public void setProducerSystemUsagePortion(int producerSystemUsagePortion) {
this.producerSystemUsagePortion = producerSystemUsagePortion;
}
public int getConsumerSystemUsagePortion() {
return consumerSystemUsagePortion;
}
public void setConsumerSystemUsagePortion(int consumerSystemUsagePortion) {
this.consumerSystemUsagePortion = consumerSystemUsagePortion;
}
public boolean isSplitSystemUsageForProducersConsumers() {
return splitSystemUsageForProducersConsumers;
}
public void setSplitSystemUsageForProducersConsumers(boolean splitSystemUsageForProducersConsumers) {
this.splitSystemUsageForProducersConsumers = splitSystemUsageForProducersConsumers;
}
public boolean isMonitorConnectionSplits() {
return monitorConnectionSplits;
}
public void setMonitorConnectionSplits(boolean monitorConnectionSplits) {
this.monitorConnectionSplits = monitorConnectionSplits;
}
public int getTaskRunnerPriority() {
return taskRunnerPriority;
}
public void setTaskRunnerPriority(int taskRunnerPriority) {
this.taskRunnerPriority = taskRunnerPriority;
}
public boolean isDedicatedTaskRunner() {
return dedicatedTaskRunner;
}
public void setDedicatedTaskRunner(boolean dedicatedTaskRunner) {
this.dedicatedTaskRunner = dedicatedTaskRunner;
}
public boolean isCacheTempDestinations() {
return cacheTempDestinations;
}
public void setCacheTempDestinations(boolean cacheTempDestinations) {
this.cacheTempDestinations = cacheTempDestinations;
}
public int getTimeBeforePurgeTempDestinations() {
return timeBeforePurgeTempDestinations;
}
public void setTimeBeforePurgeTempDestinations(int timeBeforePurgeTempDestinations) {
this.timeBeforePurgeTempDestinations = timeBeforePurgeTempDestinations;
}
public boolean isUseTempMirroredQueues() {
return useTempMirroredQueues;
}
public void setUseTempMirroredQueues(boolean useTempMirroredQueues) {
this.useTempMirroredQueues = useTempMirroredQueues;
}
public synchronized JobSchedulerStore getJobSchedulerStore() {
if (jobSchedulerStore == null && isSchedulerSupport()) {
try {
String clazz = "org.apache.activemq.store.kahadb.scheduler.JobSchedulerStoreImpl";
jobSchedulerStore = (JobSchedulerStore) getClass().getClassLoader().loadClass(clazz).newInstance();
jobSchedulerStore.setDirectory(getSchedulerDirectoryFile());
configureService(jobSchedulerStore);
jobSchedulerStore.start();
LOG.info("JobScheduler using directory: " + getSchedulerDirectoryFile());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
return jobSchedulerStore;
}
public void setJobSchedulerStore(JobSchedulerStore jobSchedulerStore) {
this.jobSchedulerStore = jobSchedulerStore;
configureService(jobSchedulerStore);
try {
jobSchedulerStore.start();
} catch (Exception e) {
RuntimeException exception = new RuntimeException(
"Failed to start provided job scheduler store: " + jobSchedulerStore, e);
LOG.error(exception.getLocalizedMessage(), e);
throw exception;
}
}
//
// Implementation methods
// -------------------------------------------------------------------------
/**
* Handles any lazy-creation helper properties which are added to make
* things easier to configure inside environments such as Spring
*
* @throws Exception
*/
protected void processHelperProperties() throws Exception {
if (transportConnectorURIs != null) {
for (int i = 0; i < transportConnectorURIs.length; i++) {
String uri = transportConnectorURIs[i];
addConnector(uri);
}
}
if (networkConnectorURIs != null) {
for (int i = 0; i < networkConnectorURIs.length; i++) {
String uri = networkConnectorURIs[i];
addNetworkConnector(uri);
}
}
if (jmsBridgeConnectors != null) {
for (int i = 0; i < jmsBridgeConnectors.length; i++) {
addJmsConnector(jmsBridgeConnectors[i]);
}
}
}
protected void checkSystemUsageLimits() throws IOException {
SystemUsage usage = getSystemUsage();
long memLimit = usage.getMemoryUsage().getLimit();
long jvmLimit = Runtime.getRuntime().maxMemory();
if (memLimit > jvmLimit) {
LOG.error("Memory Usage for the Broker (" + memLimit / (1024 * 1024) +
" mb) is more than the maximum available for the JVM: " +
jvmLimit / (1024 * 1024) + " mb - resetting to maximum available: " + jvmLimit / (1024 * 1024) + " mb");
usage.getMemoryUsage().setLimit(jvmLimit);
}
if (getPersistenceAdapter() != null) {
PersistenceAdapter adapter = getPersistenceAdapter();
File dir = adapter.getDirectory();
if (dir != null) {
String dirPath = dir.getAbsolutePath();
if (!dir.isAbsolute()) {
dir = new File(dirPath);
}
while (dir != null && dir.isDirectory() == false) {
dir = dir.getParentFile();
}
long storeLimit = usage.getStoreUsage().getLimit();
long dirFreeSpace = dir.getUsableSpace();
if (storeLimit > dirFreeSpace) {
LOG.warn("Store limit is " + storeLimit / (1024 * 1024) +
" mb, whilst the data directory: " + dir.getAbsolutePath() +
" only has " + dirFreeSpace / (1024 * 1024) +
" mb of usable space - resetting to maximum available disk space: " +
dirFreeSpace / (1024 * 1024) + " mb");
usage.getStoreUsage().setLimit(dirFreeSpace);
}
}
long maxJournalFileSize = 0;
long storeLimit = usage.getStoreUsage().getLimit();
if (adapter instanceof JournaledStore) {
maxJournalFileSize = ((JournaledStore) adapter).getJournalMaxFileLength();
}
if (storeLimit < maxJournalFileSize) {
LOG.error("Store limit is " + storeLimit / (1024 * 1024) +
" mb, whilst the max journal file size for the store is: " +
maxJournalFileSize / (1024 * 1024) + " mb, " +
"the store will not accept any data when used.");
}
}
File tmpDir = getTmpDataDirectory();
if (tmpDir != null) {
String tmpDirPath = tmpDir.getAbsolutePath();
if (!tmpDir.isAbsolute()) {
tmpDir = new File(tmpDirPath);
}
long storeLimit = usage.getTempUsage().getLimit();
while (tmpDir != null && tmpDir.isDirectory() == false) {
tmpDir = tmpDir.getParentFile();
}
long dirFreeSpace = tmpDir.getUsableSpace();
if (storeLimit > dirFreeSpace) {
LOG.error("Temporary Store limit is " + storeLimit / (1024 * 1024) +
" mb, whilst the temporary data directory: " + tmpDirPath +
" only has " + dirFreeSpace / (1024 * 1024) + " mb of usable space - resetting to maximum available " +
dirFreeSpace / (1024 * 1024) + " mb.");
usage.getTempUsage().setLimit(dirFreeSpace);
}
if (isPersistent()) {
long maxJournalFileSize;
PListStore store = usage.getTempUsage().getStore();
if (store != null && store instanceof JournaledStore) {
maxJournalFileSize = ((JournaledStore) store).getJournalMaxFileLength();
} else {
maxJournalFileSize = DEFAULT_MAX_FILE_LENGTH;
}
if (storeLimit < maxJournalFileSize) {
LOG.error("Temporary Store limit is " + storeLimit / (1024 * 1024) +
" mb, whilst the max journal file size for the temporary store is: " +
maxJournalFileSize / (1024 * 1024) + " mb, " +
"the temp store will not accept any data when used.");
}
}
}
if (getJobSchedulerStore() != null) {
JobSchedulerStore scheduler = getJobSchedulerStore();
File schedulerDir = scheduler.getDirectory();
if (schedulerDir != null) {
String schedulerDirPath = schedulerDir.getAbsolutePath();
if (!schedulerDir.isAbsolute()) {
schedulerDir = new File(schedulerDirPath);
}
while (schedulerDir != null && schedulerDir.isDirectory() == false) {
schedulerDir = schedulerDir.getParentFile();
}
long schedularLimit = usage.getJobSchedulerUsage().getLimit();
long dirFreeSpace = schedulerDir.getUsableSpace();
if (schedularLimit > dirFreeSpace) {
LOG.warn("Job Schedular Store limit is " + schedularLimit / (1024 * 1024) +
" mb, whilst the data directory: " + schedulerDir.getAbsolutePath() +
- " only has " + dirFreeSpace / (1024 * 1024) + " mb of usable space - reseting to " +
+ " only has " + dirFreeSpace / (1024 * 1024) + " mb of usable space - resetting to " +
dirFreeSpace / (1024 * 1024) + " mb.");
usage.getJobSchedulerUsage().setLimit(dirFreeSpace);
}
}
}
}
public void stopAllConnectors(ServiceStopper stopper) {
for (Iterator<NetworkConnector> iter = getNetworkConnectors().iterator(); iter.hasNext();) {
NetworkConnector connector = iter.next();
unregisterNetworkConnectorMBean(connector);
stopper.stop(connector);
}
for (Iterator<ProxyConnector> iter = getProxyConnectors().iterator(); iter.hasNext();) {
ProxyConnector connector = iter.next();
stopper.stop(connector);
}
for (Iterator<JmsConnector> iter = jmsConnectors.iterator(); iter.hasNext();) {
JmsConnector connector = iter.next();
stopper.stop(connector);
}
for (Iterator<TransportConnector> iter = getTransportConnectors().iterator(); iter.hasNext();) {
TransportConnector connector = iter.next();
try {
unregisterConnectorMBean(connector);
} catch (IOException e) {
}
stopper.stop(connector);
}
}
protected TransportConnector registerConnectorMBean(TransportConnector connector) throws IOException {
try {
ObjectName objectName = createConnectorObjectName(connector);
connector = connector.asManagedConnector(getManagementContext(), objectName);
ConnectorViewMBean view = new ConnectorView(connector);
AnnotatedMBean.registerMBean(getManagementContext(), view, objectName);
return connector;
} catch (Throwable e) {
throw IOExceptionSupport.create("Transport Connector could not be registered in JMX: " + e.getMessage(), e);
}
}
protected void unregisterConnectorMBean(TransportConnector connector) throws IOException {
if (isUseJmx()) {
try {
ObjectName objectName = createConnectorObjectName(connector);
getManagementContext().unregisterMBean(objectName);
} catch (Throwable e) {
throw IOExceptionSupport.create(
"Transport Connector could not be unregistered in JMX: " + e.getMessage(), e);
}
}
}
protected PersistenceAdapter registerPersistenceAdapterMBean(PersistenceAdapter adaptor) throws IOException {
return adaptor;
}
protected void unregisterPersistenceAdapterMBean(PersistenceAdapter adaptor) throws IOException {
if (isUseJmx()) {}
}
private ObjectName createConnectorObjectName(TransportConnector connector) throws MalformedObjectNameException {
return BrokerMBeanSupport.createConnectorName(getBrokerObjectName(), "clientConnectors", connector.getName());
}
protected void registerNetworkConnectorMBean(NetworkConnector connector) throws IOException {
NetworkConnectorViewMBean view = new NetworkConnectorView(connector);
try {
ObjectName objectName = createNetworkConnectorObjectName(connector);
connector.setObjectName(objectName);
AnnotatedMBean.registerMBean(getManagementContext(), view, objectName);
} catch (Throwable e) {
throw IOExceptionSupport.create("Network Connector could not be registered in JMX: " + e.getMessage(), e);
}
}
protected ObjectName createNetworkConnectorObjectName(NetworkConnector connector) throws MalformedObjectNameException {
return BrokerMBeanSupport.createNetworkConnectorName(getBrokerObjectName(), "networkConnectors", connector.getName());
}
public ObjectName createDuplexNetworkConnectorObjectName(String transport) throws MalformedObjectNameException {
return BrokerMBeanSupport.createNetworkConnectorName(getBrokerObjectName(), "duplexNetworkConnectors", transport.toString());
}
protected void unregisterNetworkConnectorMBean(NetworkConnector connector) {
if (isUseJmx()) {
try {
ObjectName objectName = createNetworkConnectorObjectName(connector);
getManagementContext().unregisterMBean(objectName);
} catch (Exception e) {
LOG.error("Network Connector could not be unregistered from JMX: " + e, e);
}
}
}
protected void registerProxyConnectorMBean(ProxyConnector connector) throws IOException {
ProxyConnectorView view = new ProxyConnectorView(connector);
try {
ObjectName objectName = BrokerMBeanSupport.createNetworkConnectorName(getBrokerObjectName(), "proxyConnectors", connector.getName());
AnnotatedMBean.registerMBean(getManagementContext(), view, objectName);
} catch (Throwable e) {
throw IOExceptionSupport.create("Broker could not be registered in JMX: " + e.getMessage(), e);
}
}
protected void registerJmsConnectorMBean(JmsConnector connector) throws IOException {
JmsConnectorView view = new JmsConnectorView(connector);
try {
ObjectName objectName = BrokerMBeanSupport.createNetworkConnectorName(getBrokerObjectName(), "jmsConnectors", connector.getName());
AnnotatedMBean.registerMBean(getManagementContext(), view, objectName);
} catch (Throwable e) {
throw IOExceptionSupport.create("Broker could not be registered in JMX: " + e.getMessage(), e);
}
}
/**
* Factory method to create a new broker
*
* @throws Exception
* @throws
* @throws
*/
protected Broker createBroker() throws Exception {
regionBroker = createRegionBroker();
Broker broker = addInterceptors(regionBroker);
// Add a filter that will stop access to the broker once stopped
broker = new MutableBrokerFilter(broker) {
Broker old;
@Override
public void stop() throws Exception {
old = this.next.getAndSet(new ErrorBroker("Broker has been stopped: " + this) {
// Just ignore additional stop actions.
@Override
public void stop() throws Exception {
}
});
old.stop();
}
@Override
public void start() throws Exception {
if (forceStart && old != null) {
this.next.set(old);
}
getNext().start();
}
};
return broker;
}
/**
* Factory method to create the core region broker onto which interceptors
* are added
*
* @throws Exception
*/
protected Broker createRegionBroker() throws Exception {
if (destinationInterceptors == null) {
destinationInterceptors = createDefaultDestinationInterceptor();
}
configureServices(destinationInterceptors);
DestinationInterceptor destinationInterceptor = new CompositeDestinationInterceptor(destinationInterceptors);
if (destinationFactory == null) {
destinationFactory = new DestinationFactoryImpl(this, getTaskRunnerFactory(), getPersistenceAdapter());
}
return createRegionBroker(destinationInterceptor);
}
protected Broker createRegionBroker(DestinationInterceptor destinationInterceptor) throws IOException {
RegionBroker regionBroker;
if (isUseJmx()) {
try {
regionBroker = new ManagedRegionBroker(this, getManagementContext(), getBrokerObjectName(),
getTaskRunnerFactory(), getConsumerSystemUsage(), destinationFactory, destinationInterceptor,getScheduler(),getExecutor());
} catch(MalformedObjectNameException me){
LOG.error("Couldn't create ManagedRegionBroker",me);
throw new IOException(me);
}
} else {
regionBroker = new RegionBroker(this, getTaskRunnerFactory(), getConsumerSystemUsage(), destinationFactory,
destinationInterceptor,getScheduler(),getExecutor());
}
destinationFactory.setRegionBroker(regionBroker);
regionBroker.setKeepDurableSubsActive(keepDurableSubsActive);
regionBroker.setBrokerName(getBrokerName());
regionBroker.getDestinationStatistics().setEnabled(enableStatistics);
regionBroker.setAllowTempAutoCreationOnSend(isAllowTempAutoCreationOnSend());
if (brokerId != null) {
regionBroker.setBrokerId(brokerId);
}
return regionBroker;
}
/**
* Create the default destination interceptor
*/
protected DestinationInterceptor[] createDefaultDestinationInterceptor() {
List<DestinationInterceptor> answer = new ArrayList<DestinationInterceptor>();
if (isUseVirtualTopics()) {
VirtualDestinationInterceptor interceptor = new VirtualDestinationInterceptor();
VirtualTopic virtualTopic = new VirtualTopic();
virtualTopic.setName("VirtualTopic.>");
VirtualDestination[] virtualDestinations = { virtualTopic };
interceptor.setVirtualDestinations(virtualDestinations);
answer.add(interceptor);
}
if (isUseMirroredQueues()) {
MirroredQueue interceptor = new MirroredQueue();
answer.add(interceptor);
}
DestinationInterceptor[] array = new DestinationInterceptor[answer.size()];
answer.toArray(array);
return array;
}
/**
* Strategy method to add interceptors to the broker
*
* @throws IOException
*/
protected Broker addInterceptors(Broker broker) throws Exception {
if (isSchedulerSupport()) {
SchedulerBroker sb = new SchedulerBroker(this, broker, getJobSchedulerStore());
if (isUseJmx()) {
JobSchedulerViewMBean view = new JobSchedulerView(sb.getJobScheduler());
try {
ObjectName objectName = BrokerMBeanSupport.createJobSchedulerServiceName(getBrokerObjectName());
AnnotatedMBean.registerMBean(getManagementContext(), view, objectName);
this.adminView.setJMSJobScheduler(objectName);
} catch (Throwable e) {
throw IOExceptionSupport.create("JobScheduler could not be registered in JMX: "
+ e.getMessage(), e);
}
}
broker = sb;
}
if (isUseJmx()) {
HealthViewMBean statusView = new HealthView((ManagedRegionBroker)getRegionBroker());
try {
ObjectName objectName = BrokerMBeanSupport.createHealthServiceName(getBrokerObjectName());
AnnotatedMBean.registerMBean(getManagementContext(), statusView, objectName);
} catch (Throwable e) {
throw IOExceptionSupport.create("Status MBean could not be registered in JMX: "
+ e.getMessage(), e);
}
}
if (isAdvisorySupport()) {
broker = new AdvisoryBroker(broker);
}
broker = new CompositeDestinationBroker(broker);
broker = new TransactionBroker(broker, getPersistenceAdapter().createTransactionStore());
if (isPopulateJMSXUserID()) {
UserIDBroker userIDBroker = new UserIDBroker(broker);
userIDBroker.setUseAuthenticatePrincipal(isUseAuthenticatedPrincipalForJMSXUserID());
broker = userIDBroker;
}
if (isMonitorConnectionSplits()) {
broker = new ConnectionSplitBroker(broker);
}
if (plugins != null) {
for (int i = 0; i < plugins.length; i++) {
BrokerPlugin plugin = plugins[i];
broker = plugin.installPlugin(broker);
}
}
return broker;
}
protected PersistenceAdapter createPersistenceAdapter() throws IOException {
if (isPersistent()) {
PersistenceAdapterFactory fac = getPersistenceFactory();
if (fac != null) {
return fac.createPersistenceAdapter();
} else {
try {
String clazz = "org.apache.activemq.store.kahadb.KahaDBPersistenceAdapter";
PersistenceAdapter adaptor = (PersistenceAdapter)getClass().getClassLoader().loadClass(clazz).newInstance();
File dir = new File(getBrokerDataDirectory(),"KahaDB");
adaptor.setDirectory(dir);
return adaptor;
} catch (Throwable e) {
throw IOExceptionSupport.create(e);
}
}
} else {
return new MemoryPersistenceAdapter();
}
}
protected ObjectName createBrokerObjectName() throws MalformedObjectNameException {
return BrokerMBeanSupport.createBrokerObjectName(getManagementContext().getJmxDomainName(), getBrokerName());
}
protected TransportConnector createTransportConnector(URI brokerURI) throws Exception {
TransportServer transport = TransportFactorySupport.bind(this, brokerURI);
return new TransportConnector(transport);
}
/**
* Extracts the port from the options
*/
protected Object getPort(Map<?,?> options) {
Object port = options.get("port");
if (port == null) {
port = DEFAULT_PORT;
LOG.warn("No port specified so defaulting to: " + port);
}
return port;
}
protected void addShutdownHook() {
if (useShutdownHook) {
shutdownHook = new Thread("ActiveMQ ShutdownHook") {
@Override
public void run() {
containerShutdown();
}
};
Runtime.getRuntime().addShutdownHook(shutdownHook);
}
}
protected void removeShutdownHook() {
if (shutdownHook != null) {
try {
Runtime.getRuntime().removeShutdownHook(shutdownHook);
} catch (Exception e) {
LOG.debug("Caught exception, must be shutting down: " + e);
}
}
}
/**
* Sets hooks to be executed when broker shut down
*
* @org.apache.xbean.Property
*/
public void setShutdownHooks(List<Runnable> hooks) throws Exception {
for (Runnable hook : hooks) {
addShutdownHook(hook);
}
}
/**
* Causes a clean shutdown of the container when the VM is being shut down
*/
protected void containerShutdown() {
try {
stop();
} catch (IOException e) {
Throwable linkedException = e.getCause();
if (linkedException != null) {
logError("Failed to shut down: " + e + ". Reason: " + linkedException, linkedException);
} else {
logError("Failed to shut down: " + e, e);
}
if (!useLoggingForShutdownErrors) {
e.printStackTrace(System.err);
}
} catch (Exception e) {
logError("Failed to shut down: " + e, e);
}
}
protected void logError(String message, Throwable e) {
if (useLoggingForShutdownErrors) {
LOG.error("Failed to shut down: " + e);
} else {
System.err.println("Failed to shut down: " + e);
}
}
/**
* Starts any configured destinations on startup
*/
protected void startDestinations() throws Exception {
if (destinations != null) {
ConnectionContext adminConnectionContext = getAdminConnectionContext();
for (int i = 0; i < destinations.length; i++) {
ActiveMQDestination destination = destinations[i];
getBroker().addDestination(adminConnectionContext, destination,true);
}
}
if (isUseVirtualTopics()) {
startVirtualConsumerDestinations();
}
}
/**
* Returns the broker's administration connection context used for
* configuring the broker at startup
*/
public ConnectionContext getAdminConnectionContext() throws Exception {
return BrokerSupport.getConnectionContext(getBroker());
}
protected void startManagementContext() throws Exception {
getManagementContext().setBrokerName(brokerName);
getManagementContext().start();
adminView = new BrokerView(this, null);
ObjectName objectName = getBrokerObjectName();
AnnotatedMBean.registerMBean(getManagementContext(), adminView, objectName);
}
/**
* Start all transport and network connections, proxies and bridges
*
* @throws Exception
*/
public void startAllConnectors() throws Exception {
Set<ActiveMQDestination> durableDestinations = getBroker().getDurableDestinations();
List<TransportConnector> al = new ArrayList<TransportConnector>();
for (Iterator<TransportConnector> iter = getTransportConnectors().iterator(); iter.hasNext();) {
TransportConnector connector = iter.next();
connector.setBrokerService(this);
al.add(startTransportConnector(connector));
}
if (al.size() > 0) {
// let's clear the transportConnectors list and replace it with
// the started transportConnector instances
this.transportConnectors.clear();
setTransportConnectors(al);
}
this.slave = false;
URI uri = getVmConnectorURI();
Map<String, String> map = new HashMap<String, String>(URISupport.parseParameters(uri));
map.put("network", "true");
map.put("async", "false");
uri = URISupport.createURIWithQuery(uri, URISupport.createQueryString(map));
if (!stopped.get()) {
ThreadPoolExecutor networkConnectorStartExecutor = null;
if (isNetworkConnectorStartAsync()) {
// spin up as many threads as needed
networkConnectorStartExecutor = new ThreadPoolExecutor(0, Integer.MAX_VALUE,
10, TimeUnit.SECONDS, new SynchronousQueue<Runnable>(),
new ThreadFactory() {
int count=0;
@Override
public Thread newThread(Runnable runnable) {
Thread thread = new Thread(runnable, "NetworkConnector Start Thread-" +(count++));
thread.setDaemon(true);
return thread;
}
});
}
for (Iterator<NetworkConnector> iter = getNetworkConnectors().iterator(); iter.hasNext();) {
final NetworkConnector connector = iter.next();
connector.setLocalUri(uri);
connector.setBrokerName(getBrokerName());
connector.setDurableDestinations(durableDestinations);
if (getDefaultSocketURIString() != null) {
connector.setBrokerURL(getDefaultSocketURIString());
}
if (networkConnectorStartExecutor != null) {
networkConnectorStartExecutor.execute(new Runnable() {
@Override
public void run() {
try {
LOG.info("Async start of " + connector);
connector.start();
} catch(Exception e) {
LOG.error("Async start of network connector: " + connector + " failed", e);
}
}
});
} else {
connector.start();
}
}
if (networkConnectorStartExecutor != null) {
// executor done when enqueued tasks are complete
ThreadPoolUtils.shutdown(networkConnectorStartExecutor);
}
for (Iterator<ProxyConnector> iter = getProxyConnectors().iterator(); iter.hasNext();) {
ProxyConnector connector = iter.next();
connector.start();
}
for (Iterator<JmsConnector> iter = jmsConnectors.iterator(); iter.hasNext();) {
JmsConnector connector = iter.next();
connector.start();
}
for (Service service : services) {
configureService(service);
service.start();
}
}
}
protected TransportConnector startTransportConnector(TransportConnector connector) throws Exception {
connector.setTaskRunnerFactory(getTaskRunnerFactory());
MessageAuthorizationPolicy policy = getMessageAuthorizationPolicy();
if (policy != null) {
connector.setMessageAuthorizationPolicy(policy);
}
if (isUseJmx()) {
connector = registerConnectorMBean(connector);
}
connector.getStatistics().setEnabled(enableStatistics);
connector.start();
return connector;
}
/**
* Perform any custom dependency injection
*/
protected void configureServices(Object[] services) {
for (Object service : services) {
configureService(service);
}
}
/**
* Perform any custom dependency injection
*/
protected void configureService(Object service) {
if (service instanceof BrokerServiceAware) {
BrokerServiceAware serviceAware = (BrokerServiceAware) service;
serviceAware.setBrokerService(this);
}
}
public void handleIOException(IOException exception) {
if (ioExceptionHandler != null) {
ioExceptionHandler.handle(exception);
} else {
LOG.info("No IOExceptionHandler registered, ignoring IO exception, " + exception, exception);
}
}
protected void startVirtualConsumerDestinations() throws Exception {
ConnectionContext adminConnectionContext = getAdminConnectionContext();
Set<ActiveMQDestination> destinations = destinationFactory.getDestinations();
DestinationFilter filter = getVirtualTopicConsumerDestinationFilter();
if (!destinations.isEmpty()) {
for (ActiveMQDestination destination : destinations) {
if (filter.matches(destination) == true) {
broker.addDestination(adminConnectionContext, destination, false);
}
}
}
}
private DestinationFilter getVirtualTopicConsumerDestinationFilter() {
// created at startup, so no sync needed
if (virtualConsumerDestinationFilter == null) {
Set <ActiveMQQueue> consumerDestinations = new HashSet<ActiveMQQueue>();
if (destinationInterceptors != null) {
for (DestinationInterceptor interceptor : destinationInterceptors) {
if (interceptor instanceof VirtualDestinationInterceptor) {
VirtualDestinationInterceptor virtualDestinationInterceptor = (VirtualDestinationInterceptor) interceptor;
for (VirtualDestination virtualDestination: virtualDestinationInterceptor.getVirtualDestinations()) {
if (virtualDestination instanceof VirtualTopic) {
consumerDestinations.add(new ActiveMQQueue(((VirtualTopic) virtualDestination).getPrefix() + DestinationFilter.ANY_DESCENDENT));
}
}
}
}
}
ActiveMQQueue filter = new ActiveMQQueue();
filter.setCompositeDestinations(consumerDestinations.toArray(new ActiveMQDestination[]{}));
virtualConsumerDestinationFilter = DestinationFilter.parseFilter(filter);
}
return virtualConsumerDestinationFilter;
}
protected synchronized ThreadPoolExecutor getExecutor() {
if (this.executor == null) {
this.executor = new ThreadPoolExecutor(1, 10, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() {
private long i = 0;
@Override
public Thread newThread(Runnable runnable) {
this.i++;
Thread thread = new Thread(runnable, "ActiveMQ BrokerService.worker." + this.i);
thread.setDaemon(true);
thread.setUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(final Thread t, final Throwable e) {
LOG.error("Error in thread '{}'", t.getName(), e);
}
});
return thread;
}
}, new RejectedExecutionHandler() {
@Override
public void rejectedExecution(final Runnable r, final ThreadPoolExecutor executor) {
try {
executor.getQueue().offer(r, 60, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new RejectedExecutionException("Interrupted waiting for BrokerService.worker");
}
throw new RejectedExecutionException("Timed Out while attempting to enqueue Task.");
}
});
}
return this.executor;
}
public synchronized Scheduler getScheduler() {
if (this.scheduler==null) {
this.scheduler = new Scheduler("ActiveMQ Broker["+getBrokerName()+"] Scheduler");
try {
this.scheduler.start();
} catch (Exception e) {
LOG.error("Failed to start Scheduler ",e);
}
}
return this.scheduler;
}
public Broker getRegionBroker() {
return regionBroker;
}
public void setRegionBroker(Broker regionBroker) {
this.regionBroker = regionBroker;
}
public void addShutdownHook(Runnable hook) {
synchronized (shutdownHooks) {
shutdownHooks.add(hook);
}
}
public void removeShutdownHook(Runnable hook) {
synchronized (shutdownHooks) {
shutdownHooks.remove(hook);
}
}
public boolean isSystemExitOnShutdown() {
return systemExitOnShutdown;
}
/**
* @org.apache.xbean.Property propertyEditor="org.apache.activemq.util.BooleanEditor"
*/
public void setSystemExitOnShutdown(boolean systemExitOnShutdown) {
this.systemExitOnShutdown = systemExitOnShutdown;
}
public int getSystemExitOnShutdownExitCode() {
return systemExitOnShutdownExitCode;
}
public void setSystemExitOnShutdownExitCode(int systemExitOnShutdownExitCode) {
this.systemExitOnShutdownExitCode = systemExitOnShutdownExitCode;
}
public SslContext getSslContext() {
return sslContext;
}
public void setSslContext(SslContext sslContext) {
this.sslContext = sslContext;
}
public boolean isShutdownOnSlaveFailure() {
return shutdownOnSlaveFailure;
}
/**
* @org.apache.xbean.Property propertyEditor="org.apache.activemq.util.BooleanEditor"
*/
public void setShutdownOnSlaveFailure(boolean shutdownOnSlaveFailure) {
this.shutdownOnSlaveFailure = shutdownOnSlaveFailure;
}
public boolean isWaitForSlave() {
return waitForSlave;
}
/**
* @org.apache.xbean.Property propertyEditor="org.apache.activemq.util.BooleanEditor"
*/
public void setWaitForSlave(boolean waitForSlave) {
this.waitForSlave = waitForSlave;
}
public long getWaitForSlaveTimeout() {
return this.waitForSlaveTimeout;
}
public void setWaitForSlaveTimeout(long waitForSlaveTimeout) {
this.waitForSlaveTimeout = waitForSlaveTimeout;
}
/**
* Get the passiveSlave
* @return the passiveSlave
*/
public boolean isPassiveSlave() {
return this.passiveSlave;
}
/**
* Set the passiveSlave
* @param passiveSlave the passiveSlave to set
* @org.apache.xbean.Property propertyEditor="org.apache.activemq.util.BooleanEditor"
*/
public void setPassiveSlave(boolean passiveSlave) {
this.passiveSlave = passiveSlave;
}
/**
* override the Default IOException handler, called when persistence adapter
* has experiences File or JDBC I/O Exceptions
*
* @param ioExceptionHandler
*/
public void setIoExceptionHandler(IOExceptionHandler ioExceptionHandler) {
configureService(ioExceptionHandler);
this.ioExceptionHandler = ioExceptionHandler;
}
public IOExceptionHandler getIoExceptionHandler() {
return ioExceptionHandler;
}
/**
* @return the schedulerSupport
*/
public boolean isSchedulerSupport() {
return this.schedulerSupport;
}
/**
* @param schedulerSupport the schedulerSupport to set
* @org.apache.xbean.Property propertyEditor="org.apache.activemq.util.BooleanEditor"
*/
public void setSchedulerSupport(boolean schedulerSupport) {
this.schedulerSupport = schedulerSupport;
}
/**
* @return the schedulerDirectory
*/
public File getSchedulerDirectoryFile() {
if (this.schedulerDirectoryFile == null) {
this.schedulerDirectoryFile = new File(getBrokerDataDirectory(), "scheduler");
}
return schedulerDirectoryFile;
}
/**
* @param schedulerDirectory the schedulerDirectory to set
*/
public void setSchedulerDirectoryFile(File schedulerDirectory) {
this.schedulerDirectoryFile = schedulerDirectory;
}
public void setSchedulerDirectory(String schedulerDirectory) {
setSchedulerDirectoryFile(new File(schedulerDirectory));
}
public int getSchedulePeriodForDestinationPurge() {
return this.schedulePeriodForDestinationPurge;
}
public void setSchedulePeriodForDestinationPurge(int schedulePeriodForDestinationPurge) {
this.schedulePeriodForDestinationPurge = schedulePeriodForDestinationPurge;
}
public int getMaxPurgedDestinationsPerSweep() {
return this.maxPurgedDestinationsPerSweep;
}
public void setMaxPurgedDestinationsPerSweep(int maxPurgedDestinationsPerSweep) {
this.maxPurgedDestinationsPerSweep = maxPurgedDestinationsPerSweep;
}
public BrokerContext getBrokerContext() {
return brokerContext;
}
public void setBrokerContext(BrokerContext brokerContext) {
this.brokerContext = brokerContext;
}
public void setBrokerId(String brokerId) {
this.brokerId = new BrokerId(brokerId);
}
public boolean isUseAuthenticatedPrincipalForJMSXUserID() {
return useAuthenticatedPrincipalForJMSXUserID;
}
public void setUseAuthenticatedPrincipalForJMSXUserID(boolean useAuthenticatedPrincipalForJMSXUserID) {
this.useAuthenticatedPrincipalForJMSXUserID = useAuthenticatedPrincipalForJMSXUserID;
}
/**
* Should MBeans that support showing the Authenticated User Name information have this
* value filled in or not.
*
* @return true if user names should be exposed in MBeans
*/
public boolean isPopulateUserNameInMBeans() {
return this.populateUserNameInMBeans;
}
/**
* Sets whether Authenticated User Name information is shown in MBeans that support this field.
* @param value if MBeans should expose user name information.
*/
public void setPopulateUserNameInMBeans(boolean value) {
this.populateUserNameInMBeans = value;
}
/**
* Gets the time in Milliseconds that an invocation of an MBean method will wait before
* failing. The default value is to wait forever (zero).
*
* @return timeout in milliseconds before MBean calls fail, (default is 0 or no timeout).
*/
public long getMbeanInvocationTimeout() {
return mbeanInvocationTimeout;
}
/**
* Gets the time in Milliseconds that an invocation of an MBean method will wait before
* failing. The default value is to wait forever (zero).
*
* @param mbeanInvocationTimeout
* timeout in milliseconds before MBean calls fail, (default is 0 or no timeout).
*/
public void setMbeanInvocationTimeout(long mbeanInvocationTimeout) {
this.mbeanInvocationTimeout = mbeanInvocationTimeout;
}
public boolean isNetworkConnectorStartAsync() {
return networkConnectorStartAsync;
}
public void setNetworkConnectorStartAsync(boolean networkConnectorStartAsync) {
this.networkConnectorStartAsync = networkConnectorStartAsync;
}
public boolean isAllowTempAutoCreationOnSend() {
return allowTempAutoCreationOnSend;
}
/**
* enable if temp destinations need to be propagated through a network when
* advisorySupport==false. This is used in conjunction with the policy
* gcInactiveDestinations for matching temps so they can get removed
* when inactive
*
* @param allowTempAutoCreationOnSend
*/
public void setAllowTempAutoCreationOnSend(boolean allowTempAutoCreationOnSend) {
this.allowTempAutoCreationOnSend = allowTempAutoCreationOnSend;
}
public long getOfflineDurableSubscriberTimeout() {
return offlineDurableSubscriberTimeout;
}
public void setOfflineDurableSubscriberTimeout(long offlineDurableSubscriberTimeout) {
this.offlineDurableSubscriberTimeout = offlineDurableSubscriberTimeout;
}
public long getOfflineDurableSubscriberTaskSchedule() {
return offlineDurableSubscriberTaskSchedule;
}
public void setOfflineDurableSubscriberTaskSchedule(long offlineDurableSubscriberTaskSchedule) {
this.offlineDurableSubscriberTaskSchedule = offlineDurableSubscriberTaskSchedule;
}
public boolean shouldRecordVirtualDestination(ActiveMQDestination destination) {
return isUseVirtualTopics() && destination.isQueue() &&
getVirtualTopicConsumerDestinationFilter().matches(destination);
}
public Throwable getStartException() {
return startException;
}
public boolean isStartAsync() {
return startAsync;
}
public void setStartAsync(boolean startAsync) {
this.startAsync = startAsync;
}
public boolean isSlave() {
return this.slave;
}
public boolean isStopping() {
return this.stopping.get();
}
/**
* @return true if the broker allowed to restart on shutdown.
*/
public boolean isRestartAllowed() {
return restartAllowed;
}
/**
* Sets if the broker allowed to restart on shutdown.
* @return
*/
public void setRestartAllowed(boolean restartAllowed) {
this.restartAllowed = restartAllowed;
}
/**
* A lifecycle manager of the BrokerService should
* inspect this property after a broker shutdown has occurred
* to find out if the broker needs to be re-created and started
* again.
*
* @return true if the broker wants to be restarted after it shuts down.
*/
public boolean isRestartRequested() {
return restartRequested;
}
public void requestRestart() {
this.restartRequested = true;
}
public int getStoreOpenWireVersion() {
return storeOpenWireVersion;
}
public void setStoreOpenWireVersion(int storeOpenWireVersion) {
this.storeOpenWireVersion = storeOpenWireVersion;
}
}
| true | true | protected void checkSystemUsageLimits() throws IOException {
SystemUsage usage = getSystemUsage();
long memLimit = usage.getMemoryUsage().getLimit();
long jvmLimit = Runtime.getRuntime().maxMemory();
if (memLimit > jvmLimit) {
LOG.error("Memory Usage for the Broker (" + memLimit / (1024 * 1024) +
" mb) is more than the maximum available for the JVM: " +
jvmLimit / (1024 * 1024) + " mb - resetting to maximum available: " + jvmLimit / (1024 * 1024) + " mb");
usage.getMemoryUsage().setLimit(jvmLimit);
}
if (getPersistenceAdapter() != null) {
PersistenceAdapter adapter = getPersistenceAdapter();
File dir = adapter.getDirectory();
if (dir != null) {
String dirPath = dir.getAbsolutePath();
if (!dir.isAbsolute()) {
dir = new File(dirPath);
}
while (dir != null && dir.isDirectory() == false) {
dir = dir.getParentFile();
}
long storeLimit = usage.getStoreUsage().getLimit();
long dirFreeSpace = dir.getUsableSpace();
if (storeLimit > dirFreeSpace) {
LOG.warn("Store limit is " + storeLimit / (1024 * 1024) +
" mb, whilst the data directory: " + dir.getAbsolutePath() +
" only has " + dirFreeSpace / (1024 * 1024) +
" mb of usable space - resetting to maximum available disk space: " +
dirFreeSpace / (1024 * 1024) + " mb");
usage.getStoreUsage().setLimit(dirFreeSpace);
}
}
long maxJournalFileSize = 0;
long storeLimit = usage.getStoreUsage().getLimit();
if (adapter instanceof JournaledStore) {
maxJournalFileSize = ((JournaledStore) adapter).getJournalMaxFileLength();
}
if (storeLimit < maxJournalFileSize) {
LOG.error("Store limit is " + storeLimit / (1024 * 1024) +
" mb, whilst the max journal file size for the store is: " +
maxJournalFileSize / (1024 * 1024) + " mb, " +
"the store will not accept any data when used.");
}
}
File tmpDir = getTmpDataDirectory();
if (tmpDir != null) {
String tmpDirPath = tmpDir.getAbsolutePath();
if (!tmpDir.isAbsolute()) {
tmpDir = new File(tmpDirPath);
}
long storeLimit = usage.getTempUsage().getLimit();
while (tmpDir != null && tmpDir.isDirectory() == false) {
tmpDir = tmpDir.getParentFile();
}
long dirFreeSpace = tmpDir.getUsableSpace();
if (storeLimit > dirFreeSpace) {
LOG.error("Temporary Store limit is " + storeLimit / (1024 * 1024) +
" mb, whilst the temporary data directory: " + tmpDirPath +
" only has " + dirFreeSpace / (1024 * 1024) + " mb of usable space - resetting to maximum available " +
dirFreeSpace / (1024 * 1024) + " mb.");
usage.getTempUsage().setLimit(dirFreeSpace);
}
if (isPersistent()) {
long maxJournalFileSize;
PListStore store = usage.getTempUsage().getStore();
if (store != null && store instanceof JournaledStore) {
maxJournalFileSize = ((JournaledStore) store).getJournalMaxFileLength();
} else {
maxJournalFileSize = DEFAULT_MAX_FILE_LENGTH;
}
if (storeLimit < maxJournalFileSize) {
LOG.error("Temporary Store limit is " + storeLimit / (1024 * 1024) +
" mb, whilst the max journal file size for the temporary store is: " +
maxJournalFileSize / (1024 * 1024) + " mb, " +
"the temp store will not accept any data when used.");
}
}
}
if (getJobSchedulerStore() != null) {
JobSchedulerStore scheduler = getJobSchedulerStore();
File schedulerDir = scheduler.getDirectory();
if (schedulerDir != null) {
String schedulerDirPath = schedulerDir.getAbsolutePath();
if (!schedulerDir.isAbsolute()) {
schedulerDir = new File(schedulerDirPath);
}
while (schedulerDir != null && schedulerDir.isDirectory() == false) {
schedulerDir = schedulerDir.getParentFile();
}
long schedularLimit = usage.getJobSchedulerUsage().getLimit();
long dirFreeSpace = schedulerDir.getUsableSpace();
if (schedularLimit > dirFreeSpace) {
LOG.warn("Job Schedular Store limit is " + schedularLimit / (1024 * 1024) +
" mb, whilst the data directory: " + schedulerDir.getAbsolutePath() +
" only has " + dirFreeSpace / (1024 * 1024) + " mb of usable space - reseting to " +
dirFreeSpace / (1024 * 1024) + " mb.");
usage.getJobSchedulerUsage().setLimit(dirFreeSpace);
}
}
}
}
| protected void checkSystemUsageLimits() throws IOException {
SystemUsage usage = getSystemUsage();
long memLimit = usage.getMemoryUsage().getLimit();
long jvmLimit = Runtime.getRuntime().maxMemory();
if (memLimit > jvmLimit) {
LOG.error("Memory Usage for the Broker (" + memLimit / (1024 * 1024) +
" mb) is more than the maximum available for the JVM: " +
jvmLimit / (1024 * 1024) + " mb - resetting to maximum available: " + jvmLimit / (1024 * 1024) + " mb");
usage.getMemoryUsage().setLimit(jvmLimit);
}
if (getPersistenceAdapter() != null) {
PersistenceAdapter adapter = getPersistenceAdapter();
File dir = adapter.getDirectory();
if (dir != null) {
String dirPath = dir.getAbsolutePath();
if (!dir.isAbsolute()) {
dir = new File(dirPath);
}
while (dir != null && dir.isDirectory() == false) {
dir = dir.getParentFile();
}
long storeLimit = usage.getStoreUsage().getLimit();
long dirFreeSpace = dir.getUsableSpace();
if (storeLimit > dirFreeSpace) {
LOG.warn("Store limit is " + storeLimit / (1024 * 1024) +
" mb, whilst the data directory: " + dir.getAbsolutePath() +
" only has " + dirFreeSpace / (1024 * 1024) +
" mb of usable space - resetting to maximum available disk space: " +
dirFreeSpace / (1024 * 1024) + " mb");
usage.getStoreUsage().setLimit(dirFreeSpace);
}
}
long maxJournalFileSize = 0;
long storeLimit = usage.getStoreUsage().getLimit();
if (adapter instanceof JournaledStore) {
maxJournalFileSize = ((JournaledStore) adapter).getJournalMaxFileLength();
}
if (storeLimit < maxJournalFileSize) {
LOG.error("Store limit is " + storeLimit / (1024 * 1024) +
" mb, whilst the max journal file size for the store is: " +
maxJournalFileSize / (1024 * 1024) + " mb, " +
"the store will not accept any data when used.");
}
}
File tmpDir = getTmpDataDirectory();
if (tmpDir != null) {
String tmpDirPath = tmpDir.getAbsolutePath();
if (!tmpDir.isAbsolute()) {
tmpDir = new File(tmpDirPath);
}
long storeLimit = usage.getTempUsage().getLimit();
while (tmpDir != null && tmpDir.isDirectory() == false) {
tmpDir = tmpDir.getParentFile();
}
long dirFreeSpace = tmpDir.getUsableSpace();
if (storeLimit > dirFreeSpace) {
LOG.error("Temporary Store limit is " + storeLimit / (1024 * 1024) +
" mb, whilst the temporary data directory: " + tmpDirPath +
" only has " + dirFreeSpace / (1024 * 1024) + " mb of usable space - resetting to maximum available " +
dirFreeSpace / (1024 * 1024) + " mb.");
usage.getTempUsage().setLimit(dirFreeSpace);
}
if (isPersistent()) {
long maxJournalFileSize;
PListStore store = usage.getTempUsage().getStore();
if (store != null && store instanceof JournaledStore) {
maxJournalFileSize = ((JournaledStore) store).getJournalMaxFileLength();
} else {
maxJournalFileSize = DEFAULT_MAX_FILE_LENGTH;
}
if (storeLimit < maxJournalFileSize) {
LOG.error("Temporary Store limit is " + storeLimit / (1024 * 1024) +
" mb, whilst the max journal file size for the temporary store is: " +
maxJournalFileSize / (1024 * 1024) + " mb, " +
"the temp store will not accept any data when used.");
}
}
}
if (getJobSchedulerStore() != null) {
JobSchedulerStore scheduler = getJobSchedulerStore();
File schedulerDir = scheduler.getDirectory();
if (schedulerDir != null) {
String schedulerDirPath = schedulerDir.getAbsolutePath();
if (!schedulerDir.isAbsolute()) {
schedulerDir = new File(schedulerDirPath);
}
while (schedulerDir != null && schedulerDir.isDirectory() == false) {
schedulerDir = schedulerDir.getParentFile();
}
long schedularLimit = usage.getJobSchedulerUsage().getLimit();
long dirFreeSpace = schedulerDir.getUsableSpace();
if (schedularLimit > dirFreeSpace) {
LOG.warn("Job Schedular Store limit is " + schedularLimit / (1024 * 1024) +
" mb, whilst the data directory: " + schedulerDir.getAbsolutePath() +
" only has " + dirFreeSpace / (1024 * 1024) + " mb of usable space - resetting to " +
dirFreeSpace / (1024 * 1024) + " mb.");
usage.getJobSchedulerUsage().setLimit(dirFreeSpace);
}
}
}
}
|
diff --git a/opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/administration/database/presenter/Resources.java b/opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/administration/database/presenter/Resources.java
index c5894d6a5..7ba8b4481 100644
--- a/opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/administration/database/presenter/Resources.java
+++ b/opal-gwt-client/src/main/java/org/obiba/opal/web/gwt/app/client/administration/database/presenter/Resources.java
@@ -1,35 +1,37 @@
/*******************************************************************************
* Copyright (c) 2012 OBiBa. All rights reserved.
*
* This program and the accompanying materials
* are made available under the terms of the GNU Public License v3.0.
*
* 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.obiba.opal.web.gwt.app.client.administration.database.presenter;
final class Resources {
static String databases() {
return "/jdbc/databases";
}
static String database(String name) {
return "/jdbc/database/" + name;
}
static String database(String name, String... more) {
String r = database(name);
if(more != null) {
+ StringBuilder sb = new StringBuilder(r);
for(String s : more) {
- r += "/" + s;
+ sb.append("/").append(s);
}
+ r = sb.toString();
}
return r;
}
public static String drivers() {
return "/jdbc/drivers";
}
}
| false | true | static String database(String name, String... more) {
String r = database(name);
if(more != null) {
for(String s : more) {
r += "/" + s;
}
}
return r;
}
| static String database(String name, String... more) {
String r = database(name);
if(more != null) {
StringBuilder sb = new StringBuilder(r);
for(String s : more) {
sb.append("/").append(s);
}
r = sb.toString();
}
return r;
}
|
diff --git a/src/main/java/drinkcounter/web/controllers/ui/UserController.java b/src/main/java/drinkcounter/web/controllers/ui/UserController.java
index 5a71fa8..e578617 100644
--- a/src/main/java/drinkcounter/web/controllers/ui/UserController.java
+++ b/src/main/java/drinkcounter/web/controllers/ui/UserController.java
@@ -1,188 +1,189 @@
package drinkcounter.web.controllers.ui;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import drinkcounter.model.User;
import drinkcounter.DrinkCounterService;
import drinkcounter.UserService;
import drinkcounter.authentication.AuthenticationChecks;
import drinkcounter.authentication.NotLoggedInException;
import drinkcounter.model.Party;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
/**
*
* @author murgo
*/
@Controller
public class UserController {
@Autowired private DrinkCounterService drinkCounterService;
@Autowired private UserService userService;
@Autowired private AuthenticationChecks authenticationChecks;
@RequestMapping("/addUser")
public String addUser(
@RequestParam("name") String name,
@RequestParam("sex") String sex,
@RequestParam("weight") float weight,
@RequestParam("email") String email,
HttpSession session){
String openId = (String)session.getAttribute(AuthenticationController.OPENID);
if (openId == null)
throw new NotLoggedInException();
if (name == null || name.length() == 0 || weight < 1 || !userService.emailIsCorrect(email) || userService.getUserByEmail(email) != null)
throw new IllegalArgumentException();
User user = new User();
user.setName(name);
user.setSex(User.Sex.valueOf(sex));
user.setWeight(weight);
user.setOpenId(openId);
user.setEmail(email);
userService.addUser(user);
return "redirect:user";
}
@RequestMapping("/modifyUser")
public String modifyUser(
@RequestParam("userId") String userId,
@RequestParam("name") String name,
@RequestParam("sex") String sex,
@RequestParam("weight") float weight,
@RequestParam("email") String email,
HttpSession session){
String openId = (String)session.getAttribute(AuthenticationController.OPENID);
int uid = Integer.parseInt(userId);
authenticationChecks.checkLowLevelRightsToUser(openId, uid);
User user = userService.getUser(uid);
if (!user.getEmail().equalsIgnoreCase(email) && (!userService.emailIsCorrect(email) || userService.getUserByEmail(email) != null))
throw new IllegalArgumentException();
if (name == null || name.length() == 0 || weight < 1)
throw new IllegalArgumentException();
user.setName(name);
user.setSex(User.Sex.valueOf(sex));
user.setWeight(weight);
user.setOpenId(openId);
user.setEmail(email);
userService.updateUser(user);
return "redirect:user";
}
@RequestMapping("/addDrink")
public String addDrink(HttpSession session, @RequestParam("id") String userId){
String openId = (String)session.getAttribute(AuthenticationController.OPENID);
int id = Integer.parseInt(userId);
authenticationChecks.checkHighLevelRightsToUser(openId, id);
drinkCounterService.addDrink(id);
return "redirect:parties";
}
@RequestMapping("/addDrinkToDate")
public String addDrinkToDate(HttpSession session, @RequestParam("userId") String userId, @RequestParam("date") String date){
String openId = (String)session.getAttribute(AuthenticationController.OPENID);
int id = Integer.parseInt(userId);
authenticationChecks.checkHighLevelRightsToUser(openId, id);
drinkCounterService.addDrinkToDate(id, date);
return "redirect:user";
}
@RequestMapping("/removeDrink")
public String removeDrink(HttpSession session, @RequestParam("userId") String userId, @RequestParam("drinkId") String drinkId){
String openId = (String)session.getAttribute(AuthenticationController.OPENID);
int id = Integer.parseInt(userId);
authenticationChecks.checkLowLevelRightsToUser(openId, id);
drinkCounterService.removeDrinkFromUser(id, Integer.parseInt(drinkId));
return "redirect:user";
}
@RequestMapping("/user")
public ModelAndView userPage(HttpSession session){
String openId = (String)session.getAttribute(AuthenticationController.OPENID);
authenticationChecks.checkLogin(openId);
User user = userService.getUserByOpenId(openId);
ModelAndView mav = new ModelAndView();
mav.setViewName("user");
mav.addObject("user", user);
mav.addObject("parties", user.getParties());
return mav;
}
@RequestMapping("/newuser")
public ModelAndView newUser(HttpSession session){
String openId = (String)session.getAttribute(AuthenticationController.OPENID);
if (openId == null)
throw new NotLoggedInException();
ModelAndView mav = new ModelAndView();
mav.setViewName("newuser");
return mav;
}
@RequestMapping("/checkEmail")
public ResponseEntity<byte[]> checkEmail(HttpSession session, @RequestParam("email") String email){
String openId = (String)session.getAttribute(AuthenticationController.OPENID);
if (openId == null)
throw new NotLoggedInException();
String data = userService.emailIsCorrect(email) && userService.getUserByEmail(email) == null ? "1" : "0";
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "text/plain;charset=utf-8");
return new ResponseEntity<byte[]>(data.getBytes(), headers, HttpStatus.OK);
}
@RequestMapping("/getUserByEmail")
public ResponseEntity<byte[]> getUserNotInPartyByEmail(HttpSession session, @RequestParam("email") String email, @RequestParam("partyId") String partyId){
+ System.out.println(email);
String openId = (String)session.getAttribute(AuthenticationController.OPENID);
int id = Integer.parseInt(partyId);
authenticationChecks.checkRightsForParty(openId, id);
String data = "";
if (!userService.emailIsCorrect(email))
data = "0";
User user = userService.getUserByEmail(email);
if (user == null)
data = "0";
else {
// TODO optimize by query
List<Party> parties = user.getParties();
data = Integer.toString(user.getId());
for (Party p : parties) {
if (p.getId() == id) {
// user is already in party
data = "0";
break;
}
}
}
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "text/plain;charset=utf-8");
return new ResponseEntity<byte[]>(data.getBytes(), headers, HttpStatus.OK);
}
}
| true | true | public ResponseEntity<byte[]> getUserNotInPartyByEmail(HttpSession session, @RequestParam("email") String email, @RequestParam("partyId") String partyId){
String openId = (String)session.getAttribute(AuthenticationController.OPENID);
int id = Integer.parseInt(partyId);
authenticationChecks.checkRightsForParty(openId, id);
String data = "";
if (!userService.emailIsCorrect(email))
data = "0";
User user = userService.getUserByEmail(email);
if (user == null)
data = "0";
else {
// TODO optimize by query
List<Party> parties = user.getParties();
data = Integer.toString(user.getId());
for (Party p : parties) {
if (p.getId() == id) {
// user is already in party
data = "0";
break;
}
}
}
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "text/plain;charset=utf-8");
return new ResponseEntity<byte[]>(data.getBytes(), headers, HttpStatus.OK);
}
| public ResponseEntity<byte[]> getUserNotInPartyByEmail(HttpSession session, @RequestParam("email") String email, @RequestParam("partyId") String partyId){
System.out.println(email);
String openId = (String)session.getAttribute(AuthenticationController.OPENID);
int id = Integer.parseInt(partyId);
authenticationChecks.checkRightsForParty(openId, id);
String data = "";
if (!userService.emailIsCorrect(email))
data = "0";
User user = userService.getUserByEmail(email);
if (user == null)
data = "0";
else {
// TODO optimize by query
List<Party> parties = user.getParties();
data = Integer.toString(user.getId());
for (Party p : parties) {
if (p.getId() == id) {
// user is already in party
data = "0";
break;
}
}
}
HttpHeaders headers = new HttpHeaders();
headers.set("Content-Type", "text/plain;charset=utf-8");
return new ResponseEntity<byte[]>(data.getBytes(), headers, HttpStatus.OK);
}
|
diff --git a/luni/src/main/java/java/text/SimpleDateFormat.java b/luni/src/main/java/java/text/SimpleDateFormat.java
index 46ecc1af3..19855b5d0 100644
--- a/luni/src/main/java/java/text/SimpleDateFormat.java
+++ b/luni/src/main/java/java/text/SimpleDateFormat.java
@@ -1,1302 +1,1302 @@
/*
* 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 java.text;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamField;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import java.util.Locale;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
import libcore.icu.LocaleData;
import libcore.icu.TimeZones;
/**
* A concrete class for formatting and parsing dates in a locale-sensitive
* manner. Formatting turns a {@link Date} into a {@link String}, and parsing turns a
* {@code String} into a {@code Date}.
*
* <h4>Time Pattern Syntax</h4>
* <p>You can supply a pattern describing what strings are produced/accepted, but almost all
* callers should use {@link DateFormat#getDateInstance}, {@link DateFormat#getDateTimeInstance},
* or {@link DateFormat#getTimeInstance} to get a ready-made instance suitable for the user's
* locale.
*
* <p>The main reason you'd create an instance this class directly is because you need to
* format/parse a specific machine-readable format, in which case you almost certainly want
* to explicitly ask for {@link Locale#US} to ensure that you get ASCII digits (rather than,
* say, Arabic digits).
* (See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".)
* The most useful non-localized pattern is {@code "yyyy-MM-dd HH:mm:ss.SSSZ"}, which corresponds
* to the ISO 8601 international standard date format.
*
* <p>To specify the time format, use a <i>time pattern</i> string. In this
* string, any character from {@code 'A'} to {@code 'Z'} or {@code 'a'} to {@code 'z'} is
* treated specially. All other characters are passed through verbatim. The interpretation of each
* of the ASCII letters is given in the table below. ASCII letters not appearing in the table are
* reserved for future use, and it is an error to attempt to use them.
*
* <p><table BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
* <tr BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
* <td><B>Symbol</B></td> <td><B>Meaning</B></td> <td><B>Presentation</B></td> <td><B>Example</B></td> </tr>
* <tr> <td>{@code D}</td> <td>day in year</td> <td>(Number)</td> <td>189</td> </tr>
* <tr> <td>{@code E}</td> <td>day of week</td> <td>(Text)</td> <td>Tuesday</td> </tr>
* <tr> <td>{@code F}</td> <td>day of week in month</td> <td>(Number)</td> <td>2 <i>(2nd Wed in July)</i></td> </tr>
* <tr> <td>{@code G}</td> <td>era designator</td> <td>(Text)</td> <td>AD</td> </tr>
* <tr> <td>{@code H}</td> <td>hour in day (0-23)</td> <td>(Number)</td> <td>0</td> </tr>
* <tr> <td>{@code K}</td> <td>hour in am/pm (0-11)</td> <td>(Number)</td> <td>0</td> </tr>
* <tr> <td>{@code L}</td> <td>stand-alone month</td> <td>(Text/Number)</td> <td>July / 07</td> </tr>
* <tr> <td>{@code M}</td> <td>month in year</td> <td>(Text/Number)</td> <td>July / 07</td> </tr>
* <tr> <td>{@code S}</td> <td>fractional seconds</td> <td>(Number)</td> <td>978</td> </tr>
* <tr> <td>{@code W}</td> <td>week in month</td> <td>(Number)</td> <td>2</td> </tr>
* <tr> <td>{@code Z}</td> <td>time zone (RFC 822)</td> <td>(Timezone)</td> <td>-0800</td> </tr>
* <tr> <td>{@code a}</td> <td>am/pm marker</td> <td>(Text)</td> <td>PM</td> </tr>
* <tr> <td>{@code c}</td> <td>stand-alone day of week</td> <td>(Text/Number)</td> <td>Tuesday / 2</td> </tr>
* <tr> <td>{@code d}</td> <td>day in month</td> <td>(Number)</td> <td>10</td> </tr>
* <tr> <td>{@code h}</td> <td>hour in am/pm (1-12)</td> <td>(Number)</td> <td>12</td> </tr>
* <tr> <td>{@code k}</td> <td>hour in day (1-24)</td> <td>(Number)</td> <td>24</td> </tr>
* <tr> <td>{@code m}</td> <td>minute in hour</td> <td>(Number)</td> <td>30</td> </tr>
* <tr> <td>{@code s}</td> <td>second in minute</td> <td>(Number)</td> <td>55</td> </tr>
* <tr> <td>{@code w}</td> <td>week in year</td> <td>(Number)</td> <td>27</td> </tr>
* <tr> <td>{@code y}</td> <td>year</td> <td>(Number)</td> <td>2010</td> </tr>
* <tr> <td>{@code z}</td> <td>time zone</td> <td>(Timezone)</td> <td>Pacific Standard Time</td> </tr>
* <tr> <td>{@code '}</td> <td>escape for text</td> <td>(Delimiter)</td> <td>'Date='</td> </tr>
* <tr> <td>{@code ''}</td> <td>single quote</td> <td>(Literal)</td> <td>'o''clock'</td> </tr>
* </table>
*
* <p>The number of consecutive copies (the "count") of a pattern character further influences
* the format.
* <ul>
* <li><b>Text</b> if the count is 4 or more, use the full form; otherwise use a short or
* abbreviated form if one exists. So {@code zzzz} might give {@code Pacific Standard Time}
* whereas {@code z} might give {@code PST}. Note that the count does <i>not</i> specify the
* exact width of the field.
*
* <li><b>Number</b> the count is the minimum number of digits. Shorter values are
* zero-padded to this width, longer values overflow this width.
*
* <p>Years are handled specially: {@code yy} truncates to the last 2 digits, but any
* other number of consecutive {@code y}s does not truncate. So where {@code yyyy} or
* {@code y} might give {@code 2010}, {@code yy} would give {@code 10}.
*
* <p>Fractional seconds are also handled specially: they're zero-padded on the
* <i>right</i>.
*
* <li><b>Text/Number</b>: if the count is 3 or more, use text; otherwise use a number.
* So {@code MM} might give {@code 07} while {@code MMM} gives {@code July}.
* </ul>
*
* <p>The two pattern characters {@code L} and {@code c} are ICU-compatible extensions, not
* available in the RI. These are necessary for correct localization in languages such as Russian
* that distinguish between, say, "June" and "June 2010".
*
* <p>When numeric fields are adjacent directly, with no intervening delimiter
* characters, they constitute a run of adjacent numeric fields. Such runs are
* parsed specially. For example, the format "HHmmss" parses the input text
* "123456" to 12:34:56, parses the input text "12345" to 1:23:45, and fails to
* parse "1234". In other words, the leftmost field of the run is flexible,
* while the others keep a fixed width. If the parse fails anywhere in the run,
* then the leftmost field is shortened by one character, and the entire run is
* parsed again. This is repeated until either the parse succeeds or the
* leftmost field is one character in length. If the parse still fails at that
* point, the parse of the run fails.
*
* <p>See {@link #set2DigitYearStart} for more about handling two-digit years.
*
* <h4>Sample Code</h4>
* <p>If you're formatting for human use, you should use an instance returned from
* {@link DateFormat} as described above. This code:
* <pre>
* DateFormat[] formats = new DateFormat[] {
* DateFormat.getDateInstance(),
* DateFormat.getDateTimeInstance(),
* DateFormat.getTimeInstance(),
* };
* for (DateFormat df : formats) {
* System.err.println(df.format(new Date(0)));
* }
* </pre>
*
* <p>Produces this output when run on an {@code en_US} device in the PDT time zone:
* <pre>
* Dec 31, 1969
* Dec 31, 1969 4:00:00 PM
* 4:00:00 PM
* </pre>
* And will produce similarly appropriate localized human-readable output on any user's system.
*
* <p>If you're formatting for machine use, consider this code:
* <pre>
* String[] formats = new String[] {
* "yyyy-MM-dd",
* "yyyy-MM-dd HH:mm",
* "yyyy-MM-dd HH:mmZ",
* "yyyy-MM-dd HH:mm:ss.SSSZ",
* "yyyy-MM-dd'T'HH:mm:ss.SSSZ",
* };
* for (String format : formats) {
* SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.US);
* System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
* sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
* System.err.format("%30s %s\n", format, sdf.format(new Date(0)));
* }
* </pre>
*
* <p>Which produces this output when run in the PDT time zone:
* <pre>
* yyyy-MM-dd 1969-12-31
* yyyy-MM-dd 1970-01-01
* yyyy-MM-dd HH:mm 1969-12-31 16:00
* yyyy-MM-dd HH:mm 1970-01-01 00:00
* yyyy-MM-dd HH:mmZ 1969-12-31 16:00-0800
* yyyy-MM-dd HH:mmZ 1970-01-01 00:00+0000
* yyyy-MM-dd HH:mm:ss.SSSZ 1969-12-31 16:00:00.000-0800
* yyyy-MM-dd HH:mm:ss.SSSZ 1970-01-01 00:00:00.000+0000
* yyyy-MM-dd'T'HH:mm:ss.SSSZ 1969-12-31T16:00:00.000-0800
* yyyy-MM-dd'T'HH:mm:ss.SSSZ 1970-01-01T00:00:00.000+0000
* </pre>
*
* <p>As this example shows, each {@code SimpleDateFormat} instance has a {@link TimeZone}.
* This is because it's called upon to format instances of {@code Date}, which represents an
* absolute time in UTC. That is, {@code Date} does not carry time zone information.
* By default, {@code SimpleDateFormat} will use the system's default time zone. This is
* appropriate for human-readable output (for which, see the previous sample instead), but
* generally inappropriate for machine-readable output, where ambiguity is a problem. Note that
* in this example, the output that included a time but no time zone cannot be parsed back into
* the original {@code Date}. For this
* reason it is almost always necessary and desirable to include the timezone in the output.
* It may also be desirable to set the formatter's time zone to UTC (to ease comparison, or to
* make logs more readable, for example).
*
* <h4>Synchronization</h4>
* {@code SimpleDateFormat} is not thread-safe. Users should create a separate instance for
* each thread.
*
* @see java.util.Calendar
* @see java.util.Date
* @see java.util.TimeZone
* @see java.text.DateFormat
*/
public class SimpleDateFormat extends DateFormat {
private static final long serialVersionUID = 4774881970558875024L;
// 'L' and 'c' are ICU-compatible extensions for stand-alone month and stand-alone weekday.
static final String PATTERN_CHARS = "GyMdkHmsSEDFwWahKzZLc";
// The index of 'Z' in the PATTERN_CHARS string. This pattern character is supported by the RI,
// but has no corresponding public constant.
private static final int RFC_822_TIMEZONE_FIELD = 18;
// The index of 'L' (cf. 'M') in the PATTERN_CHARS string. This is an ICU-compatible extension
// necessary for correct localization in various languages (http://b/2633414).
private static final int STAND_ALONE_MONTH_FIELD = 19;
// The index of 'c' (cf. 'E') in the PATTERN_CHARS string. This is an ICU-compatible extension
// necessary for correct localization in various languages (http://b/2633414).
private static final int STAND_ALONE_DAY_OF_WEEK_FIELD = 20;
private String pattern;
private DateFormatSymbols formatData;
transient private int creationYear;
private Date defaultCenturyStart;
/**
* Constructs a new {@code SimpleDateFormat} for formatting and parsing
* dates and times in the {@code SHORT} style for the user's default locale.
* See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".
*/
public SimpleDateFormat() {
this(Locale.getDefault());
this.pattern = defaultPattern();
this.formatData = new DateFormatSymbols(Locale.getDefault());
}
/**
* Constructs a new {@code SimpleDateFormat} using the specified
* non-localized pattern and the {@code DateFormatSymbols} and {@code
* Calendar} for the user's default locale.
* See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".
*
* @param pattern
* the pattern.
* @throws NullPointerException
* if the pattern is {@code null}.
* @throws IllegalArgumentException
* if {@code pattern} is not considered to be usable by this
* formatter.
*/
public SimpleDateFormat(String pattern) {
this(pattern, Locale.getDefault());
}
/**
* Validates the format character.
*
* @param format
* the format character
*
* @throws IllegalArgumentException
* when the format character is invalid
*/
private void validateFormat(char format) {
int index = PATTERN_CHARS.indexOf(format);
if (index == -1) {
throw new IllegalArgumentException("Unknown pattern character '" + format + "'");
}
}
/**
* Validates the pattern.
*
* @param template
* the pattern to validate.
*
* @throws NullPointerException
* if the pattern is null
* @throws IllegalArgumentException
* if the pattern is invalid
*/
private void validatePattern(String template) {
boolean quote = false;
int next, last = -1, count = 0;
final int patternLength = template.length();
for (int i = 0; i < patternLength; i++) {
next = (template.charAt(i));
if (next == '\'') {
if (count > 0) {
validateFormat((char) last);
count = 0;
}
if (last == next) {
last = -1;
} else {
last = next;
}
quote = !quote;
continue;
}
if (!quote
&& (last == next || (next >= 'a' && next <= 'z') || (next >= 'A' && next <= 'Z'))) {
if (last == next) {
count++;
} else {
if (count > 0) {
validateFormat((char) last);
}
last = next;
count = 1;
}
} else {
if (count > 0) {
validateFormat((char) last);
count = 0;
}
last = -1;
}
}
if (count > 0) {
validateFormat((char) last);
}
if (quote) {
throw new IllegalArgumentException("Unterminated quote");
}
}
/**
* Constructs a new {@code SimpleDateFormat} using the specified
* non-localized pattern and {@code DateFormatSymbols} and the {@code
* Calendar} for the user's default locale.
* See "<a href="../util/Locale.html#default_locale">Be wary of the default locale</a>".
*
* @param template
* the pattern.
* @param value
* the DateFormatSymbols.
* @throws NullPointerException
* if the pattern is {@code null}.
* @throws IllegalArgumentException
* if the pattern is invalid.
*/
public SimpleDateFormat(String template, DateFormatSymbols value) {
this(Locale.getDefault());
validatePattern(template);
pattern = template;
formatData = (DateFormatSymbols) value.clone();
}
/**
* Constructs a new {@code SimpleDateFormat} using the specified
* non-localized pattern and the {@code DateFormatSymbols} and {@code
* Calendar} for the specified locale.
*
* @param template
* the pattern.
* @param locale
* the locale.
* @throws NullPointerException
* if the pattern is {@code null}.
* @throws IllegalArgumentException
* if the pattern is invalid.
*/
public SimpleDateFormat(String template, Locale locale) {
this(locale);
validatePattern(template);
pattern = template;
formatData = new DateFormatSymbols(locale);
}
private SimpleDateFormat(Locale locale) {
numberFormat = NumberFormat.getInstance(locale);
numberFormat.setParseIntegerOnly(true);
numberFormat.setGroupingUsed(false);
calendar = new GregorianCalendar(locale);
calendar.add(Calendar.YEAR, -80);
creationYear = calendar.get(Calendar.YEAR);
defaultCenturyStart = calendar.getTime();
}
/**
* Changes the pattern of this simple date format to the specified pattern
* which uses localized pattern characters.
*
* @param template
* the localized pattern.
*/
public void applyLocalizedPattern(String template) {
pattern = convertPattern(template, formatData.getLocalPatternChars(), PATTERN_CHARS, true);
}
/**
* Changes the pattern of this simple date format to the specified pattern
* which uses non-localized pattern characters.
*
* @param template
* the non-localized pattern.
* @throws NullPointerException
* if the pattern is {@code null}.
* @throws IllegalArgumentException
* if the pattern is invalid.
*/
public void applyPattern(String template) {
validatePattern(template);
pattern = template;
}
/**
* Returns a new {@code SimpleDateFormat} with the same pattern and
* properties as this simple date format.
*
* @return a shallow copy of this simple date format.
* @see java.lang.Cloneable
*/
@Override
public Object clone() {
SimpleDateFormat clone = (SimpleDateFormat) super.clone();
clone.formatData = (DateFormatSymbols) formatData.clone();
clone.defaultCenturyStart = new Date(defaultCenturyStart.getTime());
return clone;
}
private static String defaultPattern() {
LocaleData localeData = LocaleData.get(Locale.getDefault());
return localeData.getDateFormat(SHORT) + " " + localeData.getTimeFormat(SHORT);
}
/**
* Compares the specified object with this simple date format and indicates
* if they are equal. In order to be equal, {@code object} must be an
* instance of {@code SimpleDateFormat} and have the same {@code DateFormat}
* properties, pattern, {@code DateFormatSymbols} and creation year.
*
* @param object
* the object to compare with this object.
* @return {@code true} if the specified object is equal to this simple date
* format; {@code false} otherwise.
* @see #hashCode
*/
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (!(object instanceof SimpleDateFormat)) {
return false;
}
SimpleDateFormat simple = (SimpleDateFormat) object;
return super.equals(object) && pattern.equals(simple.pattern)
&& formatData.equals(simple.formatData);
}
/**
* Formats the specified object using the rules of this simple date format
* and returns an {@code AttributedCharacterIterator} with the formatted
* date and attributes.
*
* @param object
* the object to format.
* @return an {@code AttributedCharacterIterator} with the formatted date
* and attributes.
* @throws NullPointerException
* if the object is {@code null}.
* @throws IllegalArgumentException
* if the object cannot be formatted by this simple date
* format.
*/
@Override
public AttributedCharacterIterator formatToCharacterIterator(Object object) {
if (object == null) {
throw new NullPointerException();
}
if (object instanceof Date) {
return formatToCharacterIteratorImpl((Date) object);
}
if (object instanceof Number) {
return formatToCharacterIteratorImpl(new Date(((Number) object).longValue()));
}
throw new IllegalArgumentException();
}
private AttributedCharacterIterator formatToCharacterIteratorImpl(Date date) {
StringBuffer buffer = new StringBuffer();
ArrayList<FieldPosition> fields = new ArrayList<FieldPosition>();
// format the date, and find fields
formatImpl(date, buffer, null, fields);
// create and AttributedString with the formatted buffer
AttributedString as = new AttributedString(buffer.toString());
// add DateFormat field attributes to the AttributedString
for (FieldPosition pos : fields) {
Format.Field attribute = pos.getFieldAttribute();
as.addAttribute(attribute, attribute, pos.getBeginIndex(), pos.getEndIndex());
}
// return the CharacterIterator from AttributedString
return as.getIterator();
}
/**
* Formats the date.
* <p>
* If the FieldPosition {@code field} is not null, and the field
* specified by this FieldPosition is formatted, set the begin and end index
* of the formatted field in the FieldPosition.
* <p>
* If the list {@code fields} is not null, find fields of this
* date, set FieldPositions with these fields, and add them to the fields
* vector.
*
* @param date
* Date to Format
* @param buffer
* StringBuffer to store the resulting formatted String
* @param field
* FieldPosition to set begin and end index of the field
* specified, if it is part of the format for this date
* @param fields
* list used to store the FieldPositions for each field in this
* date
* @return the formatted Date
* @throws IllegalArgumentException
* if the object cannot be formatted by this Format.
*/
private StringBuffer formatImpl(Date date, StringBuffer buffer,
FieldPosition field, List<FieldPosition> fields) {
boolean quote = false;
int next, last = -1, count = 0;
calendar.setTime(date);
if (field != null) {
field.clear();
}
final int patternLength = pattern.length();
for (int i = 0; i < patternLength; i++) {
next = (pattern.charAt(i));
if (next == '\'') {
if (count > 0) {
append(buffer, field, fields, (char) last, count);
count = 0;
}
if (last == next) {
buffer.append('\'');
last = -1;
} else {
last = next;
}
quote = !quote;
continue;
}
if (!quote
&& (last == next || (next >= 'a' && next <= 'z') || (next >= 'A' && next <= 'Z'))) {
if (last == next) {
count++;
} else {
if (count > 0) {
append(buffer, field, fields, (char) last, count);
}
last = next;
count = 1;
}
} else {
if (count > 0) {
append(buffer, field, fields, (char) last, count);
count = 0;
}
last = -1;
buffer.append((char) next);
}
}
if (count > 0) {
append(buffer, field, fields, (char) last, count);
}
return buffer;
}
private void append(StringBuffer buffer, FieldPosition position,
List<FieldPosition> fields, char format, int count) {
int field = -1;
int index = PATTERN_CHARS.indexOf(format);
if (index == -1) {
throw new IllegalArgumentException("Unknown pattern character '" + format + "'");
}
int beginPosition = buffer.length();
Field dateFormatField = null;
switch (index) {
case ERA_FIELD:
dateFormatField = Field.ERA;
buffer.append(formatData.eras[calendar.get(Calendar.ERA)]);
break;
case YEAR_FIELD:
dateFormatField = Field.YEAR;
int year = calendar.get(Calendar.YEAR);
/*
* For 'y' and 'yyy', we're consistent with Unicode and previous releases
* of Android. But this means we're inconsistent with the RI.
* http://unicode.org/reports/tr35/
*/
if (count == 2) {
- appendNumber(buffer, 2, year %= 100);
+ appendNumber(buffer, 2, year % 100);
} else {
appendNumber(buffer, count, year);
}
break;
case STAND_ALONE_MONTH_FIELD: // L
dateFormatField = Field.MONTH;
appendMonth(buffer, count, formatData.longStandAloneMonths, formatData.shortStandAloneMonths);
break;
case MONTH_FIELD: // M
dateFormatField = Field.MONTH;
appendMonth(buffer, count, formatData.months, formatData.shortMonths);
break;
case DATE_FIELD:
dateFormatField = Field.DAY_OF_MONTH;
field = Calendar.DATE;
break;
case HOUR_OF_DAY1_FIELD: // k
dateFormatField = Field.HOUR_OF_DAY1;
int hour = calendar.get(Calendar.HOUR_OF_DAY);
appendNumber(buffer, count, hour == 0 ? 24 : hour);
break;
case HOUR_OF_DAY0_FIELD: // H
dateFormatField = Field.HOUR_OF_DAY0;
field = Calendar.HOUR_OF_DAY;
break;
case MINUTE_FIELD:
dateFormatField = Field.MINUTE;
field = Calendar.MINUTE;
break;
case SECOND_FIELD:
dateFormatField = Field.SECOND;
field = Calendar.SECOND;
break;
case MILLISECOND_FIELD:
dateFormatField = Field.MILLISECOND;
int value = calendar.get(Calendar.MILLISECOND);
appendNumber(buffer, count, value);
break;
case STAND_ALONE_DAY_OF_WEEK_FIELD:
dateFormatField = Field.DAY_OF_WEEK;
appendDayOfWeek(buffer, count, formatData.longStandAloneWeekdays, formatData.shortStandAloneWeekdays);
break;
case DAY_OF_WEEK_FIELD:
dateFormatField = Field.DAY_OF_WEEK;
appendDayOfWeek(buffer, count, formatData.weekdays, formatData.shortWeekdays);
break;
case DAY_OF_YEAR_FIELD:
dateFormatField = Field.DAY_OF_YEAR;
field = Calendar.DAY_OF_YEAR;
break;
case DAY_OF_WEEK_IN_MONTH_FIELD:
dateFormatField = Field.DAY_OF_WEEK_IN_MONTH;
field = Calendar.DAY_OF_WEEK_IN_MONTH;
break;
case WEEK_OF_YEAR_FIELD:
dateFormatField = Field.WEEK_OF_YEAR;
field = Calendar.WEEK_OF_YEAR;
break;
case WEEK_OF_MONTH_FIELD:
dateFormatField = Field.WEEK_OF_MONTH;
field = Calendar.WEEK_OF_MONTH;
break;
case AM_PM_FIELD:
dateFormatField = Field.AM_PM;
buffer.append(formatData.ampms[calendar.get(Calendar.AM_PM)]);
break;
case HOUR1_FIELD: // h
dateFormatField = Field.HOUR1;
hour = calendar.get(Calendar.HOUR);
appendNumber(buffer, count, hour == 0 ? 12 : hour);
break;
case HOUR0_FIELD: // K
dateFormatField = Field.HOUR0;
field = Calendar.HOUR;
break;
case TIMEZONE_FIELD: // z
dateFormatField = Field.TIME_ZONE;
appendTimeZone(buffer, count, true);
break;
case RFC_822_TIMEZONE_FIELD: // Z
dateFormatField = Field.TIME_ZONE;
appendNumericTimeZone(buffer, false);
break;
}
if (field != -1) {
appendNumber(buffer, count, calendar.get(field));
}
if (fields != null) {
position = new FieldPosition(dateFormatField);
position.setBeginIndex(beginPosition);
position.setEndIndex(buffer.length());
fields.add(position);
} else {
// Set to the first occurrence
if ((position.getFieldAttribute() == dateFormatField || (position
.getFieldAttribute() == null && position.getField() == index))
&& position.getEndIndex() == 0) {
position.setBeginIndex(beginPosition);
position.setEndIndex(buffer.length());
}
}
}
private void appendDayOfWeek(StringBuffer buffer, int count, String[] longs, String[] shorts) {
boolean isLong = (count > 3);
String[] days = isLong ? longs : shorts;
buffer.append(days[calendar.get(Calendar.DAY_OF_WEEK)]);
}
private void appendMonth(StringBuffer buffer, int count, String[] longs, String[] shorts) {
int month = calendar.get(Calendar.MONTH);
if (count <= 2) {
appendNumber(buffer, count, month + 1);
return;
}
boolean isLong = (count > 3);
String[] months = isLong ? longs : shorts;
buffer.append(months[month]);
}
/**
* Append a representation of the time zone of 'calendar' to 'buffer'.
*
* @param count the number of z or Z characters in the format string; "zzz" would be 3,
* for example.
* @param generalTimeZone true if we should use a display name ("PDT") if available;
* false implies that we should use RFC 822 format ("-0800") instead. This corresponds to 'z'
* versus 'Z' in the format string.
*/
private void appendTimeZone(StringBuffer buffer, int count, boolean generalTimeZone) {
if (generalTimeZone) {
TimeZone tz = calendar.getTimeZone();
boolean daylight = (calendar.get(Calendar.DST_OFFSET) != 0);
int style = count < 4 ? TimeZone.SHORT : TimeZone.LONG;
if (!formatData.customZoneStrings) {
buffer.append(tz.getDisplayName(daylight, style, formatData.locale));
return;
}
// We can't call TimeZone.getDisplayName() because it would not use
// the custom DateFormatSymbols of this SimpleDateFormat.
String custom = TimeZones.getDisplayName(formatData.zoneStrings, tz.getID(), daylight, style);
if (custom != null) {
buffer.append(custom);
return;
}
}
// We didn't find what we were looking for, so default to a numeric time zone.
appendNumericTimeZone(buffer, generalTimeZone);
}
/**
* @param generalTimeZone "GMT-08:00" rather than "-0800".
*/
private void appendNumericTimeZone(StringBuffer buffer, boolean generalTimeZone) {
int offset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
char sign = '+';
if (offset < 0) {
sign = '-';
offset = -offset;
}
if (generalTimeZone) {
buffer.append("GMT");
}
buffer.append(sign);
appendNumber(buffer, 2, offset / 3600000);
if (generalTimeZone) {
buffer.append(':');
}
appendNumber(buffer, 2, (offset % 3600000) / 60000);
}
private void appendNumber(StringBuffer buffer, int count, int value) {
// TODO: we could avoid using the NumberFormat in most cases for a significant speedup.
// The only problem is that we expose the NumberFormat to third-party code, so we'd have
// some work to do to work out when the optimization is valid.
int minimumIntegerDigits = numberFormat.getMinimumIntegerDigits();
numberFormat.setMinimumIntegerDigits(count);
numberFormat.format(Integer.valueOf(value), buffer, new FieldPosition(0));
numberFormat.setMinimumIntegerDigits(minimumIntegerDigits);
}
private Date error(ParsePosition position, int offset, TimeZone zone) {
position.setErrorIndex(offset);
calendar.setTimeZone(zone);
return null;
}
/**
* Formats the specified date as a string using the pattern of this date
* format and appends the string to the specified string buffer.
* <p>
* If the {@code field} member of {@code field} contains a value specifying
* a format field, then its {@code beginIndex} and {@code endIndex} members
* will be updated with the position of the first occurrence of this field
* in the formatted text.
*
* @param date
* the date to format.
* @param buffer
* the target string buffer to append the formatted date/time to.
* @param fieldPos
* on input: an optional alignment field; on output: the offsets
* of the alignment field in the formatted text.
* @return the string buffer.
* @throws IllegalArgumentException
* if there are invalid characters in the pattern.
*/
@Override
public StringBuffer format(Date date, StringBuffer buffer, FieldPosition fieldPos) {
// Harmony delegates to ICU's SimpleDateFormat, we implement it directly
return formatImpl(date, buffer, fieldPos, null);
}
/**
* Returns the date which is the start of the one hundred year period for two-digit year values.
* See {@link #set2DigitYearStart} for details.
*/
public Date get2DigitYearStart() {
return (Date) defaultCenturyStart.clone();
}
/**
* Returns the {@code DateFormatSymbols} used by this simple date format.
*
* @return the {@code DateFormatSymbols} object.
*/
public DateFormatSymbols getDateFormatSymbols() {
return (DateFormatSymbols) formatData.clone();
}
@Override
public int hashCode() {
return super.hashCode() + pattern.hashCode() + formatData.hashCode() + creationYear;
}
private int parse(String string, int offset, char format, int count) {
int index = PATTERN_CHARS.indexOf(format);
if (index == -1) {
throw new IllegalArgumentException("Unknown pattern character '" + format + "'");
}
int field = -1;
// TODO: what's 'absolute' for? when is 'count' negative, and why?
int absolute = 0;
if (count < 0) {
count = -count;
absolute = count;
}
switch (index) {
case ERA_FIELD:
return parseText(string, offset, formatData.eras, Calendar.ERA);
case YEAR_FIELD:
if (count >= 3) {
field = Calendar.YEAR;
} else {
ParsePosition position = new ParsePosition(offset);
Number result = parseNumber(absolute, string, position);
if (result == null) {
return -position.getErrorIndex() - 1;
}
int year = result.intValue();
// A two digit year must be exactly two digits, i.e. 01
if ((position.getIndex() - offset) == 2 && year >= 0) {
year += creationYear / 100 * 100;
if (year < creationYear) {
year += 100;
}
}
calendar.set(Calendar.YEAR, year);
return position.getIndex();
}
break;
case STAND_ALONE_MONTH_FIELD: // L
return parseMonth(string, offset, count, absolute,
formatData.longStandAloneMonths, formatData.shortStandAloneMonths);
case MONTH_FIELD: // M
return parseMonth(string, offset, count, absolute,
formatData.months, formatData.shortMonths);
case DATE_FIELD:
field = Calendar.DATE;
break;
case HOUR_OF_DAY1_FIELD: // k
ParsePosition position = new ParsePosition(offset);
Number result = parseNumber(absolute, string, position);
if (result == null) {
return -position.getErrorIndex() - 1;
}
int hour = result.intValue();
if (hour == 24) {
hour = 0;
}
calendar.set(Calendar.HOUR_OF_DAY, hour);
return position.getIndex();
case HOUR_OF_DAY0_FIELD: // H
field = Calendar.HOUR_OF_DAY;
break;
case MINUTE_FIELD:
field = Calendar.MINUTE;
break;
case SECOND_FIELD:
field = Calendar.SECOND;
break;
case MILLISECOND_FIELD:
field = Calendar.MILLISECOND;
break;
case STAND_ALONE_DAY_OF_WEEK_FIELD:
return parseDayOfWeek(string, offset, formatData.longStandAloneWeekdays, formatData.shortStandAloneWeekdays);
case DAY_OF_WEEK_FIELD:
return parseDayOfWeek(string, offset, formatData.weekdays, formatData.shortWeekdays);
case DAY_OF_YEAR_FIELD:
field = Calendar.DAY_OF_YEAR;
break;
case DAY_OF_WEEK_IN_MONTH_FIELD:
field = Calendar.DAY_OF_WEEK_IN_MONTH;
break;
case WEEK_OF_YEAR_FIELD:
field = Calendar.WEEK_OF_YEAR;
break;
case WEEK_OF_MONTH_FIELD:
field = Calendar.WEEK_OF_MONTH;
break;
case AM_PM_FIELD:
return parseText(string, offset, formatData.ampms, Calendar.AM_PM);
case HOUR1_FIELD: // h
position = new ParsePosition(offset);
result = parseNumber(absolute, string, position);
if (result == null) {
return -position.getErrorIndex() - 1;
}
hour = result.intValue();
if (hour == 12) {
hour = 0;
}
calendar.set(Calendar.HOUR, hour);
return position.getIndex();
case HOUR0_FIELD: // K
field = Calendar.HOUR;
break;
case TIMEZONE_FIELD: // z
return parseTimeZone(string, offset);
case RFC_822_TIMEZONE_FIELD: // Z
return parseTimeZone(string, offset);
}
if (field != -1) {
return parseNumber(absolute, string, offset, field, 0);
}
return offset;
}
private int parseDayOfWeek(String string, int offset, String[] longs, String[] shorts) {
int index = parseText(string, offset, longs, Calendar.DAY_OF_WEEK);
if (index < 0) {
index = parseText(string, offset, shorts, Calendar.DAY_OF_WEEK);
}
return index;
}
private int parseMonth(String string, int offset, int count, int absolute, String[] longs, String[] shorts) {
if (count <= 2) {
return parseNumber(absolute, string, offset, Calendar.MONTH, -1);
}
int index = parseText(string, offset, longs, Calendar.MONTH);
if (index < 0) {
index = parseText(string, offset, shorts, Calendar.MONTH);
}
return index;
}
/**
* Parses a date from the specified string starting at the index specified
* by {@code position}. If the string is successfully parsed then the index
* of the {@code ParsePosition} is updated to the index following the parsed
* text. On error, the index is unchanged and the error index of {@code
* ParsePosition} is set to the index where the error occurred.
*
* @param string
* the string to parse using the pattern of this simple date
* format.
* @param position
* input/output parameter, specifies the start index in {@code
* string} from where to start parsing. If parsing is successful,
* it is updated with the index following the parsed text; on
* error, the index is unchanged and the error index is set to
* the index where the error occurred.
* @return the date resulting from the parse, or {@code null} if there is an
* error.
* @throws IllegalArgumentException
* if there are invalid characters in the pattern.
*/
@Override
public Date parse(String string, ParsePosition position) {
// Harmony delegates to ICU's SimpleDateFormat, we implement it directly
boolean quote = false;
int next, last = -1, count = 0, offset = position.getIndex();
int length = string.length();
calendar.clear();
TimeZone zone = calendar.getTimeZone();
final int patternLength = pattern.length();
for (int i = 0; i < patternLength; i++) {
next = pattern.charAt(i);
if (next == '\'') {
if (count > 0) {
if ((offset = parse(string, offset, (char) last, count)) < 0) {
return error(position, -offset - 1, zone);
}
count = 0;
}
if (last == next) {
if (offset >= length || string.charAt(offset) != '\'') {
return error(position, offset, zone);
}
offset++;
last = -1;
} else {
last = next;
}
quote = !quote;
continue;
}
if (!quote
&& (last == next || (next >= 'a' && next <= 'z') || (next >= 'A' && next <= 'Z'))) {
if (last == next) {
count++;
} else {
if (count > 0) {
if ((offset = parse(string, offset, (char) last, -count)) < 0) {
return error(position, -offset - 1, zone);
}
}
last = next;
count = 1;
}
} else {
if (count > 0) {
if ((offset = parse(string, offset, (char) last, count)) < 0) {
return error(position, -offset - 1, zone);
}
count = 0;
}
last = -1;
if (offset >= length || string.charAt(offset) != next) {
return error(position, offset, zone);
}
offset++;
}
}
if (count > 0) {
if ((offset = parse(string, offset, (char) last, count)) < 0) {
return error(position, -offset - 1, zone);
}
}
Date date;
try {
date = calendar.getTime();
} catch (IllegalArgumentException e) {
return error(position, offset, zone);
}
position.setIndex(offset);
calendar.setTimeZone(zone);
return date;
}
private Number parseNumber(int max, String string, ParsePosition position) {
int digit, length = string.length(), result = 0;
int index = position.getIndex();
if (max > 0 && max < length - index) {
length = index + max;
}
while (index < length
&& (string.charAt(index) == ' ' || string.charAt(index) == '\t')) {
index++;
}
if (max == 0) {
position.setIndex(index);
return numberFormat.parse(string, position);
}
while (index < length
&& (digit = Character.digit(string.charAt(index), 10)) != -1) {
index++;
result = result * 10 + digit;
}
if (index == position.getIndex()) {
position.setErrorIndex(index);
return null;
}
position.setIndex(index);
return Integer.valueOf(result);
}
private int parseNumber(int max, String string, int offset, int field, int skew) {
ParsePosition position = new ParsePosition(offset);
Number result = parseNumber(max, string, position);
if (result == null) {
return -position.getErrorIndex() - 1;
}
calendar.set(field, result.intValue() + skew);
return position.getIndex();
}
private int parseText(String string, int offset, String[] text, int field) {
int found = -1;
for (int i = 0; i < text.length; i++) {
if (text[i].isEmpty()) {
continue;
}
if (string.regionMatches(true, offset, text[i], 0, text[i].length())) {
// Search for the longest match, in case some fields are subsets
if (found == -1 || text[i].length() > text[found].length()) {
found = i;
}
}
}
if (found != -1) {
calendar.set(field, found);
return offset + text[found].length();
}
return -offset - 1;
}
private int parseTimeZone(String string, int offset) {
boolean foundGMT = string.regionMatches(offset, "GMT", 0, 3);
if (foundGMT) {
offset += 3;
}
char sign;
if (offset < string.length()
&& ((sign = string.charAt(offset)) == '+' || sign == '-')) {
ParsePosition position = new ParsePosition(offset + 1);
Number result = numberFormat.parse(string, position);
if (result == null) {
return -position.getErrorIndex() - 1;
}
int hour = result.intValue();
int raw = hour * 3600000;
int index = position.getIndex();
if (index < string.length() && string.charAt(index) == ':') {
position.setIndex(index + 1);
result = numberFormat.parse(string, position);
if (result == null) {
return -position.getErrorIndex() - 1;
}
int minute = result.intValue();
raw += minute * 60000;
} else if (hour >= 24) {
raw = (hour / 100 * 3600000) + (hour % 100 * 60000);
}
if (sign == '-') {
raw = -raw;
}
calendar.setTimeZone(new SimpleTimeZone(raw, ""));
return position.getIndex();
}
if (foundGMT) {
calendar.setTimeZone(TimeZone.getTimeZone("GMT"));
return offset;
}
String[][] zones = formatData.internalZoneStrings();
for (String[] element : zones) {
for (int j = 1; j < 5; j++) {
if (string.regionMatches(true, offset, element[j], 0, element[j].length())) {
TimeZone zone = TimeZone.getTimeZone(element[0]);
if (zone == null) {
return -offset - 1;
}
int raw = zone.getRawOffset();
if (j >= 3 && zone.useDaylightTime()) {
raw += 3600000;
}
calendar.setTimeZone(new SimpleTimeZone(raw, ""));
return offset + element[j].length();
}
}
}
return -offset - 1;
}
/**
* Sets the date which is the start of the one hundred year period for two-digit year values.
*
* <p>When parsing a date string using the abbreviated year pattern {@code yy}, {@code
* SimpleDateFormat} must interpret the abbreviated year relative to some
* century. It does this by adjusting dates to be within 80 years before and 20
* years after the time the {@code SimpleDateFormat} instance was created. For
* example, using a pattern of {@code MM/dd/yy}, an
* instance created on Jan 1, 1997 would interpret the string {@code "01/11/12"}
* as Jan 11, 2012 but interpret the string {@code "05/04/64"} as May 4, 1964.
* During parsing, only strings consisting of exactly two digits, as
* defined by {@link java.lang.Character#isDigit(char)}, will be parsed into the
* default century. Any other numeric string, such as a one digit string, a
* three or more digit string, or a two digit string that isn't all digits (for
* example, {@code "-1"}), is interpreted literally. So using the same pattern, both
* {@code "01/02/3"} and {@code "01/02/003"} are parsed as Jan 2, 3 AD.
* Similarly, {@code "01/02/-3"} is parsed as Jan 2, 4 BC.
*
* <p>If the year pattern does not have exactly two 'y' characters, the year is
* interpreted literally, regardless of the number of digits. So using the
* pattern {@code MM/dd/yyyy}, {@code "01/11/12"} is parsed as Jan 11, 12 A.D.
*/
public void set2DigitYearStart(Date date) {
defaultCenturyStart = (Date) date.clone();
Calendar cal = new GregorianCalendar();
cal.setTime(defaultCenturyStart);
creationYear = cal.get(Calendar.YEAR);
}
/**
* Sets the {@code DateFormatSymbols} used by this simple date format.
*
* @param value
* the new {@code DateFormatSymbols} object.
*/
public void setDateFormatSymbols(DateFormatSymbols value) {
formatData = (DateFormatSymbols) value.clone();
}
/**
* Returns the pattern of this simple date format using localized pattern
* characters.
*
* @return the localized pattern.
*/
public String toLocalizedPattern() {
return convertPattern(pattern, PATTERN_CHARS, formatData.getLocalPatternChars(), false);
}
private static String convertPattern(String template, String fromChars, String toChars, boolean check) {
if (!check && fromChars.equals(toChars)) {
return template;
}
boolean quote = false;
StringBuilder output = new StringBuilder();
int length = template.length();
for (int i = 0; i < length; i++) {
int index;
char next = template.charAt(i);
if (next == '\'') {
quote = !quote;
}
if (!quote && (index = fromChars.indexOf(next)) != -1) {
output.append(toChars.charAt(index));
} else if (check && !quote && ((next >= 'a' && next <= 'z') || (next >= 'A' && next <= 'Z'))) {
throw new IllegalArgumentException("Invalid pattern character '" + next + "' in " + "'" + template + "'");
} else {
output.append(next);
}
}
if (quote) {
throw new IllegalArgumentException("Unterminated quote");
}
return output.toString();
}
/**
* Returns the pattern of this simple date format using non-localized
* pattern characters.
*
* @return the non-localized pattern.
*/
public String toPattern() {
return pattern;
}
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("defaultCenturyStart", Date.class),
new ObjectStreamField("formatData", DateFormatSymbols.class),
new ObjectStreamField("pattern", String.class),
new ObjectStreamField("serialVersionOnStream", int.class),
};
private void writeObject(ObjectOutputStream stream) throws IOException {
ObjectOutputStream.PutField fields = stream.putFields();
fields.put("defaultCenturyStart", defaultCenturyStart);
fields.put("formatData", formatData);
fields.put("pattern", pattern);
fields.put("serialVersionOnStream", 1);
stream.writeFields();
}
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
ObjectInputStream.GetField fields = stream.readFields();
int version = fields.get("serialVersionOnStream", 0);
Date date;
if (version > 0) {
date = (Date) fields.get("defaultCenturyStart", new Date());
} else {
date = new Date();
}
set2DigitYearStart(date);
formatData = (DateFormatSymbols) fields.get("formatData", null);
pattern = (String) fields.get("pattern", "");
}
}
| true | true | private void append(StringBuffer buffer, FieldPosition position,
List<FieldPosition> fields, char format, int count) {
int field = -1;
int index = PATTERN_CHARS.indexOf(format);
if (index == -1) {
throw new IllegalArgumentException("Unknown pattern character '" + format + "'");
}
int beginPosition = buffer.length();
Field dateFormatField = null;
switch (index) {
case ERA_FIELD:
dateFormatField = Field.ERA;
buffer.append(formatData.eras[calendar.get(Calendar.ERA)]);
break;
case YEAR_FIELD:
dateFormatField = Field.YEAR;
int year = calendar.get(Calendar.YEAR);
/*
* For 'y' and 'yyy', we're consistent with Unicode and previous releases
* of Android. But this means we're inconsistent with the RI.
* http://unicode.org/reports/tr35/
*/
if (count == 2) {
appendNumber(buffer, 2, year %= 100);
} else {
appendNumber(buffer, count, year);
}
break;
case STAND_ALONE_MONTH_FIELD: // L
dateFormatField = Field.MONTH;
appendMonth(buffer, count, formatData.longStandAloneMonths, formatData.shortStandAloneMonths);
break;
case MONTH_FIELD: // M
dateFormatField = Field.MONTH;
appendMonth(buffer, count, formatData.months, formatData.shortMonths);
break;
case DATE_FIELD:
dateFormatField = Field.DAY_OF_MONTH;
field = Calendar.DATE;
break;
case HOUR_OF_DAY1_FIELD: // k
dateFormatField = Field.HOUR_OF_DAY1;
int hour = calendar.get(Calendar.HOUR_OF_DAY);
appendNumber(buffer, count, hour == 0 ? 24 : hour);
break;
case HOUR_OF_DAY0_FIELD: // H
dateFormatField = Field.HOUR_OF_DAY0;
field = Calendar.HOUR_OF_DAY;
break;
case MINUTE_FIELD:
dateFormatField = Field.MINUTE;
field = Calendar.MINUTE;
break;
case SECOND_FIELD:
dateFormatField = Field.SECOND;
field = Calendar.SECOND;
break;
case MILLISECOND_FIELD:
dateFormatField = Field.MILLISECOND;
int value = calendar.get(Calendar.MILLISECOND);
appendNumber(buffer, count, value);
break;
case STAND_ALONE_DAY_OF_WEEK_FIELD:
dateFormatField = Field.DAY_OF_WEEK;
appendDayOfWeek(buffer, count, formatData.longStandAloneWeekdays, formatData.shortStandAloneWeekdays);
break;
case DAY_OF_WEEK_FIELD:
dateFormatField = Field.DAY_OF_WEEK;
appendDayOfWeek(buffer, count, formatData.weekdays, formatData.shortWeekdays);
break;
case DAY_OF_YEAR_FIELD:
dateFormatField = Field.DAY_OF_YEAR;
field = Calendar.DAY_OF_YEAR;
break;
case DAY_OF_WEEK_IN_MONTH_FIELD:
dateFormatField = Field.DAY_OF_WEEK_IN_MONTH;
field = Calendar.DAY_OF_WEEK_IN_MONTH;
break;
case WEEK_OF_YEAR_FIELD:
dateFormatField = Field.WEEK_OF_YEAR;
field = Calendar.WEEK_OF_YEAR;
break;
case WEEK_OF_MONTH_FIELD:
dateFormatField = Field.WEEK_OF_MONTH;
field = Calendar.WEEK_OF_MONTH;
break;
case AM_PM_FIELD:
dateFormatField = Field.AM_PM;
buffer.append(formatData.ampms[calendar.get(Calendar.AM_PM)]);
break;
case HOUR1_FIELD: // h
dateFormatField = Field.HOUR1;
hour = calendar.get(Calendar.HOUR);
appendNumber(buffer, count, hour == 0 ? 12 : hour);
break;
case HOUR0_FIELD: // K
dateFormatField = Field.HOUR0;
field = Calendar.HOUR;
break;
case TIMEZONE_FIELD: // z
dateFormatField = Field.TIME_ZONE;
appendTimeZone(buffer, count, true);
break;
case RFC_822_TIMEZONE_FIELD: // Z
dateFormatField = Field.TIME_ZONE;
appendNumericTimeZone(buffer, false);
break;
}
if (field != -1) {
appendNumber(buffer, count, calendar.get(field));
}
if (fields != null) {
position = new FieldPosition(dateFormatField);
position.setBeginIndex(beginPosition);
position.setEndIndex(buffer.length());
fields.add(position);
} else {
// Set to the first occurrence
if ((position.getFieldAttribute() == dateFormatField || (position
.getFieldAttribute() == null && position.getField() == index))
&& position.getEndIndex() == 0) {
position.setBeginIndex(beginPosition);
position.setEndIndex(buffer.length());
}
}
}
| private void append(StringBuffer buffer, FieldPosition position,
List<FieldPosition> fields, char format, int count) {
int field = -1;
int index = PATTERN_CHARS.indexOf(format);
if (index == -1) {
throw new IllegalArgumentException("Unknown pattern character '" + format + "'");
}
int beginPosition = buffer.length();
Field dateFormatField = null;
switch (index) {
case ERA_FIELD:
dateFormatField = Field.ERA;
buffer.append(formatData.eras[calendar.get(Calendar.ERA)]);
break;
case YEAR_FIELD:
dateFormatField = Field.YEAR;
int year = calendar.get(Calendar.YEAR);
/*
* For 'y' and 'yyy', we're consistent with Unicode and previous releases
* of Android. But this means we're inconsistent with the RI.
* http://unicode.org/reports/tr35/
*/
if (count == 2) {
appendNumber(buffer, 2, year % 100);
} else {
appendNumber(buffer, count, year);
}
break;
case STAND_ALONE_MONTH_FIELD: // L
dateFormatField = Field.MONTH;
appendMonth(buffer, count, formatData.longStandAloneMonths, formatData.shortStandAloneMonths);
break;
case MONTH_FIELD: // M
dateFormatField = Field.MONTH;
appendMonth(buffer, count, formatData.months, formatData.shortMonths);
break;
case DATE_FIELD:
dateFormatField = Field.DAY_OF_MONTH;
field = Calendar.DATE;
break;
case HOUR_OF_DAY1_FIELD: // k
dateFormatField = Field.HOUR_OF_DAY1;
int hour = calendar.get(Calendar.HOUR_OF_DAY);
appendNumber(buffer, count, hour == 0 ? 24 : hour);
break;
case HOUR_OF_DAY0_FIELD: // H
dateFormatField = Field.HOUR_OF_DAY0;
field = Calendar.HOUR_OF_DAY;
break;
case MINUTE_FIELD:
dateFormatField = Field.MINUTE;
field = Calendar.MINUTE;
break;
case SECOND_FIELD:
dateFormatField = Field.SECOND;
field = Calendar.SECOND;
break;
case MILLISECOND_FIELD:
dateFormatField = Field.MILLISECOND;
int value = calendar.get(Calendar.MILLISECOND);
appendNumber(buffer, count, value);
break;
case STAND_ALONE_DAY_OF_WEEK_FIELD:
dateFormatField = Field.DAY_OF_WEEK;
appendDayOfWeek(buffer, count, formatData.longStandAloneWeekdays, formatData.shortStandAloneWeekdays);
break;
case DAY_OF_WEEK_FIELD:
dateFormatField = Field.DAY_OF_WEEK;
appendDayOfWeek(buffer, count, formatData.weekdays, formatData.shortWeekdays);
break;
case DAY_OF_YEAR_FIELD:
dateFormatField = Field.DAY_OF_YEAR;
field = Calendar.DAY_OF_YEAR;
break;
case DAY_OF_WEEK_IN_MONTH_FIELD:
dateFormatField = Field.DAY_OF_WEEK_IN_MONTH;
field = Calendar.DAY_OF_WEEK_IN_MONTH;
break;
case WEEK_OF_YEAR_FIELD:
dateFormatField = Field.WEEK_OF_YEAR;
field = Calendar.WEEK_OF_YEAR;
break;
case WEEK_OF_MONTH_FIELD:
dateFormatField = Field.WEEK_OF_MONTH;
field = Calendar.WEEK_OF_MONTH;
break;
case AM_PM_FIELD:
dateFormatField = Field.AM_PM;
buffer.append(formatData.ampms[calendar.get(Calendar.AM_PM)]);
break;
case HOUR1_FIELD: // h
dateFormatField = Field.HOUR1;
hour = calendar.get(Calendar.HOUR);
appendNumber(buffer, count, hour == 0 ? 12 : hour);
break;
case HOUR0_FIELD: // K
dateFormatField = Field.HOUR0;
field = Calendar.HOUR;
break;
case TIMEZONE_FIELD: // z
dateFormatField = Field.TIME_ZONE;
appendTimeZone(buffer, count, true);
break;
case RFC_822_TIMEZONE_FIELD: // Z
dateFormatField = Field.TIME_ZONE;
appendNumericTimeZone(buffer, false);
break;
}
if (field != -1) {
appendNumber(buffer, count, calendar.get(field));
}
if (fields != null) {
position = new FieldPosition(dateFormatField);
position.setBeginIndex(beginPosition);
position.setEndIndex(buffer.length());
fields.add(position);
} else {
// Set to the first occurrence
if ((position.getFieldAttribute() == dateFormatField || (position
.getFieldAttribute() == null && position.getField() == index))
&& position.getEndIndex() == 0) {
position.setBeginIndex(beginPosition);
position.setEndIndex(buffer.length());
}
}
}
|
diff --git a/org.eclipse.virgo.kernel.osgi/src/main/java/org/eclipse/virgo/kernel/osgi/region/RegionManager.java b/org.eclipse.virgo.kernel.osgi/src/main/java/org/eclipse/virgo/kernel/osgi/region/RegionManager.java
index 8e1dc43d..07bc7ccc 100644
--- a/org.eclipse.virgo.kernel.osgi/src/main/java/org/eclipse/virgo/kernel/osgi/region/RegionManager.java
+++ b/org.eclipse.virgo.kernel.osgi/src/main/java/org/eclipse/virgo/kernel/osgi/region/RegionManager.java
@@ -1,314 +1,314 @@
/*******************************************************************************
* Copyright (c) 2008, 2010 VMware Inc.
* 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:
* VMware Inc. - initial contribution
*******************************************************************************/
package org.eclipse.virgo.kernel.osgi.region;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import org.eclipse.virgo.kernel.core.Shutdown;
import org.eclipse.virgo.kernel.osgi.framework.OsgiFrameworkLogEvents;
import org.eclipse.virgo.kernel.serviceability.NonNull;
import org.eclipse.virgo.medic.eventlog.EventLogger;
import org.eclipse.virgo.osgi.launcher.parser.ArgumentParser;
import org.eclipse.virgo.osgi.launcher.parser.BundleEntry;
import org.eclipse.virgo.util.osgi.ServiceRegistrationTracker;
import org.osgi.framework.Bundle;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleException;
import org.osgi.framework.hooks.bundle.EventHook;
import org.osgi.framework.hooks.bundle.FindHook;
import org.osgi.framework.hooks.resolver.ResolverHookFactory;
import org.osgi.service.cm.Configuration;
import org.osgi.service.cm.ConfigurationAdmin;
import org.osgi.service.event.Event;
import org.osgi.service.event.EventAdmin;
/**
* Creates and manages the user {@link Region regions}.
* <p />
*
* <strong>Concurrent Semantics</strong><br />
*
* Threadsafe.
*
*/
final class RegionManager {
private static final String USER_REGION_BUNDLE_CONTEXT_SERVICE_PROPERTY = "org.eclipse.virgo.kernel.regionContext";
private static final String REFERENCE_SCHEME = "reference:";
private static final String FILE_SCHEME = "file:";
private static final String USER_REGION_LOCATION_TAG = "userregion@";
private static final String USER_REGION_CONFIGURATION_PID = "org.eclipse.virgo.kernel.userregion";
private static final String USER_REGION_BASE_BUNDLES_PROPERTY = "baseBundles";
private static final String USER_REGION_PACKAGE_IMPORTS_PROPERTY = "packageImports";
private static final String USER_REGION_SERVICE_IMPORTS_PROPERTY = "serviceImports";
private static final String USER_REGION_SERVICE_EXPORTS_PROPERTY = "serviceExports";
private static final String REGION_KERNEL = "org.eclipse.virgo.region.kernel";
private static final String REGION_USER = "org.eclipse.virgo.region.user";
private static final String EVENT_REGION_STARTING = "org/eclipse/virgo/kernel/region/STARTING";
private static final String EVENT_PROPERTY_REGION_BUNDLECONTEXT = "region.bundleContext";
private final ServiceRegistrationTracker tracker = new ServiceRegistrationTracker();
private final BundleContext bundleContext;
private final ArgumentParser parser = new ArgumentParser();
private final EventAdmin eventAdmin;
private String regionBundles;
private String regionImports;
private String regionServiceImports;
private String regionServiceExports;
public RegionManager(BundleContext bundleContext, EventAdmin eventAdmin, ConfigurationAdmin configAdmin, EventLogger eventLogger,
Shutdown shutdown) {
this.bundleContext = bundleContext;
this.eventAdmin = eventAdmin;
getRegionConfiguration(configAdmin, eventLogger, shutdown);
}
private void getRegionConfiguration(ConfigurationAdmin configAdmin, EventLogger eventLogger, Shutdown shutdown) {
try {
Configuration config = configAdmin.getConfiguration(USER_REGION_CONFIGURATION_PID, null);
@SuppressWarnings("unchecked")
Dictionary<String, String> properties = (Dictionary<String, String>) config.getProperties();
if (properties != null) {
this.regionBundles = properties.get(USER_REGION_BASE_BUNDLES_PROPERTY);
this.regionImports = properties.get(USER_REGION_PACKAGE_IMPORTS_PROPERTY);
this.regionServiceImports = properties.get(USER_REGION_SERVICE_IMPORTS_PROPERTY);
this.regionServiceExports = properties.get(USER_REGION_SERVICE_EXPORTS_PROPERTY);
} else {
eventLogger.log(OsgiFrameworkLogEvents.USER_REGION_CONFIGURATION_UNAVAILABLE);
shutdown.immediateShutdown();
}
} catch (Exception e) {
eventLogger.log(OsgiFrameworkLogEvents.USER_REGION_CONFIGURATION_UNAVAILABLE, e);
shutdown.immediateShutdown();
}
}
public void start() throws BundleException {
createAndPublishUserRegion();
}
private void createAndPublishUserRegion() throws BundleException {
registerRegionService(new ImmutableRegion(REGION_KERNEL, this.bundleContext));
String userRegionImportsProperty = this.regionImports != null ? this.regionImports
: this.bundleContext.getProperty(USER_REGION_PACKAGE_IMPORTS_PROPERTY);
String expandedUserRegionImportsProperty = null;
if (userRegionImportsProperty != null) {
expandedUserRegionImportsProperty = PackageImportWildcardExpander.expandPackageImportsWildcards(userRegionImportsProperty,
this.bundleContext);
}
RegionMembership regionMembership = new RegionMembership() {
@Override
public boolean contains(Bundle bundle) {
long bundleId = bundle.getBundleId();
return contains(bundleId);
}
@Override
public boolean contains(Long bundleId) {
- // TODO implement a more robust membership scheme
+ // TODO implement a more robust membership scheme. See bug 333193.
return bundleId > bundleContext.getBundle().getBundleId() || bundleId == 0L;
}
};
registerResolverHookFactory(new RegionResolverHookFactory(regionMembership, expandedUserRegionImportsProperty));
registerBundleEventHook(new RegionBundleEventHook(regionMembership));
registerBundleFindHook(new RegionBundleFindHook(regionMembership));
registerServiceEventHook(new RegionServiceEventHook(regionMembership, this.regionServiceImports, this.regionServiceExports));
registerServiceFindHook(new RegionServiceFindHook(regionMembership, this.regionServiceImports, this.regionServiceExports));
BundleContext userRegionBundleContext = initialiseUserRegionBundles();
registerRegionMembership(regionMembership, userRegionBundleContext);
registerRegionService(new ImmutableRegion(REGION_USER, userRegionBundleContext));
publishUserRegionBundleContext(userRegionBundleContext);
}
private void registerRegionMembership(RegionMembership regionMembership, BundleContext userRegionBundleContext) {
this.tracker.track(this.bundleContext.registerService(RegionMembership.class, regionMembership, null));
if (userRegionBundleContext != null) {
this.tracker.track(userRegionBundleContext.registerService(RegionMembership.class, regionMembership, null));
}
}
private void registerServiceFindHook(org.osgi.framework.hooks.service.FindHook serviceFindHook) {
this.tracker.track(this.bundleContext.registerService(org.osgi.framework.hooks.service.FindHook.class, serviceFindHook, null));
}
private void registerServiceEventHook(org.osgi.framework.hooks.service.EventHook serviceEventHook) {
this.tracker.track(this.bundleContext.registerService(org.osgi.framework.hooks.service.EventHook.class, serviceEventHook, null));
}
private void registerBundleFindHook(FindHook findHook) {
this.tracker.track(this.bundleContext.registerService(FindHook.class, findHook, null));
}
private void registerBundleEventHook(EventHook eventHook) {
this.tracker.track(this.bundleContext.registerService(EventHook.class, eventHook, null));
}
private void publishUserRegionBundleContext(BundleContext userRegionBundleContext) {
Dictionary<String, String> properties = new Hashtable<String, String>();
properties.put(USER_REGION_BUNDLE_CONTEXT_SERVICE_PROPERTY, "true");
this.bundleContext.registerService(BundleContext.class, userRegionBundleContext, properties);
}
private void registerResolverHookFactory(ResolverHookFactory resolverHookFactory) {
this.tracker.track(this.bundleContext.registerService(ResolverHookFactory.class, resolverHookFactory, null));
}
private BundleContext initialiseUserRegionBundles() throws BundleException {
BundleContext userRegionBundleContext = null;
String userRegionBundlesProperty = this.regionBundles != null ? this.regionBundles
: this.bundleContext.getProperty(USER_REGION_BASE_BUNDLES_PROPERTY);
if (userRegionBundlesProperty != null) {
List<Bundle> bundlesToStart = new ArrayList<Bundle>();
for (BundleEntry entry : this.parser.parseBundleEntries(userRegionBundlesProperty)) {
URI uri = entry.getURI();
Bundle bundle = this.bundleContext.installBundle(USER_REGION_LOCATION_TAG + uri.toString(), openBundleStream(uri));
if (entry.isAutoStart()) {
bundlesToStart.add(bundle);
}
}
if (bundlesToStart.isEmpty()) {
throw new BundleException(USER_REGION_BASE_BUNDLES_PROPERTY + " property did not specify at least one bundle to start");
}
for (Bundle bundle : bundlesToStart) {
try {
bundle.start();
} catch (BundleException e) {
throw new BundleException("Failed to start bundle " + bundle.getSymbolicName() + " " + bundle.getVersion(), e);
}
if (userRegionBundleContext == null) {
userRegionBundleContext = bundle.getBundleContext();
notifyUserRegionStarting(userRegionBundleContext);
}
}
}
return userRegionBundleContext;
}
private InputStream openBundleStream(URI uri) throws BundleException {
String absoluteBundleUriString = getAbsoluteUriString(uri);
try {
// Use the reference: scheme to obtain an InputStream for either a file or a directory.
return new URL(REFERENCE_SCHEME + absoluteBundleUriString).openStream();
} catch (MalformedURLException e) {
throw new BundleException(USER_REGION_BASE_BUNDLES_PROPERTY + " property resulted in an invalid bundle URI '" + absoluteBundleUriString
+ "'", e);
} catch (IOException e) {
throw new BundleException(USER_REGION_BASE_BUNDLES_PROPERTY + " property referred to an invalid bundle at URI '"
+ absoluteBundleUriString + "'", e);
}
}
private String getAbsoluteUriString(URI uri) throws BundleException {
String bundleUriString = uri.toString();
if (!bundleUriString.startsWith(FILE_SCHEME)) {
throw new BundleException(USER_REGION_BASE_BUNDLES_PROPERTY + " property contained an entry '" + bundleUriString
+ "' which did not start with '" + FILE_SCHEME + "'");
}
String filePath = bundleUriString.substring(FILE_SCHEME.length());
return FILE_SCHEME + new File(filePath).getAbsolutePath();
}
private void notifyUserRegionStarting(BundleContext userRegionBundleContext) {
Map<String, Object> properties = new HashMap<String, Object>();
properties.put(EVENT_PROPERTY_REGION_BUNDLECONTEXT, userRegionBundleContext);
this.eventAdmin.sendEvent(new Event(EVENT_REGION_STARTING, properties));
}
private void registerRegionService(Region region) {
Dictionary<String, String> props = new Hashtable<String, String>();
props.put("org.eclipse.virgo.kernel.region.name", region.getName());
this.tracker.track(this.bundleContext.registerService(Region.class, region, props));
}
public void stop() {
this.tracker.unregisterAll();
}
private static class ImmutableRegion implements Region {
private final String name;
private final BundleContext bundleContext;
public ImmutableRegion(String name, @NonNull BundleContext bundleContext) {
this.name = name;
this.bundleContext = bundleContext;
}
public String getName() {
return name;
}
public BundleContext getBundleContext() {
return this.bundleContext;
}
}
}
| true | true | private void createAndPublishUserRegion() throws BundleException {
registerRegionService(new ImmutableRegion(REGION_KERNEL, this.bundleContext));
String userRegionImportsProperty = this.regionImports != null ? this.regionImports
: this.bundleContext.getProperty(USER_REGION_PACKAGE_IMPORTS_PROPERTY);
String expandedUserRegionImportsProperty = null;
if (userRegionImportsProperty != null) {
expandedUserRegionImportsProperty = PackageImportWildcardExpander.expandPackageImportsWildcards(userRegionImportsProperty,
this.bundleContext);
}
RegionMembership regionMembership = new RegionMembership() {
@Override
public boolean contains(Bundle bundle) {
long bundleId = bundle.getBundleId();
return contains(bundleId);
}
@Override
public boolean contains(Long bundleId) {
// TODO implement a more robust membership scheme
return bundleId > bundleContext.getBundle().getBundleId() || bundleId == 0L;
}
};
registerResolverHookFactory(new RegionResolverHookFactory(regionMembership, expandedUserRegionImportsProperty));
registerBundleEventHook(new RegionBundleEventHook(regionMembership));
registerBundleFindHook(new RegionBundleFindHook(regionMembership));
registerServiceEventHook(new RegionServiceEventHook(regionMembership, this.regionServiceImports, this.regionServiceExports));
registerServiceFindHook(new RegionServiceFindHook(regionMembership, this.regionServiceImports, this.regionServiceExports));
BundleContext userRegionBundleContext = initialiseUserRegionBundles();
registerRegionMembership(regionMembership, userRegionBundleContext);
registerRegionService(new ImmutableRegion(REGION_USER, userRegionBundleContext));
publishUserRegionBundleContext(userRegionBundleContext);
}
| private void createAndPublishUserRegion() throws BundleException {
registerRegionService(new ImmutableRegion(REGION_KERNEL, this.bundleContext));
String userRegionImportsProperty = this.regionImports != null ? this.regionImports
: this.bundleContext.getProperty(USER_REGION_PACKAGE_IMPORTS_PROPERTY);
String expandedUserRegionImportsProperty = null;
if (userRegionImportsProperty != null) {
expandedUserRegionImportsProperty = PackageImportWildcardExpander.expandPackageImportsWildcards(userRegionImportsProperty,
this.bundleContext);
}
RegionMembership regionMembership = new RegionMembership() {
@Override
public boolean contains(Bundle bundle) {
long bundleId = bundle.getBundleId();
return contains(bundleId);
}
@Override
public boolean contains(Long bundleId) {
// TODO implement a more robust membership scheme. See bug 333193.
return bundleId > bundleContext.getBundle().getBundleId() || bundleId == 0L;
}
};
registerResolverHookFactory(new RegionResolverHookFactory(regionMembership, expandedUserRegionImportsProperty));
registerBundleEventHook(new RegionBundleEventHook(regionMembership));
registerBundleFindHook(new RegionBundleFindHook(regionMembership));
registerServiceEventHook(new RegionServiceEventHook(regionMembership, this.regionServiceImports, this.regionServiceExports));
registerServiceFindHook(new RegionServiceFindHook(regionMembership, this.regionServiceImports, this.regionServiceExports));
BundleContext userRegionBundleContext = initialiseUserRegionBundles();
registerRegionMembership(regionMembership, userRegionBundleContext);
registerRegionService(new ImmutableRegion(REGION_USER, userRegionBundleContext));
publishUserRegionBundleContext(userRegionBundleContext);
}
|
diff --git a/libraries/javalib/gnu/java/awt/peer/gtk/GdkGraphics2D.java b/libraries/javalib/gnu/java/awt/peer/gtk/GdkGraphics2D.java
index 82de03d5a..9079b9619 100644
--- a/libraries/javalib/gnu/java/awt/peer/gtk/GdkGraphics2D.java
+++ b/libraries/javalib/gnu/java/awt/peer/gtk/GdkGraphics2D.java
@@ -1,1512 +1,1515 @@
/* GdkGraphics2D.java
Copyright (C) 2003, 2004 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath 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, or (at your option)
any later version.
GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package gnu.java.awt.peer.gtk;
import gnu.classpath.Configuration;
import gnu.java.awt.ClasspathToolkit;
import gnu.java.awt.peer.ClasspathFontPeer;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.Image;
import java.awt.Paint;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Shape;
import java.awt.Stroke;
import java.awt.TexturePaint;
import java.awt.Toolkit;
import java.awt.color.ColorSpace;
import java.awt.font.FontRenderContext;
import java.awt.font.GlyphVector;
import java.awt.font.GlyphJustificationInfo;
import java.awt.geom.Arc2D;
import java.awt.geom.GeneralPath;
import java.awt.geom.NoninvertibleTransformException;
import java.awt.geom.PathIterator;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;
import java.awt.geom.AffineTransform;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.awt.image.BufferedImageOp;
import java.awt.image.ColorModel;
import java.awt.image.CropImageFilter;
import java.awt.image.DataBuffer;
import java.awt.image.DataBufferInt;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageConsumer;
import java.awt.image.ImageObserver;
import java.awt.image.ImagingOpException;
import java.awt.image.SampleModel;
import java.awt.image.Raster;
import java.awt.image.RenderedImage;
import java.awt.image.WritableRaster;
import java.awt.image.renderable.RenderableImage;
import java.awt.image.renderable.RenderContext;
import java.text.AttributedCharacterIterator;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
public class GdkGraphics2D extends Graphics2D
{
//////////////////////////////////////
////// State Management Methods //////
//////////////////////////////////////
static
{
if (Configuration.INIT_LOAD_LIBRARY)
{
System.loadLibrary("gtkpeer");
}
if (GtkToolkit.useGraphics2D ())
initStaticState ();
}
native static void initStaticState ();
private final int native_state = GtkGenericPeer.getUniqueInteger();
private Paint paint;
private Stroke stroke;
private Color fg;
private Color bg;
private Shape clip;
private AffineTransform transform;
private GtkComponentPeer component;
private Font font;
private RenderingHints hints;
private BufferedImage bimage;
private Composite comp;
private Stack stateStack;
native private void initState (GtkComponentPeer component);
native private void initState (int width, int height);
native private void copyState (GdkGraphics2D g);
native public void dispose ();
native private int[] getImagePixels();
native private void cairoSurfaceSetFilter(int filter);
native void connectSignals (GtkComponentPeer component);
public void finalize ()
{
dispose();
}
public Graphics create ()
{
return new GdkGraphics2D (this);
}
public Graphics create (int x, int y, int width, int height)
{
return new GdkGraphics2D (width, height);
}
GdkGraphics2D (GdkGraphics2D g)
{
paint = g.paint;
stroke = g.stroke;
setRenderingHints (g.hints);
if (g.fg.getAlpha() != -1)
fg = new Color (g.fg.getRed (), g.fg.getGreen (),
g.fg.getBlue (), g.fg.getAlpha ());
else
fg = new Color (g.fg.getRGB ());
if (g.bg.getAlpha() != -1)
bg = new Color(g.bg.getRed (), g.bg.getGreen (),
g.bg.getBlue (), g.bg.getAlpha ());
else
bg = new Color (g.bg.getRGB ());
if (g.clip == null)
clip = null;
else
clip = new Rectangle (g.getClipBounds ());
if (g.transform == null)
transform = new AffineTransform ();
else
transform = new AffineTransform (g.transform);
font = g.font;
component = g.component;
copyState (g);
setColor (fg);
setBackground (bg);
setPaint (paint);
setStroke (stroke);
setTransform (transform);
setClip (clip);
stateStack = new Stack();
}
GdkGraphics2D (int width, int height)
{
initState (width, height);
setColor(Color.black);
setBackground (Color.black);
setPaint (getColor());
setFont (new Font("SansSerif", Font.PLAIN, 12));
setTransform (new AffineTransform ());
setStroke (new BasicStroke ());
setRenderingHints (getDefaultHints());
stateStack = new Stack();
}
GdkGraphics2D (GtkComponentPeer component)
{
this.component = component;
setFont (new Font("SansSerif", Font.PLAIN, 12));
if (component.isRealized ())
initComponentGraphics2D ();
else
connectSignals (component);
}
void initComponentGraphics2D ()
{
initState (component);
setColor (component.awtComponent.getForeground ());
setBackground (component.awtComponent.getBackground ());
setPaint (getColor());
setTransform (new AffineTransform ());
setStroke (new BasicStroke ());
setRenderingHints (getDefaultHints());
stateStack = new Stack ();
}
GdkGraphics2D (BufferedImage bimage)
{
this.bimage = bimage;
initState (bimage.getWidth(), bimage.getHeight());
setColor(Color.black);
setBackground (Color.black);
setPaint (getColor());
setFont (new Font("SansSerif", Font.PLAIN, 12));
setTransform (new AffineTransform ());
setStroke (new BasicStroke ());
setRenderingHints (getDefaultHints());
stateStack = new Stack();
// draw current buffered image to the pixmap associated
// with it.
drawImage (bimage, new AffineTransform (1,0,0,1,0,0), bg, null);
}
////////////////////////////////////
////// Native Drawing Methods //////
////////////////////////////////////
// GDK drawing methods
private native void gdkDrawDrawable (GdkGraphics2D other, int x, int y);
// drawing utility methods
private native void drawPixels (int pixels[], int w, int h, int stride, double i2u[]);
private native void setTexturePixels (int pixels[], int w, int h, int stride);
private native void setGradient (double x1, double y1,
double x2, double y2,
int r1, int g1, int b1, int a1,
int r2, int g2, int b2, int a2,
boolean cyclic);
// simple passthroughs to cairo
private native void cairoSave ();
private native void cairoRestore ();
private native void cairoSetMatrix (double m[]);
private native void cairoSetOperator (int cairoOperator);
private native void cairoSetRGBColor (double red, double green, double blue);
private native void cairoSetAlpha (double alpha);
private native void cairoSetFillRule (int cairoFillRule);
private native void cairoSetLineWidth (double width);
private native void cairoSetLineCap (int cairoLineCap);
private native void cairoSetLineJoin (int cairoLineJoin);
private native void cairoSetDash (double dashes[], int ndash, double offset);
private native void cairoSetMiterLimit (double limit);
private native void cairoNewPath ();
private native void cairoMoveTo (double x, double y);
private native void cairoLineTo (double x, double y);
private native void cairoCurveTo (double x1, double y1,
double x2, double y2,
double x3, double y3);
private native void cairoRelMoveTo (double dx, double dy);
private native void cairoRelLineTo (double dx, double dy);
private native void cairoRelCurveTo (double dx1, double dy1,
double dx2, double dy2,
double dx3, double dy3);
private native void cairoRectangle (double x, double y,
double width, double height);
private native void cairoClosePath ();
private native void cairoStroke ();
private native void cairoFill ();
private native void cairoClip ();
/////////////////////////////////////////////
////// General Drawing Support Methods //////
/////////////////////////////////////////////
private class DrawState
{
private Paint paint;
private Stroke stroke;
private Color fg;
private Color bg;
private Shape clip;
private AffineTransform transform;
private Font font;
private Composite comp;
DrawState (GdkGraphics2D g)
{
this.paint = g.paint;
this.stroke = g.stroke;
this.fg = g.fg;
this.bg = g.bg;
this.clip = g.clip;
if (g.transform != null)
this.transform = (AffineTransform) g.transform.clone();
this.font = g.font;
this.comp = g.comp;
}
public void restore(GdkGraphics2D g)
{
g.paint = this.paint;
g.stroke = this.stroke;
g.fg = this.fg;
g.bg = this.bg;
g.clip = this.clip;
g.transform = this.transform;
g.font = this.font;
g.comp = this.comp;
}
}
private void stateSave ()
{
stateStack.push (new DrawState (this));
cairoSave ();
}
private void stateRestore ()
{
((DrawState)(stateStack.pop ())).restore (this);
cairoRestore ();
}
// Some operations (drawing rather than filling) require that their
// coords be shifted to land on 0.5-pixel boundaries, in order to land on
// "middle of pixel" coordinates and light up complete pixels.
private boolean shiftDrawCalls = false;
private final double shifted(double coord, boolean doShift)
{
if (doShift)
return Math.floor(coord) + 0.5;
else
return coord;
}
private final void walkPath(PathIterator p, boolean doShift)
{
double x = 0;
double y = 0;
double coords[] = new double[6];
cairoSetFillRule (p.getWindingRule ());
for ( ; ! p.isDone (); p.next())
{
int seg = p.currentSegment (coords);
switch(seg)
{
case PathIterator.SEG_MOVETO:
x = shifted(coords[0], doShift);
y = shifted(coords[1], doShift);
cairoMoveTo (x, y);
break;
case PathIterator.SEG_LINETO:
x = shifted(coords[0], doShift);
y = shifted(coords[1], doShift);
cairoLineTo (x, y);
break;
case PathIterator.SEG_QUADTO:
// splitting a quadratic bezier into a cubic:
// see: http://pfaedit.sourceforge.net/bezier.html
double x1 = x + (2.0/3.0) * (shifted(coords[0], doShift) - x);
double y1 = y + (2.0/3.0) * (shifted(coords[1], doShift) - y);
double x2 = x1 + (1.0/3.0) * (shifted(coords[2], doShift) - x);
double y2 = y1 + (1.0/3.0) * (shifted(coords[3], doShift) - y);
x = shifted(coords[2], doShift);
y = shifted(coords[3], doShift);
cairoCurveTo (x1, y1,
x2, y2,
x, y);
break;
case PathIterator.SEG_CUBICTO:
x = shifted(coords[4], doShift);
y = shifted(coords[5], doShift);
cairoCurveTo (shifted(coords[0], doShift), shifted(coords[1], doShift),
shifted(coords[2], doShift), shifted(coords[3], doShift),
x, y);
break;
case PathIterator.SEG_CLOSE:
cairoClosePath ();
break;
}
}
}
private final Map getDefaultHints()
{
HashMap defaultHints = new HashMap ();
defaultHints.put (RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_DEFAULT);
defaultHints.put (RenderingHints.KEY_STROKE_CONTROL,
RenderingHints.VALUE_STROKE_DEFAULT);
defaultHints.put (RenderingHints.KEY_FRACTIONALMETRICS,
RenderingHints.VALUE_FRACTIONALMETRICS_OFF);
defaultHints.put (RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_OFF);
defaultHints.put (RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_DEFAULT);
return defaultHints;
}
private final void updateBufferedImage()
{
int[] pixels = getImagePixels();
updateImagePixels(pixels);
}
private final boolean isBufferedImageGraphics ()
{
return bimage != null;
}
private final void updateImagePixels (int[] pixels)
{
// This function can only be used if
// this graphics object is used to draw into
// buffered image
if (! isBufferedImageGraphics ())
return;
WritableRaster raster = bimage.getRaster();
DataBuffer db = raster.getDataBuffer ();
// update pixels in the bufferedImage
if (raster.getSampleModel ().getDataType () == DataBuffer.TYPE_INT
&& db instanceof DataBufferInt
&& db.getNumBanks () == 1)
{
// single bank, ARGB-ints buffer in sRGB space
DataBufferInt dbi = (DataBufferInt) raster.getDataBuffer ();
for (int i=0; i < pixels.length; i++)
dbi.setElem(i, pixels[i]);
}
else
{
bimage.getRaster().setPixels (0, 0, raster.getWidth (),
raster.getHeight (), pixels);
}
}
private final boolean drawImage(Image img,
AffineTransform xform,
Color bgcolor,
ImageObserver obs)
{
if (img == null)
return false;
if (img instanceof GtkOffScreenImage &&
img.getGraphics () instanceof GdkGraphics2D &&
(xform == null
|| xform.getType () == AffineTransform.TYPE_IDENTITY
|| xform.getType () == AffineTransform.TYPE_TRANSLATION)
)
{
// we are being asked to flush a double buffer from Gdk
GdkGraphics2D g2 = (GdkGraphics2D) img.getGraphics ();
gdkDrawDrawable (g2, (int)xform.getTranslateX(), (int)xform.getTranslateY());
if (isBufferedImageGraphics ())
updateBufferedImage();
return true;
}
else
{
// In this case, xform is an AffineTransform that transforms bounding
// box of the specified image from image space to user space. However
// when we pass this transform to cairo, cairo will use this transform
// to map "user coordinates" to "pixel" coordinates, which is the
// other way around. Therefore to get the "user -> pixel" transform
// that cairo wants from "image -> user" transform that we currently
// have, we will need to invert the transformation matrix.
AffineTransform invertedXform = new AffineTransform();
try
{
invertedXform = xform.createInverse();
if (img instanceof BufferedImage)
{
// draw an image which has actually been loaded
// into memory fully
BufferedImage b = (BufferedImage) img;
return drawRaster (b.getColorModel (),
b.getData (),
invertedXform,
bgcolor);
}
else
{
return this.drawImage(GdkPixbufDecoder.createBufferedImage(img.getSource()),
xform, bgcolor,obs);
}
}
catch (NoninvertibleTransformException e)
{
throw new ImagingOpException("Unable to invert transform "
+ xform.toString());
}
}
}
//////////////////////////////////////////////////
////// Implementation of Graphics2D Methods //////
//////////////////////////////////////////////////
public void draw (Shape s)
{
if (stroke != null &&
!(stroke instanceof BasicStroke))
{
fill (stroke.createStrokedShape (s));
return;
}
cairoNewPath ();
if (s instanceof Rectangle2D)
{
Rectangle2D r = (Rectangle2D)s;
cairoRectangle (shifted(r.getX (), shiftDrawCalls),
shifted(r.getY (), shiftDrawCalls),
r.getWidth (), r.getHeight ());
}
else
walkPath (s.getPathIterator (null), shiftDrawCalls);
cairoStroke ();
if (isBufferedImageGraphics ())
updateBufferedImage();
}
public void fill (Shape s)
{
cairoNewPath ();
if (s instanceof Rectangle2D)
{
Rectangle2D r = (Rectangle2D)s;
cairoRectangle (r.getX (), r.getY (), r.getWidth (), r.getHeight ());
}
else
walkPath (s.getPathIterator (null), false);
cairoFill ();
if (isBufferedImageGraphics ())
updateBufferedImage();
}
public void clip (Shape s)
{
// update it
if (clip == null || s == null)
clip = s;
else if (s instanceof Rectangle2D
&& clip instanceof Rectangle2D)
{
Rectangle2D r = (Rectangle2D)s;
Rectangle2D curr = (Rectangle2D)clip;
clip = curr.createIntersection (r);
}
else
throw new UnsupportedOperationException ();
// draw it
if (clip != null)
{
cairoNewPath ();
if (clip instanceof Rectangle2D)
{
Rectangle2D r = (Rectangle2D)clip;
cairoRectangle (r.getX (), r.getY (),
r.getWidth (), r.getHeight ());
}
else
walkPath (clip.getPathIterator (null), false);
// cairoClosePath ();
cairoClip ();
}
}
public Paint getPaint ()
{
return paint;
}
public AffineTransform getTransform ()
{
return (AffineTransform) transform.clone ();
}
public void setPaint (Paint p)
{
if (paint == null)
return;
paint = p;
if (paint instanceof Color)
{
setColor ((Color) paint);
}
else if (paint instanceof TexturePaint)
{
TexturePaint tp = (TexturePaint) paint;
BufferedImage img = tp.getImage ();
// map the image to the anchor rectangle
int width = (int) tp.getAnchorRect ().getWidth ();
int height = (int) tp.getAnchorRect ().getHeight ();
double scaleX = width / (double) img.getWidth ();
double scaleY = width / (double) img.getHeight ();
AffineTransform at = new AffineTransform (scaleX, 0, 0, scaleY, 0, 0);
AffineTransformOp op = new AffineTransformOp (at, getRenderingHints());
BufferedImage texture = op.filter(img, null);
int pixels[] = texture.getRGB (0, 0, width, height, null, 0, width);
setTexturePixels (pixels, width, height, width);
}
else if (paint instanceof GradientPaint)
{
GradientPaint gp = (GradientPaint) paint;
Point2D p1 = gp.getPoint1 ();
Point2D p2 = gp.getPoint2 ();
Color c1 = gp.getColor1 ();
Color c2 = gp.getColor2 ();
setGradient (p1.getX (), p1.getY (),
p2.getX (), p2.getY (),
c1.getRed (), c1.getGreen (),
c1.getBlue (), c1.getAlpha (),
c2.getRed (), c2.getGreen (),
c2.getBlue (), c2.getAlpha (),
gp.isCyclic ());
}
else
throw new java.lang.UnsupportedOperationException ();
}
public void setTransform (AffineTransform tx)
{
transform = tx;
if (transform != null)
{
double m[] = new double[6];
transform.getMatrix (m);
cairoSetMatrix (m);
}
}
public void transform (AffineTransform tx)
{
if (transform == null)
transform = new AffineTransform (tx);
else
transform.concatenate (tx);
setTransform (transform);
if (clip != null)
{
// FIXME: this should actuall try to transform the shape
// rather than degrade to bounds.
Rectangle2D r = clip.getBounds2D();
double[] coords = new double[] { r.getX(), r.getY(),
r.getX() + r.getWidth(),
r.getY() + r.getHeight() };
try
{
tx.createInverse().transform(coords, 0, coords, 0, 2);
r.setRect(coords[0], coords[1],
coords[2] - coords[0],
coords[3] - coords[1]);
clip = r;
}
catch (java.awt.geom.NoninvertibleTransformException e)
{
}
}
}
public void rotate(double theta)
{
transform (AffineTransform.getRotateInstance (theta));
}
public void rotate(double theta, double x, double y)
{
transform (AffineTransform.getRotateInstance (theta, x, y));
}
public void scale(double sx, double sy)
{
transform (AffineTransform.getScaleInstance (sx, sy));
}
public void translate (double tx, double ty)
{
transform (AffineTransform.getTranslateInstance (tx, ty));
}
public void translate (int x, int y)
{
translate ((double) x, (double) y);
}
public void shear(double shearX, double shearY)
{
transform (AffineTransform.getShearInstance (shearX, shearY));
}
public Stroke getStroke()
{
return stroke;
}
public void setStroke (Stroke st)
{
stroke = st;
if (stroke instanceof BasicStroke)
{
BasicStroke bs = (BasicStroke) stroke;
cairoSetLineCap (bs.getEndCap());
cairoSetLineWidth (bs.getLineWidth());
cairoSetLineJoin (bs.getLineJoin());
cairoSetMiterLimit (bs.getMiterLimit());
float dashes[] = bs.getDashArray();
if (dashes != null)
{
double double_dashes[] = new double[dashes.length];
for (int i = 0; i < dashes.length; i++)
double_dashes[i] = dashes[i];
cairoSetDash (double_dashes, double_dashes.length,
(double) bs.getDashPhase ());
}
}
}
////////////////////////////////////////////////
////// Implementation of Graphics Methods //////
////////////////////////////////////////////////
public void setPaintMode ()
{
setComposite (java.awt.AlphaComposite.SrcOver);
}
public void setXORMode (Color c)
{
setComposite (new gnu.java.awt.BitwiseXORComposite(c));
}
public void setColor (Color c)
{
if (c == null)
c = Color.BLACK;
fg = c;
paint = c;
cairoSetRGBColor (fg.getRed() / 255.0,
fg.getGreen() / 255.0,
fg.getBlue() / 255.0);
cairoSetAlpha ((fg.getAlpha() & 255) / 255.0);
}
public Color getColor ()
{
return fg;
}
public void clipRect (int x, int y, int width, int height)
{
clip (new Rectangle (x, y, width, height));
}
public Shape getClip ()
{
return getClipInDevSpace ();
}
public Rectangle getClipBounds ()
{
if (clip == null)
return null;
else
return clip.getBounds ();
}
protected Rectangle2D getClipInDevSpace ()
{
Rectangle2D uclip = clip.getBounds2D ();
if (transform == null)
return uclip;
else
{
Point2D pos = transform.transform (new Point2D.Double(uclip.getX (),
uclip.getY ()),
(Point2D)null);
Point2D extent = transform.deltaTransform (new Point2D.Double(uclip.getWidth (),
uclip.getHeight ()),
(Point2D)null);
return new Rectangle2D.Double (pos.getX (), pos.getY (),
extent.getX (), extent.getY ());
}
}
public void setClip (int x, int y, int width, int height)
{
setClip(new Rectangle2D.Double ((double)x, (double)y,
(double)width, (double)height));
}
public void setClip (Shape s)
{
clip = s;
if (s != null)
{
cairoNewPath ();
if (s instanceof Rectangle2D)
{
Rectangle2D r = (Rectangle2D)s;
cairoRectangle (r.getX (), r.getY (),
r.getWidth (), r.getHeight ());
}
else
walkPath (s.getPathIterator (null), false);
// cairoClosePath ();
cairoClip ();
}
}
private static BasicStroke draw3DRectStroke = new BasicStroke();
public void draw3DRect(int x, int y, int width,
int height, boolean raised)
{
Stroke tmp = stroke;
setStroke(draw3DRectStroke);
super.draw3DRect(x, y, width, height, raised);
setStroke(tmp);
if (isBufferedImageGraphics ())
updateBufferedImage();
}
public void fill3DRect(int x, int y, int width,
int height, boolean raised)
{
Stroke tmp = stroke;
setStroke(draw3DRectStroke);
super.fill3DRect(x, y, width, height, raised);
setStroke(tmp);
if (isBufferedImageGraphics ())
updateBufferedImage();
}
public void drawRect (int x, int y, int width, int height)
{
draw(new Rectangle (x, y, width, height));
}
public void fillRect (int x, int y, int width, int height)
{
cairoNewPath ();
cairoRectangle (x, y, width, height);
cairoFill ();
}
public void clearRect (int x, int y, int width, int height)
{
cairoSetRGBColor (bg.getRed() / 255.0,
bg.getGreen() / 255.0,
bg.getBlue() / 255.0);
cairoSetAlpha (1.0);
cairoNewPath ();
cairoRectangle (x, y, width, height);
cairoFill ();
setColor (fg);
if (isBufferedImageGraphics ())
updateBufferedImage();
}
public void setBackground(Color c)
{
bg = c;
}
public Color getBackground()
{
return bg;
}
private final void doPolygon(int[] xPoints, int[] yPoints, int nPoints,
boolean close, boolean fill)
{
if (nPoints < 1)
return;
GeneralPath gp = new GeneralPath (PathIterator.WIND_EVEN_ODD);
gp.moveTo ((float)xPoints[0], (float)yPoints[0]);
for (int i = 1; i < nPoints; i++)
gp.lineTo ((float)xPoints[i], (float)yPoints[i]);
if (close)
gp.closePath ();
Shape sh = gp;
if (fill == false &&
stroke != null &&
!(stroke instanceof BasicStroke))
{
sh = stroke.createStrokedShape (gp);
fill = true;
}
if (fill)
fill (sh);
else
draw (sh);
}
public void drawLine (int x1, int y1, int x2, int y2)
{
int xp[] = new int[2];
int yp[] = new int[2];
xp[0] = x1;
xp[1] = x2;
yp[0] = y1;
yp[1] = y2;
doPolygon (xp, yp, 2, false, false);
}
public void fillPolygon(int[] xPoints, int[] yPoints, int nPoints)
{
doPolygon (xPoints, yPoints, nPoints, true, true);
}
public void drawPolygon(int[] xPoints, int[] yPoints, int nPoints)
{
doPolygon (xPoints, yPoints, nPoints, true, false);
}
public void drawPolyline(int[] xPoints, int[] yPoints, int nPoints)
{
doPolygon (xPoints, yPoints, nPoints, false, false);
}
private final boolean drawRaster (ColorModel cm, Raster r,
AffineTransform imageToUser,
Color bgcolor)
{
if (r == null)
return false;
SampleModel sm = r.getSampleModel ();
DataBuffer db = r.getDataBuffer ();
if (db == null || sm == null)
return false;
if (cm == null)
cm = ColorModel.getRGBdefault ();
double[] i2u = new double[6];
if (imageToUser != null)
imageToUser.getMatrix(i2u);
else
{
i2u[0] = 1; i2u[1] = 0;
i2u[2] = 0; i2u[3] = 1;
i2u[4] = 0; i2u[5] = 0;
}
int pixels[] = null;
if (sm.getDataType () == DataBuffer.TYPE_INT &&
db instanceof DataBufferInt &&
db.getNumBanks () == 1)
{
// single bank, ARGB-ints buffer in sRGB space
DataBufferInt dbi = (DataBufferInt)db;
pixels = dbi.getData ();
}
else
pixels = r.getPixels (0, 0, r.getWidth (), r.getHeight (), pixels);
ColorSpace cs = cm.getColorSpace ();
if (cs != null &&
cs.getType () != ColorSpace.CS_sRGB)
{
int pixels2[] = new int[pixels.length];
for (int i = 0; i < pixels2.length; i++)
pixels2[i] = cm.getRGB (pixels[i]);
pixels = pixels2;
}
// change all transparent pixels in the image to the
// specified bgcolor
- if (bgcolor != null)
+ if (cm.hasAlpha())
{
+ if (bgcolor != null)
+ for (int i = 0; i < pixels.length; i++)
+ {
+ if (cm.getAlpha (pixels[i]) == 0)
+ pixels[i] = bgcolor.getRGB ();
+ }
+ } else
for (int i = 0; i < pixels.length; i++)
- {
- if (cm.getAlpha (pixels[i]) == 0)
- pixels[i] = bgcolor.getRGB ();
- }
- }
+ pixels[i] |= 0xFF000000;
drawPixels (pixels, r.getWidth (), r.getHeight (), r.getWidth (), i2u);
if (isBufferedImageGraphics ())
updateBufferedImage();
return true;
}
public void drawRenderedImage(RenderedImage image,
AffineTransform xform)
{
drawRaster (image.getColorModel(), image.getData(), xform, bg);
}
public void drawRenderableImage(RenderableImage image,
AffineTransform xform)
{
drawRenderedImage (image.createRendering (new RenderContext (xform)), xform);
}
public boolean drawImage(Image img,
AffineTransform xform,
ImageObserver obs)
{
return drawImage(img, xform, bg, obs);
}
public void drawImage(BufferedImage image,
BufferedImageOp op,
int x,
int y)
{
Image filtered = op.filter(image, null);
drawImage(filtered, new AffineTransform(1f,0f,0f,1f,x,y), bg, null);
}
public boolean drawImage (Image img, int x, int y,
ImageObserver observer)
{
return drawImage(img, new AffineTransform(1f,0f,0f,1f,x,y), bg, observer);
}
///////////////////////////////////////////////
////// Unimplemented Stubs and Overloads //////
///////////////////////////////////////////////
public boolean hit(Rectangle rect, Shape text,
boolean onStroke)
{
throw new java.lang.UnsupportedOperationException ();
}
public GraphicsConfiguration getDeviceConfiguration()
{
throw new java.lang.UnsupportedOperationException ();
}
public void setComposite(Composite comp)
{
this.comp = comp;
if (comp instanceof AlphaComposite)
{
AlphaComposite a = (AlphaComposite) comp;
cairoSetOperator(a.getRule());
Color c = getColor();
setColor(new Color(c.getRed(),
c.getGreen(),
c.getBlue(),
(int) (a.getAlpha() * ((float) c.getAlpha()))));
}
else
throw new java.lang.UnsupportedOperationException ();
}
public void setRenderingHint(RenderingHints.Key hintKey,
Object hintValue)
{
hints.put (hintKey, hintValue);
if (hintKey.equals(RenderingHints.KEY_INTERPOLATION)
|| hintKey.equals(RenderingHints.KEY_ALPHA_INTERPOLATION))
{
if (hintValue.equals(RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR))
cairoSurfaceSetFilter(0);
else if (hintValue.equals(RenderingHints.VALUE_INTERPOLATION_BILINEAR))
cairoSurfaceSetFilter(1);
else if (hintValue.equals(RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED))
cairoSurfaceSetFilter(2);
else if (hintValue.equals(RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY))
cairoSurfaceSetFilter(3);
else if (hintValue.equals(RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT))
cairoSurfaceSetFilter(4);
}
shiftDrawCalls = hints.containsValue (RenderingHints.VALUE_STROKE_NORMALIZE)
|| hints.containsValue (RenderingHints.VALUE_STROKE_DEFAULT);
}
public Object getRenderingHint(RenderingHints.Key hintKey)
{
return hints.get (hintKey);
}
public void setRenderingHints(Map hints)
{
this.hints = new RenderingHints (getDefaultHints ());
this.hints.add (new RenderingHints (hints));
if (hints.containsKey(RenderingHints.KEY_INTERPOLATION))
{
if(hints.containsValue(RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR))
cairoSurfaceSetFilter(0);
else if(hints.containsValue(RenderingHints.VALUE_INTERPOLATION_BILINEAR))
cairoSurfaceSetFilter(1);
}
if (hints.containsKey(RenderingHints.KEY_ALPHA_INTERPOLATION))
{
if (hints.containsValue(RenderingHints.VALUE_ALPHA_INTERPOLATION_SPEED))
cairoSurfaceSetFilter(2);
else if (hints.containsValue(RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY))
cairoSurfaceSetFilter(3);
else if(hints.containsValue(RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT))
cairoSurfaceSetFilter(4);
}
shiftDrawCalls = hints.containsValue (RenderingHints.VALUE_STROKE_NORMALIZE)
|| hints.containsValue (RenderingHints.VALUE_STROKE_DEFAULT);
}
public void addRenderingHints(Map hints)
{
this.hints.add (new RenderingHints (hints));
}
public RenderingHints getRenderingHints()
{
return hints;
}
public Composite getComposite()
{
if (comp == null)
return AlphaComposite.SrcOver;
else
return comp;
}
public FontRenderContext getFontRenderContext ()
{
return new FontRenderContext (transform, true, true);
}
public void copyArea (int x, int y, int width, int height, int dx, int dy)
{
throw new java.lang.UnsupportedOperationException ();
}
public void drawArc (int x, int y, int width, int height,
int startAngle, int arcAngle)
{
draw (new Arc2D.Double((double)x, (double)y,
(double)width, (double)height,
(double)startAngle, (double)arcAngle,
Arc2D.OPEN));
}
public boolean drawImage (Image img, int x, int y, Color bgcolor,
ImageObserver observer)
{
return drawImage (img, x, y, img.getWidth (observer),
img.getHeight (observer), bgcolor, observer);
}
public boolean drawImage (Image img, int x, int y, int width, int height,
Color bgcolor, ImageObserver observer)
{
double scaleX = width / (double) img.getWidth (observer);
double scaleY = height / (double) img.getHeight (observer);
return drawImage (img,
new AffineTransform(scaleX, 0f, 0f, scaleY, x, y),
bgcolor,
observer);
}
public boolean drawImage (Image img, int x, int y, int width, int height,
ImageObserver observer)
{
return drawImage (img, x, y, width, height, bg, observer);
}
public boolean drawImage (Image img, int dx1, int dy1, int dx2, int dy2,
int sx1, int sy1, int sx2, int sy2,
Color bgcolor, ImageObserver observer)
{
if (img == null)
return false;
Image subImage;
int sourceWidth = sx2 - sx1;
int sourceHeight = sy2 - sy1;
int destWidth = dx2 - dx1;
int destHeight = dy2 - dy1;
double scaleX = destWidth / (double) sourceWidth;
double scaleY = destHeight / (double) sourceHeight;
// Get the subimage of the source enclosed in the
// rectangle specified by sx1, sy1, sx2, sy2
if (img instanceof BufferedImage)
{
BufferedImage b = (BufferedImage) img;
subImage = b.getSubimage(sx1,sy1,sx2,sy2);
}
else
{
// FIXME: This code currently doesn't work. Null Pointer
// exception is thrown in this case. This happens
// because img.getSource() always returns null, since source gets
// never initialized when it is created with the help of
// createImage(int width, int height).
CropImageFilter filter = new CropImageFilter(sx1,sx2,sx2,sy2);
FilteredImageSource src = new FilteredImageSource(img.getSource(),
filter);
subImage = Toolkit.getDefaultToolkit().createImage(src);
}
return drawImage(subImage, new AffineTransform(scaleX, 0, 0,
scaleY, dx1, dy1),
bgcolor,
observer);
}
public boolean drawImage (Image img, int dx1, int dy1, int dx2, int dy2,
int sx1, int sy1, int sx2, int sy2,
ImageObserver observer)
{
return drawImage (img, dx1, dy1, dx2, dy2,
sx1, sy1, sx2, sy2, bg, observer);
}
public void drawOval(int x, int y, int width, int height)
{
drawArc (x, y, width, height, 0, 360);
}
public void drawRoundRect(int x, int y, int width, int height,
int arcWidth, int arcHeight)
{
if (arcWidth > width)
arcWidth = width;
if (arcHeight > height)
arcHeight = height;
int xx = x + width - arcWidth;
int yy = y + height - arcHeight;
drawArc (x, y, arcWidth, arcHeight, 90, 90);
drawArc (xx, y, arcWidth, arcHeight, 0, 90);
drawArc (xx, yy, arcWidth, arcHeight, 270, 90);
drawArc (x, yy, arcWidth, arcHeight, 180, 90);
int y1 = y + arcHeight / 2;
int y2 = y + height - arcHeight / 2;
drawLine (x, y1, x, y2);
drawLine (x + width, y1, x + width, y2);
int x1 = x + arcWidth / 2;
int x2 = x + width - arcWidth / 2;
drawLine (x1, y, x2, y);
drawLine (x1, y + height, x2, y + height);
}
// these are the most accelerated painting paths
native void cairoDrawGdkGlyphVector (GdkFontPeer f, GdkGlyphVector gv, float x, float y);
native void cairoDrawGdkTextLayout (GdkFontPeer f, GdkTextLayout gl, float x, float y);
native void cairoDrawString (GdkFontPeer f, String str, float x, float y);
GdkFontPeer getFontPeer()
{
return (GdkFontPeer) getFont().getPeer();
}
public void drawGdkGlyphVector(GdkGlyphVector gv, float x, float y)
{
cairoDrawGdkGlyphVector(getFontPeer(), gv, x, y);
if (isBufferedImageGraphics ())
updateBufferedImage();
}
public void drawGdkTextLayout(GdkTextLayout gl, float x, float y)
{
cairoDrawGdkTextLayout(getFontPeer(), gl, x, y);
if (isBufferedImageGraphics ())
updateBufferedImage();
}
public void drawString (String str, float x, float y)
{
cairoDrawString(getFontPeer(), str, x, y);
if (isBufferedImageGraphics ())
updateBufferedImage();
}
public void drawString (String str, int x, int y)
{
drawString (str, (float)x, (float)y);
}
public void drawString (AttributedCharacterIterator ci, int x, int y)
{
drawString (ci, (float)x, (float)y);
}
public void drawGlyphVector (GlyphVector gv, float x, float y)
{
if (gv instanceof GdkGlyphVector)
drawGdkGlyphVector((GdkGlyphVector)gv, x, y);
else
throw new java.lang.UnsupportedOperationException ();
}
public void drawString (AttributedCharacterIterator ci, float x, float y)
{
GlyphVector gv = font.createGlyphVector (getFontRenderContext(), ci);
drawGlyphVector (gv, x, y);
}
public void fillArc (int x, int y, int width, int height,
int startAngle, int arcAngle)
{
fill (new Arc2D.Double((double)x, (double)y,
(double)width, (double)height,
(double)startAngle, (double)arcAngle,
Arc2D.OPEN));
}
public void fillOval(int x, int y, int width, int height)
{
fillArc (x, y, width, height, 0, 360);
}
public void fillRoundRect (int x, int y, int width, int height,
int arcWidth, int arcHeight)
{
if (arcWidth > width)
arcWidth = width;
if (arcHeight > height)
arcHeight = height;
int xx = x + width - arcWidth;
int yy = y + height - arcHeight;
fillArc (x, y, arcWidth, arcHeight, 90, 90);
fillArc (xx, y, arcWidth, arcHeight, 0, 90);
fillArc (xx, yy, arcWidth, arcHeight, 270, 90);
fillArc (x, yy, arcWidth, arcHeight, 180, 90);
fillRect (x, y + arcHeight / 2, width, height - arcHeight + 1);
fillRect (x + arcWidth / 2, y, width - arcWidth + 1, height);
}
public Font getFont ()
{
return font;
}
// Until such time as pango is happy to talk directly to cairo, we
// actually need to redirect some calls from the GtkFontPeer and
// GtkFontMetrics into the drawing kit and ask cairo ourselves.
static native void releasePeerGraphicsResource(GdkFontPeer f);
static native void getPeerTextMetrics (GdkFontPeer f, String str, double [] metrics);
static native void getPeerFontMetrics (GdkFontPeer f, double [] metrics);
public FontMetrics getFontMetrics ()
{
// the reason we go via the toolkit here is to try to get
// a cached object. the toolkit keeps such a cache.
return Toolkit.getDefaultToolkit ().getFontMetrics (font);
}
public FontMetrics getFontMetrics (Font f)
{
// the reason we go via the toolkit here is to try to get
// a cached object. the toolkit keeps such a cache.
return Toolkit.getDefaultToolkit ().getFontMetrics (f);
}
public void setFont (Font f)
{
if (f.getPeer() instanceof GdkFontPeer)
font = f;
else
font =
((ClasspathToolkit)(Toolkit.getDefaultToolkit ()))
.getFont (f.getName(), f.getAttributes ());
}
public String toString()
{
return getClass ().getName () +
"[font=" + font.toString () +
",color=" + fg.toString () + "]";
}
}
| false | true | private final boolean drawRaster (ColorModel cm, Raster r,
AffineTransform imageToUser,
Color bgcolor)
{
if (r == null)
return false;
SampleModel sm = r.getSampleModel ();
DataBuffer db = r.getDataBuffer ();
if (db == null || sm == null)
return false;
if (cm == null)
cm = ColorModel.getRGBdefault ();
double[] i2u = new double[6];
if (imageToUser != null)
imageToUser.getMatrix(i2u);
else
{
i2u[0] = 1; i2u[1] = 0;
i2u[2] = 0; i2u[3] = 1;
i2u[4] = 0; i2u[5] = 0;
}
int pixels[] = null;
if (sm.getDataType () == DataBuffer.TYPE_INT &&
db instanceof DataBufferInt &&
db.getNumBanks () == 1)
{
// single bank, ARGB-ints buffer in sRGB space
DataBufferInt dbi = (DataBufferInt)db;
pixels = dbi.getData ();
}
else
pixels = r.getPixels (0, 0, r.getWidth (), r.getHeight (), pixels);
ColorSpace cs = cm.getColorSpace ();
if (cs != null &&
cs.getType () != ColorSpace.CS_sRGB)
{
int pixels2[] = new int[pixels.length];
for (int i = 0; i < pixels2.length; i++)
pixels2[i] = cm.getRGB (pixels[i]);
pixels = pixels2;
}
// change all transparent pixels in the image to the
// specified bgcolor
if (bgcolor != null)
{
for (int i = 0; i < pixels.length; i++)
{
if (cm.getAlpha (pixels[i]) == 0)
pixels[i] = bgcolor.getRGB ();
}
}
drawPixels (pixels, r.getWidth (), r.getHeight (), r.getWidth (), i2u);
if (isBufferedImageGraphics ())
updateBufferedImage();
return true;
}
| private final boolean drawRaster (ColorModel cm, Raster r,
AffineTransform imageToUser,
Color bgcolor)
{
if (r == null)
return false;
SampleModel sm = r.getSampleModel ();
DataBuffer db = r.getDataBuffer ();
if (db == null || sm == null)
return false;
if (cm == null)
cm = ColorModel.getRGBdefault ();
double[] i2u = new double[6];
if (imageToUser != null)
imageToUser.getMatrix(i2u);
else
{
i2u[0] = 1; i2u[1] = 0;
i2u[2] = 0; i2u[3] = 1;
i2u[4] = 0; i2u[5] = 0;
}
int pixels[] = null;
if (sm.getDataType () == DataBuffer.TYPE_INT &&
db instanceof DataBufferInt &&
db.getNumBanks () == 1)
{
// single bank, ARGB-ints buffer in sRGB space
DataBufferInt dbi = (DataBufferInt)db;
pixels = dbi.getData ();
}
else
pixels = r.getPixels (0, 0, r.getWidth (), r.getHeight (), pixels);
ColorSpace cs = cm.getColorSpace ();
if (cs != null &&
cs.getType () != ColorSpace.CS_sRGB)
{
int pixels2[] = new int[pixels.length];
for (int i = 0; i < pixels2.length; i++)
pixels2[i] = cm.getRGB (pixels[i]);
pixels = pixels2;
}
// change all transparent pixels in the image to the
// specified bgcolor
if (cm.hasAlpha())
{
if (bgcolor != null)
for (int i = 0; i < pixels.length; i++)
{
if (cm.getAlpha (pixels[i]) == 0)
pixels[i] = bgcolor.getRGB ();
}
} else
for (int i = 0; i < pixels.length; i++)
pixels[i] |= 0xFF000000;
drawPixels (pixels, r.getWidth (), r.getHeight (), r.getWidth (), i2u);
if (isBufferedImageGraphics ())
updateBufferedImage();
return true;
}
|
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/JavaLocalApplicationLaunchConfigurationDelegate.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/JavaLocalApplicationLaunchConfigurationDelegate.java
index a31fe2ab1..c02ca2a2d 100644
--- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/JavaLocalApplicationLaunchConfigurationDelegate.java
+++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/JavaLocalApplicationLaunchConfigurationDelegate.java
@@ -1,420 +1,420 @@
package org.eclipse.jdt.internal.debug.ui;
/*
* (c) Copyright IBM Corp. 2000, 2001.
* All Rights Reserved.
*/
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.text.MessageFormat;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.core.runtime.Status;
import org.eclipse.debug.core.DebugPlugin;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchConfigurationWorkingCopy;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.core.Launch;
import org.eclipse.debug.core.model.ILaunchConfigurationDelegate;
import org.eclipse.debug.core.model.ISourceLocator;
import org.eclipse.debug.internal.ui.DebugUIPlugin;
import org.eclipse.debug.ui.IDebugUIConstants;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.ICompilationUnit;
import org.eclipse.jdt.core.IJavaElement;
import org.eclipse.jdt.core.IJavaModel;
import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.core.JavaCore;
import org.eclipse.jdt.core.JavaModelException;
import org.eclipse.jdt.core.Signature;
import org.eclipse.jdt.debug.ui.JavaDebugUI;
import org.eclipse.jdt.debug.ui.JavaUISourceLocator;
import org.eclipse.jdt.internal.debug.ui.launcher.MainMethodFinder;
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
import org.eclipse.jdt.launching.ExecutionArguments;
import org.eclipse.jdt.launching.IVMInstall;
import org.eclipse.jdt.launching.IVMInstallType;
import org.eclipse.jdt.launching.IVMRunner;
import org.eclipse.jdt.launching.JavaRuntime;
import org.eclipse.jdt.launching.VMRunnerConfiguration;
import org.eclipse.jdt.launching.VMRunnerResult;
import org.eclipse.ui.IEditorInput;
/**
* Launch configuration delegate for a local Java application.
*/
public class JavaLocalApplicationLaunchConfigurationDelegate implements ILaunchConfigurationDelegate {
/**
* Create the helper class that handles deleting configs whose underlying main type gets deleted
*/
/*
static {
new JavaLocalApplicationLaunchConfigurationHelper();
}
*/
/**
* @see ILaunchConfigurationDelegate#launch(ILaunchConfiguration, String)
*/
public ILaunch launch(ILaunchConfiguration configuration, String mode) throws CoreException {
return verifyAndLaunch(configuration, mode, true);
}
/**
* @see ILaunchConfigurationDelegate#verify(ILaunchConfiguration, String)
*/
public void verify(ILaunchConfiguration configuration, String mode) throws CoreException {
verifyAndLaunch(configuration, mode, false);
}
/**
* This delegate can initialize defaults for context objects that are IJavaElements
* (ICompilationUnits or IClassFiles), IFiles, and IEditorInputs. The job of this method
* is to get an IJavaElement for the context then call the method that does the real work.
*
* @see ILaunchConfigurationDelegate#initializeDefaults(ILaunchConfigurationWorkingCopy, Object)
*/
public void initializeDefaults(ILaunchConfigurationWorkingCopy configuration, Object object) {
if (object instanceof IJavaElement) {
initializeDefaults(configuration, (IJavaElement)object);
} else if (object instanceof IFile) {
IJavaElement javaElement = JavaCore.create((IFile)object);
initializeDefaults(configuration, javaElement);
} else if (object instanceof IEditorInput) {
IJavaElement javaElement = (IJavaElement) ((IEditorInput)object).getAdapter(IJavaElement.class);
initializeDefaults(configuration, javaElement);
} else {
initializeHardCodedDefaults(configuration);
}
}
/**
* Attempt to initialize default attribute values on the specified working copy by
* retrieving the values from persistent storage on the resource associated with the
* specified IJavaElement. If any of the required attributes cannot be found in
* persistent storage, this is taken to mean that there are no persisted defaults for
* the IResource, and the working copy is initialized entirely from context and
* hard-coded defaults.
*/
protected void initializeDefaults(ILaunchConfigurationWorkingCopy workingCopy, IJavaElement javaElement) {
// First look for a default config for this config type and the specified resource
if (javaElement != null) {
try {
IResource resource = javaElement.getUnderlyingResource();
if (resource != null) {
String configTypeID = workingCopy.getType().getIdentifier();
boolean foundDefault = getLaunchManager().initializeFromDefaultLaunchConfiguration(resource, workingCopy, configTypeID);
if (foundDefault) {
initializeFromContextJavaProject(workingCopy, javaElement);
initializeFromContextMainTypeAndName(workingCopy, javaElement);
return;
}
}
} catch (JavaModelException jme) {
} catch (CoreException ce) {
}
}
// If no default config was found, initialize all attributes we can from the specified
// context object and from 'hard-coded' defaults known to this delegate
if (javaElement != null) {
initializeFromContextJavaProject(workingCopy, javaElement);
initializeFromContextMainTypeAndName(workingCopy, javaElement);
}
initializeHardCodedDefaults(workingCopy);
}
/**
* Initialize those attributes whose default values are independent of any context.
*/
protected void initializeHardCodedDefaults(ILaunchConfigurationWorkingCopy workingCopy) {
initializeFromDefaultVM(workingCopy);
initializeFromDefaultContainer(workingCopy);
initializeFromDefaultPerspectives(workingCopy);
initializeFromDefaultBuild(workingCopy);
}
/**
* Set the java project attribute on the working copy based on the IJavaElement.
*/
protected void initializeFromContextJavaProject(ILaunchConfigurationWorkingCopy workingCopy, IJavaElement javaElement) {
IJavaProject javaProject = javaElement.getJavaProject();
if ((javaProject == null) || !javaProject.exists()) {
return;
}
workingCopy.setAttribute(JavaDebugUI.PROJECT_ATTR, javaProject.getElementName());
}
/**
* Set the main type & name attributes on the working copy based on the IJavaElement
*/
protected void initializeFromContextMainTypeAndName(ILaunchConfigurationWorkingCopy workingCopy, IJavaElement javaElement) {
try {
IType[] types = MainMethodFinder.findTargets(new BusyIndicatorRunnableContext(), new Object[] {javaElement});
if ((types == null) || (types.length < 1)) {
return;
}
// Simply grab the first main type found in the searched element
String fullyQualifiedName = types[0].getFullyQualifiedName();
workingCopy.setAttribute(JavaDebugUI.MAIN_TYPE_ATTR, fullyQualifiedName);
String name = types[0].getElementName();
workingCopy.rename(generateUniqueNameFrom(name));
} catch (InterruptedException ie) {
} catch (InvocationTargetException ite) {
}
}
/**
* Set the VM attributes on the working copy based on the workbench default VM.
*/
protected void initializeFromDefaultVM(ILaunchConfigurationWorkingCopy workingCopy) {
IVMInstall vmInstall = JavaRuntime.getDefaultVMInstall();
IVMInstallType vmInstallType = vmInstall.getVMInstallType();
String vmInstallTypeID = vmInstallType.getId();
workingCopy.setAttribute(JavaDebugUI.VM_INSTALL_TYPE_ATTR, vmInstallTypeID);
String vmInstallID = vmInstall.getId();
workingCopy.setAttribute(JavaDebugUI.VM_INSTALL_ATTR, vmInstallID);
}
/**
* Set the default storage location of the working copy to local.
*/
protected void initializeFromDefaultContainer(ILaunchConfigurationWorkingCopy workingCopy) {
workingCopy.setContainer(null);
}
/**
* Set the default perspectives for Run & Debug to the DebugPerspective.
*/
protected void initializeFromDefaultPerspectives(ILaunchConfigurationWorkingCopy workingCopy) {
String debugPerspID = IDebugUIConstants.ID_DEBUG_PERSPECTIVE;
workingCopy.setAttribute(IDebugUIConstants.ATTR_TARGET_RUN_PERSPECTIVE, debugPerspID);
workingCopy.setAttribute(IDebugUIConstants.ATTR_TARGET_DEBUG_PERSPECTIVE, debugPerspID);
}
/**
* Set the default 'build before launch' value.
*/
protected void initializeFromDefaultBuild(ILaunchConfigurationWorkingCopy workingCopy) {
workingCopy.setAttribute(JavaDebugUI.BUILD_BEFORE_LAUNCH_ATTR, false);
}
/**
* Verifies the given configuration can be launched, and attempts the
* launch as specified by the <code>launch</code> parameter.
*
* @param configuration the configuration to validate and launch
* @param mode the mode in which to launch
* @param doLaunch whether to launch the configuration after validation
* is complete
* @return the result launch or <code>null</code> if the launch
* is not performed.
* @exception CoreException if the configuration is invalid or
* if launching fails.
*/
protected ILaunch verifyAndLaunch(ILaunchConfiguration configuration, String mode, boolean doLaunch) throws CoreException {
/*
// Java project
String projectName = configuration.getAttribute(JavaDebugUI.PROJECT_ATTR, (String)null);
if ((projectName == null) || (projectName.trim().length() < 1)) {
abort("No project specified", null, JavaDebugUI.UNSPECIFIED_PROJECT);
}
IJavaProject javaProject = getJavaModel().getJavaProject(projectName);
if ((javaProject == null) || !javaProject.exists()) {
abort("Invalid project specified", null, JavaDebugUI.NOT_A_JAVA_PROJECT);
}
// Main type
String mainTypeName = configuration.getAttribute(JavaDebugUI.MAIN_TYPE_ATTR, (String)null);
if ((mainTypeName == null) || (mainTypeName.trim().length() < 1)) {
abort(DebugUIMessages.getString("JavaApplicationLaunchConfigurationDelegate.Main_type_not_specified._1"), null, JavaDebugUI.UNSPECIFIED_MAIN_TYPE); //$NON-NLS-1$
}
IType mainType = null;
try {
mainType = JavaLocalApplicationLaunchConfigurationHelper.findType(javaProject, mainTypeName);
} catch (JavaModelException jme) {
abort(DebugUIMessages.getString("JavaApplicationLaunchConfigurationDelegate.Main_type_does_not_exist"), null, JavaDebugUI.UNSPECIFIED_MAIN_TYPE); //$NON-NLS-1$
}
if (mainType == null) {
abort(DebugUIMessages.getString("JavaApplicationLaunchConfigurationDelegate.Main_type_does_not_exist"), null, JavaDebugUI.UNSPECIFIED_MAIN_TYPE); //$NON-NLS-1$
}
*/
// Java project
IJavaProject javaProject = JavaLocalApplicationLaunchConfigurationHelper.getJavaProject(configuration);
// Main type
IType mainType = JavaLocalApplicationLaunchConfigurationHelper.getMainType(configuration, javaProject);
// VM install type
String vmInstallTypeId = configuration.getAttribute(JavaDebugUI.VM_INSTALL_TYPE_ATTR, (String)null);
if (vmInstallTypeId == null) {
JavaLocalApplicationLaunchConfigurationHelper.abort(DebugUIMessages.getString("JavaApplicationLaunchConfigurationDelegate.JRE_Type_not_specified._2"), null, JavaDebugUI.UNSPECIFIED_VM_INSTALL_TYPE); //$NON-NLS-1$
}
IVMInstallType type = JavaRuntime.getVMInstallType(vmInstallTypeId);
if (type == null) {
JavaLocalApplicationLaunchConfigurationHelper.abort(MessageFormat.format(DebugUIMessages.getString("JavaApplicationLaunchConfigurationDelegate.VM_Install_type_does_not_exist"), new String[] {vmInstallTypeId}), null, JavaDebugUI.VM_INSTALL_TYPE_DOES_NOT_EXIST); //$NON-NLS-1$
}
// VM
String vmInstallId = configuration.getAttribute(JavaDebugUI.VM_INSTALL_ATTR, (String)null);
if (vmInstallId == null) {
JavaLocalApplicationLaunchConfigurationHelper.abort(DebugUIMessages.getString("JavaApplicationLaunchConfigurationDelegate.JRE_not_specified._3"), null, JavaDebugUI.UNSPECIFIED_VM_INSTALL); //$NON-NLS-1$
}
IVMInstall install = type.findVMInstall(vmInstallId);
if (install == null) {
JavaLocalApplicationLaunchConfigurationHelper.abort(MessageFormat.format(DebugUIMessages.getString("JavaApplicationLaunchConfigurationDelegate.JRE_{0}_does_not_exist._4"), new String[]{vmInstallId}), null, JavaDebugUI.VM_INSTALL_DOES_NOT_EXIST); //$NON-NLS-1$
}
IVMRunner runner = install.getVMRunner(mode);
if (runner == null) {
JavaLocalApplicationLaunchConfigurationHelper.abort(MessageFormat.format(DebugUIMessages.getString("JavaApplicationLaunchConfigurationDelegate.Internal_error__JRE_{0}_does_not_specify_a_VM_Runner._5"), new String[]{vmInstallId}), null, JavaDebugUI.VM_RUNNER_DOES_NOT_EXIST); //$NON-NLS-1$
}
// Working directory
String workingDir = configuration.getAttribute(JavaDebugUI.WORKING_DIRECTORY_ATTR, (String)null);
if ((workingDir != null) && (workingDir.trim().length() > 0)) {
File dir = new File(workingDir);
if (!dir.isDirectory()) {
JavaLocalApplicationLaunchConfigurationHelper.abort(MessageFormat.format(DebugUIMessages.getString("JavaApplicationLaunchConfiguration.Working_directory_does_not_exist"), new String[] {workingDir}), null, JavaDebugUI.WORKING_DIRECTORY_DOES_NOT_EXIST); //$NON-NLS-1$
}
}
// If we were just verifying, we're done
if (!doLaunch) {
return null;
}
// Build before launch
boolean build = configuration.getAttribute(JavaDebugUI.BUILD_BEFORE_LAUNCH_ATTR, false);
if (build) {
if (!DebugUIPlugin.saveAndBuild()) {
return null;
}
}
// Program & VM args
- String pgmArgs = configuration.getAttribute(JavaDebugUI.VM_ARGUMENTS_ATTR, ""); //$NON-NLS-1$
- String vmArgs = configuration.getAttribute(JavaDebugUI.PROGRAM_ARGUMENTS_ATTR, ""); //$NON-NLS-1$
+ String pgmArgs = configuration.getAttribute(JavaDebugUI.PROGRAM_ARGUMENTS_ATTR, ""); //$NON-NLS-1$
+ String vmArgs = configuration.getAttribute(JavaDebugUI.VM_ARGUMENTS_ATTR, ""); //$NON-NLS-1$
ExecutionArguments execArgs = new ExecutionArguments(vmArgs, pgmArgs);
// Classpath
List classpathList = configuration.getAttribute(JavaDebugUI.CLASSPATH_ATTR, (List)null);
String[] classpath;
if (classpathList == null) {
classpath = JavaRuntime.computeDefaultRuntimeClassPath(javaProject);
} else {
classpath = new String[classpathList.size()];
classpathList.toArray(classpath);
}
// Create VM config
VMRunnerConfiguration runConfig = new VMRunnerConfiguration(mainType.getFullyQualifiedName(), classpath);
runConfig.setProgramArguments(execArgs.getProgramArgumentsArray());
runConfig.setVMArguments(execArgs.getVMArgumentsArray());
runConfig.setWorkingDirectory(workingDir);
// Bootpath
List bootpathList = configuration.getAttribute(JavaDebugUI.BOOTPATH_ATTR, (List)null);
if (bootpathList != null) {
String[] bootpath = new String[bootpathList.size()];
bootpathList.toArray(bootpath);
runConfig.setBootClassPath(bootpath);
}
// Launch the configuration
VMRunnerResult result = runner.run(runConfig);
// Persist config info as default values on the launched resource
IResource resource = null;
try {
resource = mainType.getUnderlyingResource();
} catch (CoreException ce) {
}
if (resource != null) {
getLaunchManager().setDefaultLaunchConfiguration(resource, configuration);
}
// Create & return Launch
ISourceLocator sourceLocator = new JavaUISourceLocator(javaProject);
Launch launch = new Launch(configuration, mode, sourceLocator, result.getProcesses(), result.getDebugTarget());
return launch;
}
/**
* Convenience method to set a persistent property on the specified IResource
*/
protected void persistAttribute(QualifiedName qualName, IResource resource, String value) {
try {
resource.setPersistentProperty(qualName, value);
} catch (CoreException ce) {
}
}
/**
* Construct a new config name using the name of the given config as a starting point.
* The new name is guaranteed not to collide with any existing config name.
*/
protected String generateUniqueNameFrom(String startingName) {
int index = 1;
String baseName = startingName;
int underscoreIndex = baseName.lastIndexOf('_');
if (underscoreIndex > -1) {
String trailer = baseName.substring(underscoreIndex + 1);
try {
index = Integer.parseInt(trailer);
baseName = startingName.substring(0, underscoreIndex);
} catch (NumberFormatException nfe) {
}
}
String newName = baseName;
while (getLaunchManager().isExistingLaunchConfigurationName(newName)) {
StringBuffer buffer = new StringBuffer(baseName);
buffer.append('_');
buffer.append(String.valueOf(index));
index++;
newName = buffer.toString();
}
return newName;
}
/**
* Convenience method to get the launch manager.
*
* @return the launch manager
*/
private ILaunchManager getLaunchManager() {
return DebugPlugin.getDefault().getLaunchManager();
}
/**
* Convenience method to get the java model.
*/
private IJavaModel getJavaModel() {
return JavaCore.create(getWorkspaceRoot());
}
/**
* Convenience method to get the workspace root.
*/
private IWorkspaceRoot getWorkspaceRoot() {
return ResourcesPlugin.getWorkspace().getRoot();
}
}
| true | true | protected ILaunch verifyAndLaunch(ILaunchConfiguration configuration, String mode, boolean doLaunch) throws CoreException {
/*
// Java project
String projectName = configuration.getAttribute(JavaDebugUI.PROJECT_ATTR, (String)null);
if ((projectName == null) || (projectName.trim().length() < 1)) {
abort("No project specified", null, JavaDebugUI.UNSPECIFIED_PROJECT);
}
IJavaProject javaProject = getJavaModel().getJavaProject(projectName);
if ((javaProject == null) || !javaProject.exists()) {
abort("Invalid project specified", null, JavaDebugUI.NOT_A_JAVA_PROJECT);
}
// Main type
String mainTypeName = configuration.getAttribute(JavaDebugUI.MAIN_TYPE_ATTR, (String)null);
if ((mainTypeName == null) || (mainTypeName.trim().length() < 1)) {
abort(DebugUIMessages.getString("JavaApplicationLaunchConfigurationDelegate.Main_type_not_specified._1"), null, JavaDebugUI.UNSPECIFIED_MAIN_TYPE); //$NON-NLS-1$
}
IType mainType = null;
try {
mainType = JavaLocalApplicationLaunchConfigurationHelper.findType(javaProject, mainTypeName);
} catch (JavaModelException jme) {
abort(DebugUIMessages.getString("JavaApplicationLaunchConfigurationDelegate.Main_type_does_not_exist"), null, JavaDebugUI.UNSPECIFIED_MAIN_TYPE); //$NON-NLS-1$
}
if (mainType == null) {
abort(DebugUIMessages.getString("JavaApplicationLaunchConfigurationDelegate.Main_type_does_not_exist"), null, JavaDebugUI.UNSPECIFIED_MAIN_TYPE); //$NON-NLS-1$
}
*/
// Java project
IJavaProject javaProject = JavaLocalApplicationLaunchConfigurationHelper.getJavaProject(configuration);
// Main type
IType mainType = JavaLocalApplicationLaunchConfigurationHelper.getMainType(configuration, javaProject);
// VM install type
String vmInstallTypeId = configuration.getAttribute(JavaDebugUI.VM_INSTALL_TYPE_ATTR, (String)null);
if (vmInstallTypeId == null) {
JavaLocalApplicationLaunchConfigurationHelper.abort(DebugUIMessages.getString("JavaApplicationLaunchConfigurationDelegate.JRE_Type_not_specified._2"), null, JavaDebugUI.UNSPECIFIED_VM_INSTALL_TYPE); //$NON-NLS-1$
}
IVMInstallType type = JavaRuntime.getVMInstallType(vmInstallTypeId);
if (type == null) {
JavaLocalApplicationLaunchConfigurationHelper.abort(MessageFormat.format(DebugUIMessages.getString("JavaApplicationLaunchConfigurationDelegate.VM_Install_type_does_not_exist"), new String[] {vmInstallTypeId}), null, JavaDebugUI.VM_INSTALL_TYPE_DOES_NOT_EXIST); //$NON-NLS-1$
}
// VM
String vmInstallId = configuration.getAttribute(JavaDebugUI.VM_INSTALL_ATTR, (String)null);
if (vmInstallId == null) {
JavaLocalApplicationLaunchConfigurationHelper.abort(DebugUIMessages.getString("JavaApplicationLaunchConfigurationDelegate.JRE_not_specified._3"), null, JavaDebugUI.UNSPECIFIED_VM_INSTALL); //$NON-NLS-1$
}
IVMInstall install = type.findVMInstall(vmInstallId);
if (install == null) {
JavaLocalApplicationLaunchConfigurationHelper.abort(MessageFormat.format(DebugUIMessages.getString("JavaApplicationLaunchConfigurationDelegate.JRE_{0}_does_not_exist._4"), new String[]{vmInstallId}), null, JavaDebugUI.VM_INSTALL_DOES_NOT_EXIST); //$NON-NLS-1$
}
IVMRunner runner = install.getVMRunner(mode);
if (runner == null) {
JavaLocalApplicationLaunchConfigurationHelper.abort(MessageFormat.format(DebugUIMessages.getString("JavaApplicationLaunchConfigurationDelegate.Internal_error__JRE_{0}_does_not_specify_a_VM_Runner._5"), new String[]{vmInstallId}), null, JavaDebugUI.VM_RUNNER_DOES_NOT_EXIST); //$NON-NLS-1$
}
// Working directory
String workingDir = configuration.getAttribute(JavaDebugUI.WORKING_DIRECTORY_ATTR, (String)null);
if ((workingDir != null) && (workingDir.trim().length() > 0)) {
File dir = new File(workingDir);
if (!dir.isDirectory()) {
JavaLocalApplicationLaunchConfigurationHelper.abort(MessageFormat.format(DebugUIMessages.getString("JavaApplicationLaunchConfiguration.Working_directory_does_not_exist"), new String[] {workingDir}), null, JavaDebugUI.WORKING_DIRECTORY_DOES_NOT_EXIST); //$NON-NLS-1$
}
}
// If we were just verifying, we're done
if (!doLaunch) {
return null;
}
// Build before launch
boolean build = configuration.getAttribute(JavaDebugUI.BUILD_BEFORE_LAUNCH_ATTR, false);
if (build) {
if (!DebugUIPlugin.saveAndBuild()) {
return null;
}
}
// Program & VM args
String pgmArgs = configuration.getAttribute(JavaDebugUI.VM_ARGUMENTS_ATTR, ""); //$NON-NLS-1$
String vmArgs = configuration.getAttribute(JavaDebugUI.PROGRAM_ARGUMENTS_ATTR, ""); //$NON-NLS-1$
ExecutionArguments execArgs = new ExecutionArguments(vmArgs, pgmArgs);
// Classpath
List classpathList = configuration.getAttribute(JavaDebugUI.CLASSPATH_ATTR, (List)null);
String[] classpath;
if (classpathList == null) {
classpath = JavaRuntime.computeDefaultRuntimeClassPath(javaProject);
} else {
classpath = new String[classpathList.size()];
classpathList.toArray(classpath);
}
// Create VM config
VMRunnerConfiguration runConfig = new VMRunnerConfiguration(mainType.getFullyQualifiedName(), classpath);
runConfig.setProgramArguments(execArgs.getProgramArgumentsArray());
runConfig.setVMArguments(execArgs.getVMArgumentsArray());
runConfig.setWorkingDirectory(workingDir);
// Bootpath
List bootpathList = configuration.getAttribute(JavaDebugUI.BOOTPATH_ATTR, (List)null);
if (bootpathList != null) {
String[] bootpath = new String[bootpathList.size()];
bootpathList.toArray(bootpath);
runConfig.setBootClassPath(bootpath);
}
// Launch the configuration
VMRunnerResult result = runner.run(runConfig);
// Persist config info as default values on the launched resource
IResource resource = null;
try {
resource = mainType.getUnderlyingResource();
} catch (CoreException ce) {
}
if (resource != null) {
getLaunchManager().setDefaultLaunchConfiguration(resource, configuration);
}
// Create & return Launch
ISourceLocator sourceLocator = new JavaUISourceLocator(javaProject);
Launch launch = new Launch(configuration, mode, sourceLocator, result.getProcesses(), result.getDebugTarget());
return launch;
}
| protected ILaunch verifyAndLaunch(ILaunchConfiguration configuration, String mode, boolean doLaunch) throws CoreException {
/*
// Java project
String projectName = configuration.getAttribute(JavaDebugUI.PROJECT_ATTR, (String)null);
if ((projectName == null) || (projectName.trim().length() < 1)) {
abort("No project specified", null, JavaDebugUI.UNSPECIFIED_PROJECT);
}
IJavaProject javaProject = getJavaModel().getJavaProject(projectName);
if ((javaProject == null) || !javaProject.exists()) {
abort("Invalid project specified", null, JavaDebugUI.NOT_A_JAVA_PROJECT);
}
// Main type
String mainTypeName = configuration.getAttribute(JavaDebugUI.MAIN_TYPE_ATTR, (String)null);
if ((mainTypeName == null) || (mainTypeName.trim().length() < 1)) {
abort(DebugUIMessages.getString("JavaApplicationLaunchConfigurationDelegate.Main_type_not_specified._1"), null, JavaDebugUI.UNSPECIFIED_MAIN_TYPE); //$NON-NLS-1$
}
IType mainType = null;
try {
mainType = JavaLocalApplicationLaunchConfigurationHelper.findType(javaProject, mainTypeName);
} catch (JavaModelException jme) {
abort(DebugUIMessages.getString("JavaApplicationLaunchConfigurationDelegate.Main_type_does_not_exist"), null, JavaDebugUI.UNSPECIFIED_MAIN_TYPE); //$NON-NLS-1$
}
if (mainType == null) {
abort(DebugUIMessages.getString("JavaApplicationLaunchConfigurationDelegate.Main_type_does_not_exist"), null, JavaDebugUI.UNSPECIFIED_MAIN_TYPE); //$NON-NLS-1$
}
*/
// Java project
IJavaProject javaProject = JavaLocalApplicationLaunchConfigurationHelper.getJavaProject(configuration);
// Main type
IType mainType = JavaLocalApplicationLaunchConfigurationHelper.getMainType(configuration, javaProject);
// VM install type
String vmInstallTypeId = configuration.getAttribute(JavaDebugUI.VM_INSTALL_TYPE_ATTR, (String)null);
if (vmInstallTypeId == null) {
JavaLocalApplicationLaunchConfigurationHelper.abort(DebugUIMessages.getString("JavaApplicationLaunchConfigurationDelegate.JRE_Type_not_specified._2"), null, JavaDebugUI.UNSPECIFIED_VM_INSTALL_TYPE); //$NON-NLS-1$
}
IVMInstallType type = JavaRuntime.getVMInstallType(vmInstallTypeId);
if (type == null) {
JavaLocalApplicationLaunchConfigurationHelper.abort(MessageFormat.format(DebugUIMessages.getString("JavaApplicationLaunchConfigurationDelegate.VM_Install_type_does_not_exist"), new String[] {vmInstallTypeId}), null, JavaDebugUI.VM_INSTALL_TYPE_DOES_NOT_EXIST); //$NON-NLS-1$
}
// VM
String vmInstallId = configuration.getAttribute(JavaDebugUI.VM_INSTALL_ATTR, (String)null);
if (vmInstallId == null) {
JavaLocalApplicationLaunchConfigurationHelper.abort(DebugUIMessages.getString("JavaApplicationLaunchConfigurationDelegate.JRE_not_specified._3"), null, JavaDebugUI.UNSPECIFIED_VM_INSTALL); //$NON-NLS-1$
}
IVMInstall install = type.findVMInstall(vmInstallId);
if (install == null) {
JavaLocalApplicationLaunchConfigurationHelper.abort(MessageFormat.format(DebugUIMessages.getString("JavaApplicationLaunchConfigurationDelegate.JRE_{0}_does_not_exist._4"), new String[]{vmInstallId}), null, JavaDebugUI.VM_INSTALL_DOES_NOT_EXIST); //$NON-NLS-1$
}
IVMRunner runner = install.getVMRunner(mode);
if (runner == null) {
JavaLocalApplicationLaunchConfigurationHelper.abort(MessageFormat.format(DebugUIMessages.getString("JavaApplicationLaunchConfigurationDelegate.Internal_error__JRE_{0}_does_not_specify_a_VM_Runner._5"), new String[]{vmInstallId}), null, JavaDebugUI.VM_RUNNER_DOES_NOT_EXIST); //$NON-NLS-1$
}
// Working directory
String workingDir = configuration.getAttribute(JavaDebugUI.WORKING_DIRECTORY_ATTR, (String)null);
if ((workingDir != null) && (workingDir.trim().length() > 0)) {
File dir = new File(workingDir);
if (!dir.isDirectory()) {
JavaLocalApplicationLaunchConfigurationHelper.abort(MessageFormat.format(DebugUIMessages.getString("JavaApplicationLaunchConfiguration.Working_directory_does_not_exist"), new String[] {workingDir}), null, JavaDebugUI.WORKING_DIRECTORY_DOES_NOT_EXIST); //$NON-NLS-1$
}
}
// If we were just verifying, we're done
if (!doLaunch) {
return null;
}
// Build before launch
boolean build = configuration.getAttribute(JavaDebugUI.BUILD_BEFORE_LAUNCH_ATTR, false);
if (build) {
if (!DebugUIPlugin.saveAndBuild()) {
return null;
}
}
// Program & VM args
String pgmArgs = configuration.getAttribute(JavaDebugUI.PROGRAM_ARGUMENTS_ATTR, ""); //$NON-NLS-1$
String vmArgs = configuration.getAttribute(JavaDebugUI.VM_ARGUMENTS_ATTR, ""); //$NON-NLS-1$
ExecutionArguments execArgs = new ExecutionArguments(vmArgs, pgmArgs);
// Classpath
List classpathList = configuration.getAttribute(JavaDebugUI.CLASSPATH_ATTR, (List)null);
String[] classpath;
if (classpathList == null) {
classpath = JavaRuntime.computeDefaultRuntimeClassPath(javaProject);
} else {
classpath = new String[classpathList.size()];
classpathList.toArray(classpath);
}
// Create VM config
VMRunnerConfiguration runConfig = new VMRunnerConfiguration(mainType.getFullyQualifiedName(), classpath);
runConfig.setProgramArguments(execArgs.getProgramArgumentsArray());
runConfig.setVMArguments(execArgs.getVMArgumentsArray());
runConfig.setWorkingDirectory(workingDir);
// Bootpath
List bootpathList = configuration.getAttribute(JavaDebugUI.BOOTPATH_ATTR, (List)null);
if (bootpathList != null) {
String[] bootpath = new String[bootpathList.size()];
bootpathList.toArray(bootpath);
runConfig.setBootClassPath(bootpath);
}
// Launch the configuration
VMRunnerResult result = runner.run(runConfig);
// Persist config info as default values on the launched resource
IResource resource = null;
try {
resource = mainType.getUnderlyingResource();
} catch (CoreException ce) {
}
if (resource != null) {
getLaunchManager().setDefaultLaunchConfiguration(resource, configuration);
}
// Create & return Launch
ISourceLocator sourceLocator = new JavaUISourceLocator(javaProject);
Launch launch = new Launch(configuration, mode, sourceLocator, result.getProcesses(), result.getDebugTarget());
return launch;
}
|
diff --git a/jython/src/org/python/util/jython.java b/jython/src/org/python/util/jython.java
index daf46c6d..e619e9b3 100644
--- a/jython/src/org/python/util/jython.java
+++ b/jython/src/org/python/util/jython.java
@@ -1,547 +1,547 @@
// Copyright (c) Corporation for National Research Initiatives
package org.python.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.python.Version;
import org.python.core.CodeFlag;
import org.python.core.CompileMode;
import org.python.core.Options;
import org.python.core.Py;
import org.python.core.PyCode;
import org.python.core.PyException;
import org.python.core.PyFile;
import org.python.core.PyList;
import org.python.core.PyString;
import org.python.core.PyStringMap;
import org.python.core.PySystemState;
import org.python.core.imp;
import org.python.core.util.RelativeFile;
import org.python.modules._systemrestart;
import org.python.modules.posix.PosixModule;
import org.python.modules.thread.thread;
public class jython {
private static final String COPYRIGHT =
"Type \"help\", \"copyright\", \"credits\" or \"license\" for more information.";
static final String usageHeader =
"usage: jython [option] ... [-c cmd | -m mod | file | -] [arg] ...\n";
private static final String usage = usageHeader +
"Options and arguments:\n" + //(and corresponding environment variables):\n" +
"-c cmd : program passed in as string (terminates option list)\n" +
//"-d : debug output from parser (also PYTHONDEBUG=x)\n" +
"-Dprop=v : Set the property `prop' to value `v'\n"+
//"-E : ignore environment variables (such as PYTHONPATH)\n" +
"-C codec : Use a different codec when reading from the console.\n"+
"-h : print this help message and exit (also --help)\n" +
"-i : inspect interactively after running script\n" + //, (also PYTHONINSPECT=x)\n" +
" and force prompts, even if stdin does not appear to be a terminal\n" +
"-jar jar : program read from __run__.py in jar file\n"+
"-m mod : run library module as a script (terminates option list)\n" +
//"-O : optimize generated bytecode (a tad; also PYTHONOPTIMIZE=x)\n" +
//"-OO : remove doc-strings in addition to the -O optimizations\n" +
"-Q arg : division options: -Qold (default), -Qwarn, -Qwarnall, -Qnew\n" +
"-S : don't imply 'import site' on initialization\n" +
//"-t : issue warnings about inconsistent tab usage (-tt: issue errors)\n" +
"-u : unbuffered binary stdout and stderr\n" + // (also PYTHONUNBUFFERED=x)\n" +
//" see man page for details on internal buffering relating to '-u'\n" +
"-v : verbose (trace import statements)\n" + // (also PYTHONVERBOSE=x)\n" +
"-V : print the Python version number and exit (also --version)\n" +
"-W arg : warning control (arg is action:message:category:module:lineno)\n" +
//"-x : skip first line of source, allowing use of non-Unix forms of #!cmd\n" +
"file : program read from script file\n" +
"- : program read from stdin (default; interactive mode if a tty)\n" +
"arg ... : arguments passed to program in sys.argv[1:]\n" +
"Other environment variables:\n" +
"JYTHONPATH: '" + File.pathSeparator +
"'-separated list of directories prefixed to the default module\n" +
" search path. The result is sys.path.";
public static boolean shouldRestart;
/**
* Runs a JAR file, by executing the code found in the file __run__.py,
* which should be in the root of the JAR archive.
*
* Note that the __name__ is set to the base name of the JAR file and not
* to "__main__" (for historic reasons).
*
* This method do NOT handle exceptions. the caller SHOULD handle any
* (Py)Exceptions thrown by the code.
*
* @param filename The path to the filename to run.
*/
public static void runJar(String filename) {
// TBD: this is kind of gross because a local called `zipfile' just magically
// shows up in the module's globals. Either `zipfile' should be called
// `__zipfile__' or (preferrably, IMO), __run__.py should be imported and a main()
// function extracted. This function should be called passing zipfile in as an
// argument.
//
// Probably have to keep this code around for backwards compatibility (?)
try {
ZipFile zip = new ZipFile(filename);
ZipEntry runit = zip.getEntry("__run__.py");
if (runit == null) {
throw Py.ValueError("jar file missing '__run__.py'");
}
PyStringMap locals = new PyStringMap();
// Stripping the stuff before the last File.separator fixes Bug #931129 by
// keeping illegal characters out of the generated proxy class name
int beginIndex;
if ((beginIndex = filename.lastIndexOf(File.separator)) != -1) {
filename = filename.substring(beginIndex + 1);
}
locals.__setitem__("__name__", new PyString(filename));
locals.__setitem__("zipfile", Py.java2py(zip));
InputStream file = zip.getInputStream(runit);
PyCode code;
try {
code = Py.compile(file, "__run__", CompileMode.exec);
} finally {
file.close();
}
Py.runCode(code, locals, locals);
} catch (IOException e) {
throw Py.IOError(e);
}
}
public static void main(String[] args) {
do {
shouldRestart = false;
run(args);
} while (shouldRestart);
}
public static void run(String[] args) {
// Parse the command line options
CommandLineOptions opts = new CommandLineOptions();
if (!opts.parse(args)) {
if (opts.version) {
System.err.println("Jython " + Version.PY_VERSION);
System.exit(0);
}
if (!opts.runCommand && !opts.runModule) {
System.err.println(usage);
}
int exitcode = opts.help ? 0 : -1;
System.exit(exitcode);
}
// Setup the basic python system state from these options
PySystemState.initialize(PySystemState.getBaseProperties(), opts.properties, opts.argv);
PyList warnoptions = new PyList();
for (String wopt : opts.warnoptions) {
warnoptions.append(new PyString(wopt));
}
Py.getSystemState().setWarnoptions(warnoptions);
PySystemState systemState = Py.getSystemState();
// Decide if stdin is interactive
- if (!opts.fixInteractive && opts.interactive) {
+ if (!opts.fixInteractive || opts.interactive) {
opts.interactive = ((PyFile)Py.defaultSystemState.stdin).isatty();
if (!opts.interactive) {
systemState.ps1 = systemState.ps2 = Py.EmptyString;
}
}
// Now create an interpreter
InteractiveConsole interp = newInterpreter(opts.interactive);
systemState.__setattr__("_jy_interpreter", Py.java2py(interp));
// Print banner and copyright information (or not)
if (opts.interactive && opts.notice && !opts.runModule) {
System.err.println(InteractiveConsole.getDefaultBanner());
}
if (Options.importSite) {
try {
imp.load("site");
if (opts.interactive && opts.notice && !opts.runModule) {
System.err.println(COPYRIGHT);
}
} catch (PyException pye) {
if (!pye.match(Py.ImportError)) {
System.err.println("error importing site");
Py.printException(pye);
System.exit(-1);
}
}
}
if (opts.division != null) {
if ("old".equals(opts.division)) {
Options.divisionWarning = 0;
} else if ("warn".equals(opts.division)) {
Options.divisionWarning = 1;
} else if ("warnall".equals(opts.division)) {
Options.divisionWarning = 2;
} else if ("new".equals(opts.division)) {
Options.Qnew = true;
interp.cflags.setFlag(CodeFlag.CO_FUTURE_DIVISION);
}
}
// was there a filename on the command line?
if (opts.filename != null) {
String path;
try {
path = new File(opts.filename).getCanonicalFile().getParent();
} catch (IOException ioe) {
path = new File(opts.filename).getAbsoluteFile().getParent();
}
if (path == null) {
path = "";
}
Py.getSystemState().path.insert(0, new PyString(path));
if (opts.jar) {
try {
runJar(opts.filename);
} catch (Throwable t) {
Py.printException(t);
System.exit(-1);
}
} else if (opts.filename.equals("-")) {
try {
interp.globals.__setitem__(new PyString("__file__"), new PyString("<stdin>"));
interp.execfile(System.in, "<stdin>");
} catch (Throwable t) {
Py.printException(t);
}
} else {
try {
interp.globals.__setitem__(new PyString("__file__"),
new PyString(opts.filename));
FileInputStream file;
try {
file = new FileInputStream(new RelativeFile(opts.filename));
} catch (FileNotFoundException e) {
throw Py.IOError(e);
}
try {
if (PosixModule.getPOSIX().isatty(file.getFD())) {
opts.interactive = true;
interp.interact(null, new PyFile(file));
System.exit(0);
} else {
interp.execfile(file, opts.filename);
}
} finally {
file.close();
}
} catch (Throwable t) {
if (t instanceof PyException
&& ((PyException)t).match(_systemrestart.SystemRestart)) {
// Shutdown this instance...
shouldRestart = true;
shutdownInterpreter();
interp.cleanup();
// ..reset the state...
Py.setSystemState(new PySystemState());
// ...and start again
return;
} else {
Py.printException(t);
if (!opts.interactive) {
interp.cleanup();
System.exit(-1);
}
}
}
}
}
else {
// if there was no file name on the command line, then "" is the first element
// on sys.path. This is here because if there /was/ a filename on the c.l.,
// and say the -i option was given, sys.path[0] will have gotten filled in
// with the dir of the argument filename.
Py.getSystemState().path.insert(0, Py.EmptyString);
if (opts.command != null) {
try {
interp.exec(opts.command);
} catch (Throwable t) {
Py.printException(t);
System.exit(1);
}
}
if (opts.moduleName != null) {
// PEP 338 - Execute module as a script
try {
interp.exec("import runpy");
interp.set("name", Py.newString(opts.moduleName));
interp.exec("runpy.run_module(name, run_name='__main__', alter_sys=True)");
interp.cleanup();
System.exit(0);
} catch (Throwable t) {
Py.printException(t);
interp.cleanup();
System.exit(-1);
}
}
}
if (opts.fixInteractive || (opts.filename == null && opts.command == null)) {
if (opts.encoding == null) {
opts.encoding = PySystemState.registry.getProperty("python.console.encoding");
}
if (opts.encoding != null) {
if (!Charset.isSupported(opts.encoding)) {
System.err.println(opts.encoding
+ " is not a supported encoding on this JVM, so it can't "
+ "be used in python.console.encoding.");
System.exit(1);
}
interp.cflags.encoding = opts.encoding;
}
try {
interp.interact(null, null);
} catch (Throwable t) {
Py.printException(t);
}
}
interp.cleanup();
if (opts.fixInteractive || opts.interactive) {
System.exit(0);
}
}
/**
* Returns a new python interpreter using the InteractiveConsole subclass from the
* <tt>python.console</tt> registry key.
* <p>
* When stdin is interactive the default is {@link JLineConsole}. Otherwise the
* featureless {@link InteractiveConsole} is always used as alternative consoles cause
* unexpected behavior with the std file streams.
*/
private static InteractiveConsole newInterpreter(boolean interactiveStdin) {
if (!interactiveStdin) {
return new InteractiveConsole();
}
String interpClass = PySystemState.registry.getProperty("python.console", "");
if (interpClass.length() > 0) {
try {
return (InteractiveConsole)Class.forName(interpClass).newInstance();
} catch (Throwable t) {
// fall through
}
}
return new JLineConsole();
}
/**
* Run any finalizations on the current interpreter in preparation for a SytemRestart.
*/
public static void shutdownInterpreter() {
// Stop all the active threads and signal the SystemRestart
thread.interruptAllThreads();
Py.getSystemState()._systemRestart = true;
// Close all sockets -- not all of their operations are stopped by
// Thread.interrupt (in particular pre-nio sockets)
try {
imp.load("socket").__findattr__("_closeActiveSockets").__call__();
} catch (PyException pye) {
// continue
}
}
}
class CommandLineOptions {
public String filename;
public boolean jar, interactive, notice;
public boolean runCommand, runModule;
public boolean fixInteractive;
public boolean help, version;
public String[] argv;
public Properties properties;
public String command;
public List<String> warnoptions = Generic.list();
public String encoding;
public String division;
public String moduleName;
public CommandLineOptions() {
filename = null;
jar = fixInteractive = false;
interactive = notice = true;
runModule = false;
properties = new Properties();
help = version = false;
}
public void setProperty(String key, String value) {
properties.put(key, value);
try {
System.setProperty(key, value);
} catch (SecurityException e) {
// continue
}
}
public boolean parse(String[] args) {
int index = 0;
while (index < args.length && args[index].startsWith("-")) {
String arg = args[index];
if (arg.equals("-h") || arg.equals("-?") || arg.equals("--help")) {
help = true;
return false;
} else if (arg.equals("-V") || arg.equals("--version")) {
version = true;
return false;
} else if (arg.equals("-")) {
if (!fixInteractive) {
interactive = false;
}
filename = "-";
} else if (arg.equals("-i")) {
fixInteractive = true;
interactive = true;
} else if (arg.equals("-jar")) {
jar = true;
if (!fixInteractive) {
interactive = false;
}
} else if (arg.equals("-u")) {
Options.unbuffered = true;
} else if (arg.equals("-v")) {
Options.verbose++;
} else if (arg.equals("-vv")) {
Options.verbose += 2;
} else if (arg.equals("-vvv")) {
Options.verbose +=3 ;
} else if (arg.equals("-S")) {
Options.importSite = false;
} else if (arg.equals("-c")) {
runCommand = true;
if (arg.length() > 2) {
command = arg.substring(2);
} else if ((index + 1) < args.length) {
command = args[++index];
} else {
System.err.println("Argument expected for the -c option");
System.err.print(jython.usageHeader);
System.err.println("Try `jython -h' for more information.");
return false;
}
if (!fixInteractive) {
interactive = false;
}
index++;
break;
} else if (arg.equals("-W")) {
warnoptions.add(args[++index]);
} else if (arg.equals("-C")) {
encoding = args[++index];
setProperty("python.console.encoding", encoding);
} else if (arg.equals("-E")) {
// XXX: accept -E (ignore environment variables) to be compatiable with
// CPython. do nothing for now (we could ignore the registry)
} else if (arg.startsWith("-D")) {
String key = null;
String value = null;
int equals = arg.indexOf("=");
if (equals == -1) {
String arg2 = args[++index];
key = arg.substring(2, arg.length());
value = arg2;
} else {
key = arg.substring(2, equals);
value = arg.substring(equals + 1, arg.length());
}
setProperty(key, value);
} else if (arg.startsWith("-Q")) {
if (arg.length() > 2) {
division = arg.substring(2);
} else {
division = args[++index];
}
} else if (arg.startsWith("-m")) {
runModule = true;
if (arg.length() > 2) {
moduleName = arg.substring(2);
} else if ((index + 1) < args.length) {
moduleName = args[++index];
} else {
System.err.println("Argument expected for the -m option");
System.err.print(jython.usageHeader);
System.err.println("Try `jython -h' for more information.");
return false;
}
if (!fixInteractive) {
interactive = false;
}
index++;
int n = args.length - index + 1;
argv = new String[n];
argv[0] = moduleName;
for (int i = 1; index < args.length; i++, index++) {
argv[i] = args[index];
}
return true;
} else {
String opt = args[index];
if (opt.startsWith("--")) {
opt = opt.substring(2);
} else if (opt.startsWith("-")) {
opt = opt.substring(1);
}
System.err.println("Unknown option: " + opt);
return false;
}
index += 1;
}
notice = interactive;
if (filename == null && index < args.length && command == null) {
filename = args[index++];
if (!fixInteractive) {
interactive = false;
}
notice = false;
}
if (command != null) {
notice = false;
}
int n = args.length - index + 1;
argv = new String[n];
if (filename != null) {
argv[0] = filename;
} else if (command != null) {
argv[0] = "-c";
} else {
argv[0] = "";
}
for (int i = 1; i < n; i++, index++) {
argv[i] = args[index];
}
return true;
}
}
| true | true | public static void run(String[] args) {
// Parse the command line options
CommandLineOptions opts = new CommandLineOptions();
if (!opts.parse(args)) {
if (opts.version) {
System.err.println("Jython " + Version.PY_VERSION);
System.exit(0);
}
if (!opts.runCommand && !opts.runModule) {
System.err.println(usage);
}
int exitcode = opts.help ? 0 : -1;
System.exit(exitcode);
}
// Setup the basic python system state from these options
PySystemState.initialize(PySystemState.getBaseProperties(), opts.properties, opts.argv);
PyList warnoptions = new PyList();
for (String wopt : opts.warnoptions) {
warnoptions.append(new PyString(wopt));
}
Py.getSystemState().setWarnoptions(warnoptions);
PySystemState systemState = Py.getSystemState();
// Decide if stdin is interactive
if (!opts.fixInteractive && opts.interactive) {
opts.interactive = ((PyFile)Py.defaultSystemState.stdin).isatty();
if (!opts.interactive) {
systemState.ps1 = systemState.ps2 = Py.EmptyString;
}
}
// Now create an interpreter
InteractiveConsole interp = newInterpreter(opts.interactive);
systemState.__setattr__("_jy_interpreter", Py.java2py(interp));
// Print banner and copyright information (or not)
if (opts.interactive && opts.notice && !opts.runModule) {
System.err.println(InteractiveConsole.getDefaultBanner());
}
if (Options.importSite) {
try {
imp.load("site");
if (opts.interactive && opts.notice && !opts.runModule) {
System.err.println(COPYRIGHT);
}
} catch (PyException pye) {
if (!pye.match(Py.ImportError)) {
System.err.println("error importing site");
Py.printException(pye);
System.exit(-1);
}
}
}
if (opts.division != null) {
if ("old".equals(opts.division)) {
Options.divisionWarning = 0;
} else if ("warn".equals(opts.division)) {
Options.divisionWarning = 1;
} else if ("warnall".equals(opts.division)) {
Options.divisionWarning = 2;
} else if ("new".equals(opts.division)) {
Options.Qnew = true;
interp.cflags.setFlag(CodeFlag.CO_FUTURE_DIVISION);
}
}
// was there a filename on the command line?
if (opts.filename != null) {
String path;
try {
path = new File(opts.filename).getCanonicalFile().getParent();
} catch (IOException ioe) {
path = new File(opts.filename).getAbsoluteFile().getParent();
}
if (path == null) {
path = "";
}
Py.getSystemState().path.insert(0, new PyString(path));
if (opts.jar) {
try {
runJar(opts.filename);
} catch (Throwable t) {
Py.printException(t);
System.exit(-1);
}
} else if (opts.filename.equals("-")) {
try {
interp.globals.__setitem__(new PyString("__file__"), new PyString("<stdin>"));
interp.execfile(System.in, "<stdin>");
} catch (Throwable t) {
Py.printException(t);
}
} else {
try {
interp.globals.__setitem__(new PyString("__file__"),
new PyString(opts.filename));
FileInputStream file;
try {
file = new FileInputStream(new RelativeFile(opts.filename));
} catch (FileNotFoundException e) {
throw Py.IOError(e);
}
try {
if (PosixModule.getPOSIX().isatty(file.getFD())) {
opts.interactive = true;
interp.interact(null, new PyFile(file));
System.exit(0);
} else {
interp.execfile(file, opts.filename);
}
} finally {
file.close();
}
} catch (Throwable t) {
if (t instanceof PyException
&& ((PyException)t).match(_systemrestart.SystemRestart)) {
// Shutdown this instance...
shouldRestart = true;
shutdownInterpreter();
interp.cleanup();
// ..reset the state...
Py.setSystemState(new PySystemState());
// ...and start again
return;
} else {
Py.printException(t);
if (!opts.interactive) {
interp.cleanup();
System.exit(-1);
}
}
}
}
}
else {
// if there was no file name on the command line, then "" is the first element
// on sys.path. This is here because if there /was/ a filename on the c.l.,
// and say the -i option was given, sys.path[0] will have gotten filled in
// with the dir of the argument filename.
Py.getSystemState().path.insert(0, Py.EmptyString);
if (opts.command != null) {
try {
interp.exec(opts.command);
} catch (Throwable t) {
Py.printException(t);
System.exit(1);
}
}
if (opts.moduleName != null) {
// PEP 338 - Execute module as a script
try {
interp.exec("import runpy");
interp.set("name", Py.newString(opts.moduleName));
interp.exec("runpy.run_module(name, run_name='__main__', alter_sys=True)");
interp.cleanup();
System.exit(0);
} catch (Throwable t) {
Py.printException(t);
interp.cleanup();
System.exit(-1);
}
}
}
if (opts.fixInteractive || (opts.filename == null && opts.command == null)) {
if (opts.encoding == null) {
opts.encoding = PySystemState.registry.getProperty("python.console.encoding");
}
if (opts.encoding != null) {
if (!Charset.isSupported(opts.encoding)) {
System.err.println(opts.encoding
+ " is not a supported encoding on this JVM, so it can't "
+ "be used in python.console.encoding.");
System.exit(1);
}
interp.cflags.encoding = opts.encoding;
}
try {
interp.interact(null, null);
} catch (Throwable t) {
Py.printException(t);
}
}
interp.cleanup();
if (opts.fixInteractive || opts.interactive) {
System.exit(0);
}
}
| public static void run(String[] args) {
// Parse the command line options
CommandLineOptions opts = new CommandLineOptions();
if (!opts.parse(args)) {
if (opts.version) {
System.err.println("Jython " + Version.PY_VERSION);
System.exit(0);
}
if (!opts.runCommand && !opts.runModule) {
System.err.println(usage);
}
int exitcode = opts.help ? 0 : -1;
System.exit(exitcode);
}
// Setup the basic python system state from these options
PySystemState.initialize(PySystemState.getBaseProperties(), opts.properties, opts.argv);
PyList warnoptions = new PyList();
for (String wopt : opts.warnoptions) {
warnoptions.append(new PyString(wopt));
}
Py.getSystemState().setWarnoptions(warnoptions);
PySystemState systemState = Py.getSystemState();
// Decide if stdin is interactive
if (!opts.fixInteractive || opts.interactive) {
opts.interactive = ((PyFile)Py.defaultSystemState.stdin).isatty();
if (!opts.interactive) {
systemState.ps1 = systemState.ps2 = Py.EmptyString;
}
}
// Now create an interpreter
InteractiveConsole interp = newInterpreter(opts.interactive);
systemState.__setattr__("_jy_interpreter", Py.java2py(interp));
// Print banner and copyright information (or not)
if (opts.interactive && opts.notice && !opts.runModule) {
System.err.println(InteractiveConsole.getDefaultBanner());
}
if (Options.importSite) {
try {
imp.load("site");
if (opts.interactive && opts.notice && !opts.runModule) {
System.err.println(COPYRIGHT);
}
} catch (PyException pye) {
if (!pye.match(Py.ImportError)) {
System.err.println("error importing site");
Py.printException(pye);
System.exit(-1);
}
}
}
if (opts.division != null) {
if ("old".equals(opts.division)) {
Options.divisionWarning = 0;
} else if ("warn".equals(opts.division)) {
Options.divisionWarning = 1;
} else if ("warnall".equals(opts.division)) {
Options.divisionWarning = 2;
} else if ("new".equals(opts.division)) {
Options.Qnew = true;
interp.cflags.setFlag(CodeFlag.CO_FUTURE_DIVISION);
}
}
// was there a filename on the command line?
if (opts.filename != null) {
String path;
try {
path = new File(opts.filename).getCanonicalFile().getParent();
} catch (IOException ioe) {
path = new File(opts.filename).getAbsoluteFile().getParent();
}
if (path == null) {
path = "";
}
Py.getSystemState().path.insert(0, new PyString(path));
if (opts.jar) {
try {
runJar(opts.filename);
} catch (Throwable t) {
Py.printException(t);
System.exit(-1);
}
} else if (opts.filename.equals("-")) {
try {
interp.globals.__setitem__(new PyString("__file__"), new PyString("<stdin>"));
interp.execfile(System.in, "<stdin>");
} catch (Throwable t) {
Py.printException(t);
}
} else {
try {
interp.globals.__setitem__(new PyString("__file__"),
new PyString(opts.filename));
FileInputStream file;
try {
file = new FileInputStream(new RelativeFile(opts.filename));
} catch (FileNotFoundException e) {
throw Py.IOError(e);
}
try {
if (PosixModule.getPOSIX().isatty(file.getFD())) {
opts.interactive = true;
interp.interact(null, new PyFile(file));
System.exit(0);
} else {
interp.execfile(file, opts.filename);
}
} finally {
file.close();
}
} catch (Throwable t) {
if (t instanceof PyException
&& ((PyException)t).match(_systemrestart.SystemRestart)) {
// Shutdown this instance...
shouldRestart = true;
shutdownInterpreter();
interp.cleanup();
// ..reset the state...
Py.setSystemState(new PySystemState());
// ...and start again
return;
} else {
Py.printException(t);
if (!opts.interactive) {
interp.cleanup();
System.exit(-1);
}
}
}
}
}
else {
// if there was no file name on the command line, then "" is the first element
// on sys.path. This is here because if there /was/ a filename on the c.l.,
// and say the -i option was given, sys.path[0] will have gotten filled in
// with the dir of the argument filename.
Py.getSystemState().path.insert(0, Py.EmptyString);
if (opts.command != null) {
try {
interp.exec(opts.command);
} catch (Throwable t) {
Py.printException(t);
System.exit(1);
}
}
if (opts.moduleName != null) {
// PEP 338 - Execute module as a script
try {
interp.exec("import runpy");
interp.set("name", Py.newString(opts.moduleName));
interp.exec("runpy.run_module(name, run_name='__main__', alter_sys=True)");
interp.cleanup();
System.exit(0);
} catch (Throwable t) {
Py.printException(t);
interp.cleanup();
System.exit(-1);
}
}
}
if (opts.fixInteractive || (opts.filename == null && opts.command == null)) {
if (opts.encoding == null) {
opts.encoding = PySystemState.registry.getProperty("python.console.encoding");
}
if (opts.encoding != null) {
if (!Charset.isSupported(opts.encoding)) {
System.err.println(opts.encoding
+ " is not a supported encoding on this JVM, so it can't "
+ "be used in python.console.encoding.");
System.exit(1);
}
interp.cflags.encoding = opts.encoding;
}
try {
interp.interact(null, null);
} catch (Throwable t) {
Py.printException(t);
}
}
interp.cleanup();
if (opts.fixInteractive || opts.interactive) {
System.exit(0);
}
}
|
diff --git a/reports/src/main/java/org/sola/clients/reports/ReportManager.java b/reports/src/main/java/org/sola/clients/reports/ReportManager.java
index 659df182..65eaf863 100644
--- a/reports/src/main/java/org/sola/clients/reports/ReportManager.java
+++ b/reports/src/main/java/org/sola/clients/reports/ReportManager.java
@@ -1,940 +1,942 @@
/**
* ******************************************************************************************
* Copyright (c) 2013 Food and Agriculture Organization of the United Nations (FAO)
* and the Lesotho Land Administration Authority (LAA). 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. Neither the names of FAO, the LAA nor the names of its contributors may be used to
* endorse or promote products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,STRICT LIABILITY,OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* *********************************************************************************************
*/
package org.sola.clients.reports;
import java.io.IOException;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import net.sf.jasperreports.engine.*;
import net.sf.jasperreports.engine.data.JRBeanArrayDataSource;
import org.apache.commons.lang.time.DateFormatUtils;
import org.sola.clients.beans.administrative.*;
import org.sola.clients.beans.administrative.BaUnitBean;
import org.sola.clients.beans.administrative.LeaseReportBean;
import org.sola.clients.beans.administrative.DisputeBean;
import org.sola.clients.beans.administrative.DisputeSearchResultBean;
import org.sola.clients.beans.administrative.RrrReportBean;
import org.sola.clients.beans.application.*;
import org.sola.clients.beans.cadastre.CadastreObjectBean;
import org.sola.clients.beans.system.BrReportBean;
import org.sola.clients.beans.security.SecurityBean;
import org.sola.clients.beans.system.BrListBean;
import org.sola.clients.beans.systematicregistration.*;
import org.sola.common.messaging.ClientMessage;
import org.sola.common.messaging.MessageUtility;
/**
* Provides methods to generate and display various reports.
*/
public class ReportManager {
/**
* Generates and displays <b>Lodgement notice</b> report for the new
* application.
*
* @param appBean Application bean containing data for the report.
*/
public static JasperPrint getLodgementNoticeReport(ApplicationBean appBean) {
HashMap inputParameters = new HashMap();
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("today", new Date());
inputParameters.put("USER_NAME", SecurityBean.getCurrentUser().getFullUserName());
ApplicationBean[] beans = new ApplicationBean[1];
beans[0] = appBean;
JRDataSource jds = new JRBeanArrayDataSource(beans);
inputParameters.put("IMAGE_SCRITTA_GREEN", ReportManager.class.getResourceAsStream("/images/sola/caption_green.png"));
inputParameters.put("WHICH_CALLER", "N");
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/ApplicationPrintingForm.jasper"),
inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
/**
* Generates and displays <b>Lodgement notice</b> report for the new
* application.
*
* @param appBean Application bean containing data for the report.
*/
public static JasperPrint getDisputeConfirmationReport(DisputeBean dispBean) {
HashMap inputParameters = new HashMap();
inputParameters.put("USER", SecurityBean.getCurrentUser().getFullUserName());
inputParameters.put("LODGEMENTDATE",dispBean.getLodgementDate());
inputParameters.put("DISPUTE_CATEGORY",dispBean.getDisputeCategory().getDisplayValue());
inputParameters.put("DISPUTE_TYPE",dispBean.getDisputeType().getDisplayValue());
DisputeBean[] beans = new DisputeBean[1];
beans[0] = dispBean;
JRDataSource jds = new JRBeanArrayDataSource(beans);
inputParameters.put("IMAGE_SCRITTA_GREEN", ReportManager.class.getResourceAsStream("/images/sola/caption_green.png"));
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/DisputeConfirmation.jasper"),
inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
public static JasperPrint getDisputeMonthlyStatus(List<DisputeSearchResultBean> disputeSearchResultBean) {
//List<DisputeBean> dispBeans
HashMap inputParameters = new HashMap();
inputParameters.put("USER", SecurityBean.getCurrentUser().getFullUserName());
DisputeSearchResultBean[] beans = disputeSearchResultBean.toArray(new DisputeSearchResultBean[0]);
JRDataSource jds = new JRBeanArrayDataSource(beans);
inputParameters.put("IMAGE_SCRITTA_GREEN", ReportManager.class.getResourceAsStream("/images/sola/caption_green.png"));
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/DisputeMonthlyStatus.jasper"),
inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
public static JasperPrint getDisputeMonthlyReport(List<DisputeSearchResultBean> disputeSearchResultBean,
Date startDate,
Date endDate,
String numDisputes,
String pendingDisputes,
String completeDisputes,
String sporadic,
String regular,
String unregistered,
String numCourtCases,
String pendingCourtCases,
String completeCourtCases,
String primaryRespond,
String numPrimaryRespondPending) {
HashMap inputParameters = new HashMap();
inputParameters.put("USER", SecurityBean.getCurrentUser().getFullUserName());
inputParameters.put("NUM_DISPUTES", numDisputes);
inputParameters.put("PENDING_DISPUTES", pendingDisputes);
inputParameters.put("COMPLETE_DISPUTES", completeDisputes);
inputParameters.put("SPORADIC_DISPUTES", sporadic);
inputParameters.put("REGULAR_DISPUTES", regular);
inputParameters.put("UNREG_DISPUTES", unregistered);
inputParameters.put("NUM_COURT_CASES", numCourtCases);
inputParameters.put("PENDING_COURT", pendingCourtCases);
inputParameters.put("COMPLETE_COURT", completeCourtCases);
inputParameters.put("PRIMARY_RESPOND", primaryRespond);
inputParameters.put("PRIMARY_RESPOND_PENDING", completeCourtCases);
//inputParameters.put("USER", );
DisputeSearchResultBean[] beans = disputeSearchResultBean.toArray(new DisputeSearchResultBean[0]);
JRDataSource jds = new JRBeanArrayDataSource(beans);
inputParameters.put("IMAGE_SCRITTA_GREEN", ReportManager.class.getResourceAsStream("/images/sola/caption_green.png"));
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/DisputeMonthlyReport.jasper"),
inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
public static JasperPrint getDisputeStatisticsReport(List<DisputeSearchResultBean> disputeSearchResultBean,
String startDate,
String endDate,
String numDisputes,
String numCases,
String averageDisputeDays,
String averageCourtDays,
String numPendingDisputes,
String numPendingCourt,
String numClosedDisputes,
String numClosedCourt) {
HashMap inputParameters = new HashMap();
inputParameters.put("USER", SecurityBean.getCurrentUser().getFullUserName());
inputParameters.put("START_DATE", startDate);
inputParameters.put("END_DATE", endDate);
inputParameters.put("NUM_DISPUTES", numDisputes);
inputParameters.put("NUM_COURT", numCases);
inputParameters.put("AVRG_DAYS_DISPUTES", averageDisputeDays);
inputParameters.put("AVRG_DAYS_COURT", averageCourtDays);
inputParameters.put("NUM_PENDING_DISPUTES", numPendingDisputes);
inputParameters.put("NUM_PENDING_COURT", numPendingCourt);
inputParameters.put("NUM_CLOSED_DISPUTES", numClosedDisputes);
inputParameters.put("NUM_CLOSED_COURT", numClosedCourt);
DisputeSearchResultBean[] beans = disputeSearchResultBean.toArray(new DisputeSearchResultBean[0]);
JRDataSource jds = new JRBeanArrayDataSource(beans);
inputParameters.put("IMAGE_SCRITTA_GREEN", ReportManager.class.getResourceAsStream("/images/sola/caption_green.png"));
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/DisputeStatistics.jasper"),
inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
/**
* Generates and displays <b>Application m report</b>.
*
* @param appBean Application bean containing data for the report.
*/
public static JasperPrint getApplicationStatusReport(ApplicationBean appBean) {
HashMap inputParameters = new HashMap();
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("today", new Date());
inputParameters.put("USER_NAME", SecurityBean.getCurrentUser().getFullUserName());
ApplicationBean[] beans = new ApplicationBean[1];
beans[0] = appBean;
JRDataSource jds = new JRBeanArrayDataSource(beans);
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/ApplicationStatusReport.jasper"),
inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
/**
* Generates and displays <b>BA Unit</b> report.
*
* @param appBean Application bean containing data for the report.
*/
public static JasperPrint getBaUnitReport(BaUnitBean baUnitBean) {
HashMap inputParameters = new HashMap();
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("USER", SecurityBean.getCurrentUser().getFullUserName());
BaUnitBean[] beans = new BaUnitBean[1];
beans[0] = baUnitBean;
JRDataSource jds = new JRBeanArrayDataSource(beans);
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/BaUnitReport.jasper"),
inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
/**
* Generates and displays <b>Lease rejection</b> report.
*
* @param reportBean RRR report bean containing all required information to
* build the report.
*/
public static JasperPrint getLeaseRejectionReport(LeaseReportBean reportBean) {
HashMap inputParameters = new HashMap();
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("USER_NAME", SecurityBean.getCurrentUser().getFullUserName());
LeaseReportBean[] beans = new LeaseReportBean[1];
beans[0] = reportBean;
JRDataSource jds = new JRBeanArrayDataSource(beans);
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/lease/LeaseRefuseLetter.jasper"),
inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
/**
* Generates and displays <b>Lease offer</b> report.
*
* @param reportBean RRR report bean containing all required information to
* build the report.
*/
public static JasperPrint getLeaseOfferReport(LeaseReportBean reportBean) {
HashMap inputParameters = new HashMap();
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("USER_NAME", SecurityBean.getCurrentUser().getFullUserName());
LeaseReportBean[] beans = new LeaseReportBean[1];
beans[0] = reportBean;
JRDataSource jds = new JRBeanArrayDataSource(beans);
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/lease/LeaseOfferReport.jasper"),
inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
/**
* Generates and displays <b>Lease</b> report.
*
* @param reportBean RRR report bean containing all required information to
* build the report.
*/
public static JasperPrint getLeaseReport(LeaseReportBean reportBean, String mapImageFileName) {
HashMap inputParameters = new HashMap();
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("USER_NAME", SecurityBean.getCurrentUser().getFullUserName());
inputParameters.put("MAP_IMAGE", mapImageFileName);
LeaseReportBean[] beans = new LeaseReportBean[1];
beans[0] = reportBean;
JRDataSource jds = new JRBeanArrayDataSource(beans);
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/lease/LeaseReport.jasper"),
inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
/**
* Generates and displays <b>Lease Surrender</b> report.
*
* @param reportBean RRR report bean containing all required information to
* build the report.
*/
public static JasperPrint getLeaseSurrenderReport(LeaseReportBean reportBean) {
HashMap inputParameters = new HashMap();
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("USER_NAME", SecurityBean.getCurrentUser().getFullUserName());
LeaseReportBean[] beans = new LeaseReportBean[1];
beans[0] = reportBean;
JRDataSource jds = new JRBeanArrayDataSource(beans);
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/lease/SurrenderLeaseReport.jasper"),
inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
/**
* Generates and displays <b>Lease Vary</b> report.
*
* @param reportBean RRR report bean containing all required information to
* build the report.
*/
public static JasperPrint getLeaseVaryReport(LeaseReportBean reportBean) {
HashMap inputParameters = new HashMap();
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("USER_NAME", SecurityBean.getCurrentUser().getFullUserName());
LeaseReportBean[] beans = new LeaseReportBean[1];
beans[0] = reportBean;
JRDataSource jds = new JRBeanArrayDataSource(beans);
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/lease/VaryLeaseReport.jasper"),
inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
/**
* Generates and displays <b>Lease Vary</b> report.
*
* @param reportBean RRR report bean containing all required information to
* build the report.
*/
public static JasperPrint getSuccessionReport(LeaseReportBean reportBean) {
HashMap inputParameters = new HashMap();
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("USER_NAME", SecurityBean.getCurrentUser().getFullUserName());
LeaseReportBean[] beans = new LeaseReportBean[1];
beans[0] = reportBean;
JRDataSource jds = new JRBeanArrayDataSource(beans);
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/lease/SuccessionReport.jasper"),
inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
/**
* Generates and displays <b>Application payment receipt</b>.
*
* @param appBean Application bean containing data for the report.
*/
public static JasperPrint getApplicationFeeReport(ApplicationBean appBean) {
HashMap inputParameters = new HashMap();
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("today", new Date());
inputParameters.put("USER_NAME", SecurityBean.getCurrentUser().getFullUserName());
ApplicationBean[] beans = new ApplicationBean[1];
beans[0] = appBean;
JRDataSource jds = new JRBeanArrayDataSource(beans);
inputParameters.put("IMAGE_SCRITTA_GREEN", ReportManager.class.getResourceAsStream("/images/sola/caption_orange.png"));
inputParameters.put("WHICH_CALLER", "R");
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/ApplicationPrintingForm.jasper"), inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
/**
* Generates and displays <b>Survey report</b>.
*
* @param co CadastreObjectBean containing data for the report.
* @param appNumber Application number
*/
public static JasperPrint getSurveyReport(CadastreObjectBean co, String appNumber) {
HashMap inputParameters = new HashMap();
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("USER_NAME", SecurityBean.getCurrentUser().getFullUserName());
inputParameters.put("APP_NUMBER", appNumber);
inputParameters.put("ROAD_CLASS", co.getRoadClassType().getTranslatedDisplayValue());
inputParameters.put("VALUATION_ZONE", co.getLandGradeType().getTranslatedDisplayValue());
CadastreObjectBean[] beans = new CadastreObjectBean[1];
beans[0] = co;
JRDataSource jds = new JRBeanArrayDataSource(beans);
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/map/SurveyFormS10.jasper"), inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
/**
* Generates and displays <b>Consent Report</b>.
*
* @param appNumber Application number
*/
public static JasperPrint getConsentReport(ConsentBean consentBean) {
HashMap inputParameters = new HashMap();
inputParameters.put("DUE_DATE", DateFormatUtils.format(consentBean.getExpirationDate(), "d MMMMM yyyy"));
inputParameters.put("CONDITION_TEXT", consentBean.getSpecialConditions());
inputParameters.put("CONSIDERATION_AMOUNT", consentBean.getAmountInWords());
inputParameters.put("TRANSACTION_TYPE", consentBean.getTransactionTypeName());
ConsentBean[] beans = new ConsentBean[1];
beans[0] = consentBean;
JRDataSource jds = new JRBeanArrayDataSource(beans);
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/ConsentReport.jasper"),
inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
/**
* Generates and displays <b>Consent offer</b> report.
*
* @param consentBean RRR report bean containing all required information to
* build the report.
*/
public static JasperPrint getConsentRejectionReport(ConsentBean consentBean, ApplicationBean appBean, String freeText) {
HashMap inputParameters = new HashMap();
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("USER_NAME", SecurityBean.getCurrentUser().getFullUserName());
inputParameters.put("APPLICANT_NAME", appBean.getContactPerson().getFullName());
inputParameters.put("APPLICATION_NUMBER", appBean.getApplicationNumberFormatted());
inputParameters.put("FREE_TEXT", freeText);
ConsentBean[] beans = new ConsentBean[1];
beans[0] = consentBean;
JRDataSource jds = new JRBeanArrayDataSource(beans);
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/ConsentRejectionLetter.jasper"),
inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
/**
* Generates and displays <b>BR Report</b>.
*/
public static JasperPrint getBrReport() {
HashMap inputParameters = new HashMap();
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("today", new Date());
inputParameters.put("USER_NAME", SecurityBean.getCurrentUser().getFullUserName());
BrListBean brList = new BrListBean();
brList.FillBrs();
int sizeBrList = brList.getBrBeanList().size();
BrReportBean[] beans = new BrReportBean[sizeBrList];
for (int i = 0; i < sizeBrList; i++) {
beans[i] = brList.getBrBeanList().get(i);
if (beans[i].getFeedback() != null) {
String feedback = beans[i].getFeedback();
- feedback = feedback.substring(0, feedback.indexOf("::::"));
+ if(feedback.indexOf("::::")>-1){
+ feedback = feedback.substring(0, feedback.indexOf("::::"));
+ }
beans[i].setFeedback(feedback);
}
if (i > 0) {
String idPrev = beans[i - 1].getId();
String technicalTypeCodePrev = beans[i - 1].getTechnicalTypeCode();
String id = beans[i].getId();
String technicalTypeCode = beans[i].getTechnicalTypeCode();
if (id.equals(idPrev)
&& technicalTypeCode.equals(technicalTypeCodePrev)) {
beans[i].setId("");
beans[i].setBody("");
beans[i].setDescription("");
beans[i].setFeedback("");
beans[i].setTechnicalTypeCode("");
}
}
}
JRDataSource jds = new JRBeanArrayDataSource(beans);
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/BrReport.jasper"), inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
/**
* Generates and displays <b>BR VAlidaction Report</b>.
*/
public static JasperPrint getBrValidaction() {
HashMap inputParameters = new HashMap();
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("today", new Date());
inputParameters.put("USER_NAME", SecurityBean.getCurrentUser().getUserName());
BrListBean brList = new BrListBean();
brList.FillBrs();
int sizeBrList = brList.getBrBeanList().size();
BrReportBean[] beans = new BrReportBean[sizeBrList];
for (int i = 0; i < sizeBrList; i++) {
beans[i] = brList.getBrBeanList().get(i);
}
JRDataSource jds = new JRBeanArrayDataSource(beans);
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/BrValidaction.jasper"), inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
/**
* Generates and displays <b>BA Unit</b> report.
*
* @param appBean Application bean containing data for the report.
*/
public static JasperPrint getLodgementReport(LodgementBean lodgementBean, Date dateFrom, Date dateTo) {
HashMap inputParameters = new HashMap();
Date currentdate = new Date(System.currentTimeMillis());
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("CURRENT_DATE", currentdate);
inputParameters.put("USER", SecurityBean.getCurrentUser().getFullUserName());
inputParameters.put("FROMDATE", dateFrom);
inputParameters.put("TODATE", dateTo);
LodgementBean[] beans = new LodgementBean[1];
beans[0] = lodgementBean;
JRDataSource jds = new JRBeanArrayDataSource(beans);
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/LodgementReport.jasper"),
inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
/**
* Generates and displays <b>SolaPrintReport</b> for the map.
*
* @param layoutId String This is the id of the report. It is used to
* identify the report file.
* @param dataBean Object containing data for the report. it can be replaced
* with appropriate bean if needed
* @param mapImageLocation String this is the location of the map to be
* passed as MAP_IMAGE PARAMETER to the report. It is necessary for
* visualizing the map
* @param scalebarImageLocation String this is the location of the scalebar
* to be passed as SCALE_IMAGE PARAMETER to the report. It is necessary for
* visualizing the scalebar
*/
public static JasperPrint getSolaPrintReport(String layoutId, Object dataBean,
String mapImageLocation, String scalebarImageLocation) throws IOException {
// Image Location of the north-arrow image
String navigatorImage = "/images/sola/north-arrow.png";
HashMap inputParameters = new HashMap();
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("USER_NAME", SecurityBean.getCurrentUser().getFullUserName());
inputParameters.put("MAP_IMAGE", mapImageLocation);
inputParameters.put("SCALE_IMAGE", scalebarImageLocation);
inputParameters.put("NAVIGATOR_IMAGE",
ReportManager.class.getResourceAsStream(navigatorImage));
inputParameters.put("LAYOUT", layoutId);
inputParameters.put("INPUT_DATE",
DateFormat.getInstance().format(Calendar.getInstance().getTime()));
//This will be the bean containing data for the report.
//it is the data source for the report
//it must be replaced with appropriate bean if needed
Object[] beans = new Object[1];
beans[0] = dataBean;
JRDataSource jds = new JRBeanArrayDataSource(beans);
// this generates the report.
// NOTICE THAT THE NAMING CONVENTION IS TO PRECEED "SolaPrintReport.jasper"
// WITH THE LAYOUT NAME. SO IT MUST BE PRESENT ONE REPORT FOR EACH LAYOUT FORMAT
try {
JasperPrint jasperPrint = JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream(
"/reports/map/" + layoutId + ".jasper"), inputParameters, jds);
return jasperPrint;
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
public static JasperPrint getMapPublicDisplayReport(
String layoutId, String areaDescription, String notificationPeriod,
String mapImageLocation, String scalebarImageLocation) throws IOException {
// Image Location of the north-arrow image
String navigatorImage = "/images/sola/north-arrow.png";
HashMap inputParameters = new HashMap();
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("USER_NAME", SecurityBean.getCurrentUser().getFullUserName());
inputParameters.put("MAP_IMAGE", mapImageLocation);
inputParameters.put("SCALE_IMAGE", scalebarImageLocation);
inputParameters.put("NAVIGATOR_IMAGE",
ReportManager.class.getResourceAsStream(navigatorImage));
inputParameters.put("LAYOUT", layoutId);
inputParameters.put("INPUT_DATE",
DateFormat.getInstance().format(Calendar.getInstance().getTime()));
inputParameters.put("AREA_DESCRIPTION", areaDescription);
inputParameters.put("PERIOD_DESCRIPTION", notificationPeriod);
//This will be the bean containing data for the report.
//it is the data source for the report
//it must be replaced with appropriate bean if needed
Object[] beans = new Object[1];
beans[0] = new Object();
JRDataSource jds = new JRBeanArrayDataSource(beans);
try {
JasperPrint jasperPrint = JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream(
"/reports/map/" + layoutId + ".jasper"), inputParameters, jds);
return jasperPrint;
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
/**
* Generates and displays <b>Systematic registration Public display
* report</b>.
*
* @param parcelnumberList List Parcel list bean containing data for the
* report.
*
*/
public static JasperPrint getSysRegPubDisParcelNameReport(ParcelNumberListingListBean parcelnumberList,
Date dateFrom, Date dateTo, String location, String subReport) {
HashMap inputParameters = new HashMap();
// Date currentdate = new Date(System.currentTimeMillis());
// inputParameters.put("CURRENT_DATE", currentdate);
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("USER", SecurityBean.getCurrentUser().getFullUserName());
inputParameters.put("FROM_DATE", dateFrom);
inputParameters.put("TO_DATE", dateTo);
inputParameters.put("LOCATION", location);
inputParameters.put("SUB_REPORT", subReport);
ParcelNumberListingListBean[] beans = new ParcelNumberListingListBean[1];
beans[0] = parcelnumberList;
JRDataSource jds = new JRBeanArrayDataSource(beans);
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/SysRegPubDisParcelName.jasper"),
inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
/**
* Generates and displays <b>Systematic registration Public display
* report</b>.
*
* @param ownernameList List Parcel list bean containing data for the
* report.
*
*/
public static JasperPrint getSysRegPubDisOwnerNameReport(OwnerNameListingListBean ownernameList,
Date dateFrom, Date dateTo, String location, String subReport) {
HashMap inputParameters = new HashMap();
// Date currentdate = new Date(System.currentTimeMillis());
// inputParameters.put("CURRENT_DATE", currentdate);
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("USER", SecurityBean.getCurrentUser().getFullUserName());
inputParameters.put("FROM_DATE", dateFrom);
inputParameters.put("TO_DATE", dateTo);
inputParameters.put("LOCATION", location);
inputParameters.put("SUB_REPORT", subReport);
OwnerNameListingListBean[] beans = new OwnerNameListingListBean[1];
beans[0] = ownernameList;
JRDataSource jds = new JRBeanArrayDataSource(beans);
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/SysRegPubDisOwners.jasper"),
inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
/**
* Generates and displays <b>Systematic registration Public display
* report</b>.
*
* @param ownernameList List Parcel list bean containing data for the
* report.
*
*/
public static JasperPrint getSysRegPubDisStateLandReport(StateLandListingListBean statelandList,
Date dateFrom, Date dateTo, String location, String subReport) {
HashMap inputParameters = new HashMap();
// Date currentdate = new Date(System.currentTimeMillis());
// inputParameters.put("CURRENT_DATE", currentdate);
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("USER", SecurityBean.getCurrentUser().getFullUserName());
inputParameters.put("FROM_DATE", dateFrom);
inputParameters.put("TO_DATE", dateTo);
inputParameters.put("LOCATION", location);
inputParameters.put("SUB_REPORT", subReport);
StateLandListingListBean[] beans = new StateLandListingListBean[1];
beans[0] = statelandList;
JRDataSource jds = new JRBeanArrayDataSource(beans);
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/SysRegPubDisStateLand.jasper"),
inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
/**
* Generates and displays <b>Systematic registration Certificates
* report</b>.
*
* @param certificatesList List Parcel list bean containing data for the
* report.
*
*/
public static JasperPrint getSysRegCertificatesReport(BaUnitBean baUnitBean, String location) {
HashMap inputParameters = new HashMap();
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("USER", SecurityBean.getCurrentUser().getFullUserName());
inputParameters.put("LOCATION", location);
inputParameters.put("AREA", location);
BaUnitBean[] beans = new BaUnitBean[1];
beans[0] = baUnitBean;
JRDataSource jds = new JRBeanArrayDataSource(beans);
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/SysRegCertificates.jasper"),
inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
/**
* Generates and displays <b>BA Unit</b> report.
*
* @param appBean Application bean containing data for the report.
*/
public static JasperPrint getSysRegManagementReport(SysRegManagementBean managementBean, Date dateFrom, Date dateTo, String nameLastpart) {
HashMap inputParameters = new HashMap();
Date currentdate = new Date(System.currentTimeMillis());
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("CURRENT_DATE", currentdate);
inputParameters.put("USER", SecurityBean.getCurrentUser().getFullUserName());
inputParameters.put("FROMDATE", dateFrom);
inputParameters.put("TODATE", dateTo);
inputParameters.put("AREA", nameLastpart);
SysRegManagementBean[] beans = new SysRegManagementBean[1];
beans[0] = managementBean;
JRDataSource jds = new JRBeanArrayDataSource(beans);
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/SysRegMenagement.jasper"),
inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
// /**
// * Generates and displays <b>Sys Reg Status</b> report.
// *
// * @param appBean Application bean containing data for the report.
// */
public static JasperPrint getSysRegStatusReport(SysRegStatusBean statusBean, Date dateFrom, Date dateTo, String nameLastpart) {
HashMap inputParameters = new HashMap();
Date currentdate = new Date(System.currentTimeMillis());
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("CURRENT_DATE", currentdate);
inputParameters.put("USER", SecurityBean.getCurrentUser().getFullUserName());
inputParameters.put("FROMDATE", dateFrom);
inputParameters.put("TODATE", dateTo);
inputParameters.put("AREA", nameLastpart);
SysRegStatusBean[] beans = new SysRegStatusBean[1];
beans[0] = statusBean;
JRDataSource jds = new JRBeanArrayDataSource(beans);
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/SysRegStatus.jasper"),
inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
// /**
// * Generates and displays <b>Sys Reg Progress</b> report.
// *
// * @param appBean Application bean containing data for the report.
// */
public static JasperPrint getSysRegProgressReport(SysRegProgressBean progressBean, Date dateFrom, Date dateTo, String nameLastpart) {
HashMap inputParameters = new HashMap();
Date currentdate = new Date(System.currentTimeMillis());
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("CURRENT_DATE", currentdate);
inputParameters.put("USER", SecurityBean.getCurrentUser().getFullUserName());
inputParameters.put("FROMDATE", dateFrom);
inputParameters.put("TODATE", dateTo);
inputParameters.put("AREA", nameLastpart);
SysRegProgressBean[] beans = new SysRegProgressBean[1];
beans[0] = progressBean;
JRDataSource jds = new JRBeanArrayDataSource(beans);
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/SysRegProgress.jasper"),
inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
}
| true | true | public static JasperPrint getBrReport() {
HashMap inputParameters = new HashMap();
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("today", new Date());
inputParameters.put("USER_NAME", SecurityBean.getCurrentUser().getFullUserName());
BrListBean brList = new BrListBean();
brList.FillBrs();
int sizeBrList = brList.getBrBeanList().size();
BrReportBean[] beans = new BrReportBean[sizeBrList];
for (int i = 0; i < sizeBrList; i++) {
beans[i] = brList.getBrBeanList().get(i);
if (beans[i].getFeedback() != null) {
String feedback = beans[i].getFeedback();
feedback = feedback.substring(0, feedback.indexOf("::::"));
beans[i].setFeedback(feedback);
}
if (i > 0) {
String idPrev = beans[i - 1].getId();
String technicalTypeCodePrev = beans[i - 1].getTechnicalTypeCode();
String id = beans[i].getId();
String technicalTypeCode = beans[i].getTechnicalTypeCode();
if (id.equals(idPrev)
&& technicalTypeCode.equals(technicalTypeCodePrev)) {
beans[i].setId("");
beans[i].setBody("");
beans[i].setDescription("");
beans[i].setFeedback("");
beans[i].setTechnicalTypeCode("");
}
}
}
JRDataSource jds = new JRBeanArrayDataSource(beans);
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/BrReport.jasper"), inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
| public static JasperPrint getBrReport() {
HashMap inputParameters = new HashMap();
inputParameters.put("REPORT_LOCALE", Locale.getDefault());
inputParameters.put("today", new Date());
inputParameters.put("USER_NAME", SecurityBean.getCurrentUser().getFullUserName());
BrListBean brList = new BrListBean();
brList.FillBrs();
int sizeBrList = brList.getBrBeanList().size();
BrReportBean[] beans = new BrReportBean[sizeBrList];
for (int i = 0; i < sizeBrList; i++) {
beans[i] = brList.getBrBeanList().get(i);
if (beans[i].getFeedback() != null) {
String feedback = beans[i].getFeedback();
if(feedback.indexOf("::::")>-1){
feedback = feedback.substring(0, feedback.indexOf("::::"));
}
beans[i].setFeedback(feedback);
}
if (i > 0) {
String idPrev = beans[i - 1].getId();
String technicalTypeCodePrev = beans[i - 1].getTechnicalTypeCode();
String id = beans[i].getId();
String technicalTypeCode = beans[i].getTechnicalTypeCode();
if (id.equals(idPrev)
&& technicalTypeCode.equals(technicalTypeCodePrev)) {
beans[i].setId("");
beans[i].setBody("");
beans[i].setDescription("");
beans[i].setFeedback("");
beans[i].setTechnicalTypeCode("");
}
}
}
JRDataSource jds = new JRBeanArrayDataSource(beans);
try {
return JasperFillManager.fillReport(
ReportManager.class.getResourceAsStream("/reports/BrReport.jasper"), inputParameters, jds);
} catch (JRException ex) {
MessageUtility.displayMessage(ClientMessage.REPORT_GENERATION_FAILED,
new Object[]{ex.getLocalizedMessage()});
return null;
}
}
|
diff --git a/sccp/sccp-api/src/main/java/org/mobicents/protocols/ss7/indicator/NatureOfAddress.java b/sccp/sccp-api/src/main/java/org/mobicents/protocols/ss7/indicator/NatureOfAddress.java
index d7f68b015..4959f6db6 100644
--- a/sccp/sccp-api/src/main/java/org/mobicents/protocols/ss7/indicator/NatureOfAddress.java
+++ b/sccp/sccp-api/src/main/java/org/mobicents/protocols/ss7/indicator/NatureOfAddress.java
@@ -1,323 +1,325 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This 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 software 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 software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.mobicents.protocols.ss7.indicator;
import java.io.IOException;
/**
* Refer ITU-T Q.713 Page 9 of pdf Nature of address indicator.
*
* @author kulikov
* @author amit bhayani
*/
public enum NatureOfAddress {
UNKNOWN(0), SUBSCRIBER(1), RESERVED_NATIONAL_2(2), NATIONAL(3), INTERNATIONAL(4), SPARE_5(5), SPARE_6(6), SPARE_7(7), SPARE_8(
8), SPARE_9(9), SPARE_10(10), SPARE_11(11), SPARE_12(12), SPARE_13(13), SPARE_14(14), SPARE_15(15), SPARE_16(
16), SPARE_17(17), SPARE_18(18), SPARE_19(19), SPARE_20(20), SPARE_21(21), SPARE_22(22), SPARE_23(23), SPARE_24(
24), SPARE_25(25), SPARE_26(26), SPARE_27(27), SPARE_28(28), SPARE_29(29), SPARE_30(30), SPARE_31(31), SPARE_32(
32), SPARE_33(33), SPARE_34(34), SPARE_35(35), SPARE_36(36), SPARE_37(37), SPARE_38(38), SPARE_39(39), SPARE_40(
40), SPARE_41(41), SPARE_42(42), SPARE_43(43), SPARE_44(44), SPARE_45(45), SPARE_46(46), SPARE_47(47), SPARE_48(
48), SPARE_49(49), SPARE_50(50), SPARE_51(51), SPARE_52(52), SPARE_53(53), SPARE_54(54), SPARE_55(55), SPARE_56(
56), SPARE_57(57), SPARE_58(58), SPARE_59(59), SPARE_60(60), SPARE_61(61), SPARE_62(62), SPARE_63(63), SPARE_64(
64), SPARE_65(65), SPARE_66(66), SPARE_67(67), SPARE_68(68), SPARE_69(69), SPARE_70(70), SPARE_71(71), SPARE_72(
72), SPARE_73(73), SPARE_74(74), SPARE_75(75), SPARE_76(76), SPARE_77(77), SPARE_78(78), SPARE_79(79), SPARE_80(
80), SPARE_81(81), SPARE_82(82), SPARE_83(83), SPARE_84(84), SPARE_85(85), SPARE_86(86), SPARE_87(87), SPARE_88(
88), SPARE_89(89), SPARE_90(90), SPARE_91(91), SPARE_92(92), SPARE_93(93), SPARE_94(94), SPARE_95(95), SPARE_96(
96), SPARE_97(97), SPARE_98(98), SPARE_99(99), SPARE_100(100), SPARE_101(101), SPARE_102(102), SPARE_103(
103), SPARE_104(104), SPARE_105(105), SPARE_106(106), SPARE_107(107), SPARE_108(108), SPARE_109(109), SPARE_110(
110), SPARE_111(111), RESERVED_NATIONAL_112(112), RESERVED_NATIONAL_113(113), RESERVED_NATIONAL_114(114), RESERVED_NATIONAL_115(
115), RESERVED_NATIONAL_116(116), RESERVED_NATIONAL_117(117), RESERVED_NATIONAL_118(118), RESERVED_NATIONAL_119(
119), RESERVED_NATIONAL_120(120), RESERVED_NATIONAL_121(121), RESERVED_NATIONAL_122(122), RESERVED_NATIONAL_123(
123), RESERVED_NATIONAL_124(124), RESERVED_NATIONAL_125(125), RESERVED_NATIONAL_126(126), RESERVED(127);
private int value;
private NatureOfAddress(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public static NatureOfAddress valueOf(int v) throws IOException {
switch (v) {
case 0:
return UNKNOWN;
case 1:
return SUBSCRIBER;
case 2:
return RESERVED_NATIONAL_2;
case 3:
return NATIONAL;
case 4:
return INTERNATIONAL;
case 5:
return SPARE_5;
case 6:
return SPARE_6;
case 7:
return SPARE_7;
case 8:
return SPARE_8;
case 9:
return SPARE_9;
case 10:
return SPARE_10;
case 11:
return SPARE_11;
case 12:
return SPARE_12;
case 13:
return SPARE_13;
case 14:
return SPARE_14;
case 15:
return SPARE_15;
case 16:
return SPARE_16;
case 17:
return SPARE_17;
case 18:
return SPARE_18;
case 19:
return SPARE_19;
case 20:
return SPARE_20;
case 21:
return SPARE_21;
case 22:
return SPARE_22;
case 23:
return SPARE_23;
case 24:
return SPARE_24;
case 25:
return SPARE_25;
case 26:
return SPARE_26;
case 27:
return SPARE_27;
case 28:
return SPARE_28;
case 29:
return SPARE_29;
case 30:
return SPARE_30;
case 31:
return SPARE_31;
case 32:
return SPARE_32;
case 33:
return SPARE_33;
case 34:
return SPARE_34;
case 35:
return SPARE_35;
case 36:
return SPARE_36;
case 37:
return SPARE_37;
case 38:
return SPARE_38;
case 39:
return SPARE_39;
case 40:
return SPARE_40;
case 41:
return SPARE_41;
case 42:
return SPARE_42;
case 43:
return SPARE_43;
case 44:
return SPARE_44;
case 45:
return SPARE_45;
case 46:
return SPARE_46;
case 47:
return SPARE_47;
case 48:
return SPARE_48;
case 49:
return SPARE_49;
case 50:
return SPARE_50;
case 51:
return SPARE_51;
case 52:
return SPARE_52;
case 53:
return SPARE_53;
case 54:
return SPARE_54;
case 55:
return SPARE_55;
case 56:
return SPARE_56;
case 57:
return SPARE_57;
case 58:
return SPARE_58;
case 59:
return SPARE_59;
case 60:
return SPARE_60;
case 61:
return SPARE_61;
case 62:
return SPARE_62;
case 63:
return SPARE_63;
case 64:
return SPARE_64;
case 65:
return SPARE_65;
case 66:
return SPARE_66;
case 67:
return SPARE_67;
case 68:
return SPARE_68;
case 69:
return SPARE_69;
case 70:
return SPARE_70;
case 71:
return SPARE_71;
case 72:
return SPARE_72;
case 73:
return SPARE_73;
case 74:
return SPARE_74;
case 75:
return SPARE_75;
case 76:
return SPARE_76;
case 77:
return SPARE_77;
case 78:
return SPARE_78;
case 79:
return SPARE_79;
case 80:
return SPARE_80;
case 81:
return SPARE_81;
case 82:
return SPARE_82;
case 83:
return SPARE_83;
case 84:
return SPARE_84;
case 85:
return SPARE_85;
case 86:
return SPARE_86;
case 87:
return SPARE_87;
case 88:
return SPARE_88;
case 89:
return SPARE_89;
case 90:
return SPARE_90;
case 91:
return SPARE_91;
case 92:
return SPARE_92;
case 93:
return SPARE_93;
case 94:
return SPARE_94;
case 95:
return SPARE_95;
case 96:
return SPARE_96;
case 97:
return SPARE_97;
case 98:
return SPARE_98;
case 99:
return SPARE_99;
case 100:
return SPARE_100;
case 101:
return SPARE_101;
case 102:
return SPARE_102;
case 103:
return SPARE_103;
case 104:
return SPARE_104;
case 105:
return SPARE_105;
case 106:
return SPARE_106;
case 107:
return SPARE_107;
case 108:
return SPARE_108;
case 109:
return SPARE_109;
case 110:
return SPARE_110;
case 111:
return SPARE_111;
case 112:
return RESERVED_NATIONAL_112;
case 113:
return RESERVED_NATIONAL_113;
case 114:
return RESERVED_NATIONAL_114;
case 115:
return RESERVED_NATIONAL_115;
case 116:
return RESERVED_NATIONAL_116;
case 117:
return RESERVED_NATIONAL_117;
case 118:
return RESERVED_NATIONAL_118;
case 119:
return RESERVED_NATIONAL_119;
case 120:
return RESERVED_NATIONAL_120;
case 121:
return RESERVED_NATIONAL_121;
case 122:
return RESERVED_NATIONAL_122;
case 123:
return RESERVED_NATIONAL_123;
case 124:
return RESERVED_NATIONAL_124;
case 125:
return RESERVED_NATIONAL_125;
case 126:
return RESERVED_NATIONAL_126;
+ case 127:
+ return RESERVED;
default:
throw new IOException("Unrecognized Nature of Address. Must be between 0 to 127 and value is=" + v);
}
}
}
| true | true | public static NatureOfAddress valueOf(int v) throws IOException {
switch (v) {
case 0:
return UNKNOWN;
case 1:
return SUBSCRIBER;
case 2:
return RESERVED_NATIONAL_2;
case 3:
return NATIONAL;
case 4:
return INTERNATIONAL;
case 5:
return SPARE_5;
case 6:
return SPARE_6;
case 7:
return SPARE_7;
case 8:
return SPARE_8;
case 9:
return SPARE_9;
case 10:
return SPARE_10;
case 11:
return SPARE_11;
case 12:
return SPARE_12;
case 13:
return SPARE_13;
case 14:
return SPARE_14;
case 15:
return SPARE_15;
case 16:
return SPARE_16;
case 17:
return SPARE_17;
case 18:
return SPARE_18;
case 19:
return SPARE_19;
case 20:
return SPARE_20;
case 21:
return SPARE_21;
case 22:
return SPARE_22;
case 23:
return SPARE_23;
case 24:
return SPARE_24;
case 25:
return SPARE_25;
case 26:
return SPARE_26;
case 27:
return SPARE_27;
case 28:
return SPARE_28;
case 29:
return SPARE_29;
case 30:
return SPARE_30;
case 31:
return SPARE_31;
case 32:
return SPARE_32;
case 33:
return SPARE_33;
case 34:
return SPARE_34;
case 35:
return SPARE_35;
case 36:
return SPARE_36;
case 37:
return SPARE_37;
case 38:
return SPARE_38;
case 39:
return SPARE_39;
case 40:
return SPARE_40;
case 41:
return SPARE_41;
case 42:
return SPARE_42;
case 43:
return SPARE_43;
case 44:
return SPARE_44;
case 45:
return SPARE_45;
case 46:
return SPARE_46;
case 47:
return SPARE_47;
case 48:
return SPARE_48;
case 49:
return SPARE_49;
case 50:
return SPARE_50;
case 51:
return SPARE_51;
case 52:
return SPARE_52;
case 53:
return SPARE_53;
case 54:
return SPARE_54;
case 55:
return SPARE_55;
case 56:
return SPARE_56;
case 57:
return SPARE_57;
case 58:
return SPARE_58;
case 59:
return SPARE_59;
case 60:
return SPARE_60;
case 61:
return SPARE_61;
case 62:
return SPARE_62;
case 63:
return SPARE_63;
case 64:
return SPARE_64;
case 65:
return SPARE_65;
case 66:
return SPARE_66;
case 67:
return SPARE_67;
case 68:
return SPARE_68;
case 69:
return SPARE_69;
case 70:
return SPARE_70;
case 71:
return SPARE_71;
case 72:
return SPARE_72;
case 73:
return SPARE_73;
case 74:
return SPARE_74;
case 75:
return SPARE_75;
case 76:
return SPARE_76;
case 77:
return SPARE_77;
case 78:
return SPARE_78;
case 79:
return SPARE_79;
case 80:
return SPARE_80;
case 81:
return SPARE_81;
case 82:
return SPARE_82;
case 83:
return SPARE_83;
case 84:
return SPARE_84;
case 85:
return SPARE_85;
case 86:
return SPARE_86;
case 87:
return SPARE_87;
case 88:
return SPARE_88;
case 89:
return SPARE_89;
case 90:
return SPARE_90;
case 91:
return SPARE_91;
case 92:
return SPARE_92;
case 93:
return SPARE_93;
case 94:
return SPARE_94;
case 95:
return SPARE_95;
case 96:
return SPARE_96;
case 97:
return SPARE_97;
case 98:
return SPARE_98;
case 99:
return SPARE_99;
case 100:
return SPARE_100;
case 101:
return SPARE_101;
case 102:
return SPARE_102;
case 103:
return SPARE_103;
case 104:
return SPARE_104;
case 105:
return SPARE_105;
case 106:
return SPARE_106;
case 107:
return SPARE_107;
case 108:
return SPARE_108;
case 109:
return SPARE_109;
case 110:
return SPARE_110;
case 111:
return SPARE_111;
case 112:
return RESERVED_NATIONAL_112;
case 113:
return RESERVED_NATIONAL_113;
case 114:
return RESERVED_NATIONAL_114;
case 115:
return RESERVED_NATIONAL_115;
case 116:
return RESERVED_NATIONAL_116;
case 117:
return RESERVED_NATIONAL_117;
case 118:
return RESERVED_NATIONAL_118;
case 119:
return RESERVED_NATIONAL_119;
case 120:
return RESERVED_NATIONAL_120;
case 121:
return RESERVED_NATIONAL_121;
case 122:
return RESERVED_NATIONAL_122;
case 123:
return RESERVED_NATIONAL_123;
case 124:
return RESERVED_NATIONAL_124;
case 125:
return RESERVED_NATIONAL_125;
case 126:
return RESERVED_NATIONAL_126;
default:
throw new IOException("Unrecognized Nature of Address. Must be between 0 to 127 and value is=" + v);
}
}
| public static NatureOfAddress valueOf(int v) throws IOException {
switch (v) {
case 0:
return UNKNOWN;
case 1:
return SUBSCRIBER;
case 2:
return RESERVED_NATIONAL_2;
case 3:
return NATIONAL;
case 4:
return INTERNATIONAL;
case 5:
return SPARE_5;
case 6:
return SPARE_6;
case 7:
return SPARE_7;
case 8:
return SPARE_8;
case 9:
return SPARE_9;
case 10:
return SPARE_10;
case 11:
return SPARE_11;
case 12:
return SPARE_12;
case 13:
return SPARE_13;
case 14:
return SPARE_14;
case 15:
return SPARE_15;
case 16:
return SPARE_16;
case 17:
return SPARE_17;
case 18:
return SPARE_18;
case 19:
return SPARE_19;
case 20:
return SPARE_20;
case 21:
return SPARE_21;
case 22:
return SPARE_22;
case 23:
return SPARE_23;
case 24:
return SPARE_24;
case 25:
return SPARE_25;
case 26:
return SPARE_26;
case 27:
return SPARE_27;
case 28:
return SPARE_28;
case 29:
return SPARE_29;
case 30:
return SPARE_30;
case 31:
return SPARE_31;
case 32:
return SPARE_32;
case 33:
return SPARE_33;
case 34:
return SPARE_34;
case 35:
return SPARE_35;
case 36:
return SPARE_36;
case 37:
return SPARE_37;
case 38:
return SPARE_38;
case 39:
return SPARE_39;
case 40:
return SPARE_40;
case 41:
return SPARE_41;
case 42:
return SPARE_42;
case 43:
return SPARE_43;
case 44:
return SPARE_44;
case 45:
return SPARE_45;
case 46:
return SPARE_46;
case 47:
return SPARE_47;
case 48:
return SPARE_48;
case 49:
return SPARE_49;
case 50:
return SPARE_50;
case 51:
return SPARE_51;
case 52:
return SPARE_52;
case 53:
return SPARE_53;
case 54:
return SPARE_54;
case 55:
return SPARE_55;
case 56:
return SPARE_56;
case 57:
return SPARE_57;
case 58:
return SPARE_58;
case 59:
return SPARE_59;
case 60:
return SPARE_60;
case 61:
return SPARE_61;
case 62:
return SPARE_62;
case 63:
return SPARE_63;
case 64:
return SPARE_64;
case 65:
return SPARE_65;
case 66:
return SPARE_66;
case 67:
return SPARE_67;
case 68:
return SPARE_68;
case 69:
return SPARE_69;
case 70:
return SPARE_70;
case 71:
return SPARE_71;
case 72:
return SPARE_72;
case 73:
return SPARE_73;
case 74:
return SPARE_74;
case 75:
return SPARE_75;
case 76:
return SPARE_76;
case 77:
return SPARE_77;
case 78:
return SPARE_78;
case 79:
return SPARE_79;
case 80:
return SPARE_80;
case 81:
return SPARE_81;
case 82:
return SPARE_82;
case 83:
return SPARE_83;
case 84:
return SPARE_84;
case 85:
return SPARE_85;
case 86:
return SPARE_86;
case 87:
return SPARE_87;
case 88:
return SPARE_88;
case 89:
return SPARE_89;
case 90:
return SPARE_90;
case 91:
return SPARE_91;
case 92:
return SPARE_92;
case 93:
return SPARE_93;
case 94:
return SPARE_94;
case 95:
return SPARE_95;
case 96:
return SPARE_96;
case 97:
return SPARE_97;
case 98:
return SPARE_98;
case 99:
return SPARE_99;
case 100:
return SPARE_100;
case 101:
return SPARE_101;
case 102:
return SPARE_102;
case 103:
return SPARE_103;
case 104:
return SPARE_104;
case 105:
return SPARE_105;
case 106:
return SPARE_106;
case 107:
return SPARE_107;
case 108:
return SPARE_108;
case 109:
return SPARE_109;
case 110:
return SPARE_110;
case 111:
return SPARE_111;
case 112:
return RESERVED_NATIONAL_112;
case 113:
return RESERVED_NATIONAL_113;
case 114:
return RESERVED_NATIONAL_114;
case 115:
return RESERVED_NATIONAL_115;
case 116:
return RESERVED_NATIONAL_116;
case 117:
return RESERVED_NATIONAL_117;
case 118:
return RESERVED_NATIONAL_118;
case 119:
return RESERVED_NATIONAL_119;
case 120:
return RESERVED_NATIONAL_120;
case 121:
return RESERVED_NATIONAL_121;
case 122:
return RESERVED_NATIONAL_122;
case 123:
return RESERVED_NATIONAL_123;
case 124:
return RESERVED_NATIONAL_124;
case 125:
return RESERVED_NATIONAL_125;
case 126:
return RESERVED_NATIONAL_126;
case 127:
return RESERVED;
default:
throw new IOException("Unrecognized Nature of Address. Must be between 0 to 127 and value is=" + v);
}
}
|
diff --git a/bundles/model/org.openhab.model.core/src/main/java/org/openhab/model/core/internal/ModelRepositoryImpl.java b/bundles/model/org.openhab.model.core/src/main/java/org/openhab/model/core/internal/ModelRepositoryImpl.java
index 6e97d99a..238a3c42 100644
--- a/bundles/model/org.openhab.model.core/src/main/java/org/openhab/model/core/internal/ModelRepositoryImpl.java
+++ b/bundles/model/org.openhab.model.core/src/main/java/org/openhab/model/core/internal/ModelRepositoryImpl.java
@@ -1,157 +1,157 @@
/**
* openHAB, the open Home Automation Bus.
* Copyright (C) 2010, openHAB.org <[email protected]>
*
* See the contributors.txt file in the distribution for a
* full listing of individual contributors.
*
* 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>.
*
* Additional permission under GNU GPL version 3 section 7
*
* If you modify this Program, or any covered work, by linking or
* combining it with Eclipse (or a modified version of that library),
* containing parts covered by the terms of the Eclipse Public License
* (EPL), the licensors of this Program grant you additional permission
* to convey the resulting work.
*/
package org.openhab.model.core.internal;
import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.resource.XtextResourceSet;
import org.openhab.model.core.EventType;
import org.openhab.model.core.ModelRepository;
import org.openhab.model.core.ModelRepositoryChangeListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.Iterables;
public class ModelRepositoryImpl implements ModelRepository {
private static final Logger logger = LoggerFactory.getLogger(ModelRepositoryImpl.class);
private final ResourceSet resourceSet;
private final Set<ModelRepositoryChangeListener> listeners = new HashSet<ModelRepositoryChangeListener>();
public ModelRepositoryImpl() {
XtextResourceSet xtextResourceSet = new XtextResourceSet();
xtextResourceSet.addLoadOption(XtextResource.OPTION_RESOLVE_ALL, Boolean.TRUE);
this.resourceSet = xtextResourceSet;
}
@Override
public EObject getModel(String name) {
Resource resource = getResource(name);
if(resource!=null) {
if(resource.getContents().size()>0) {
return resource.getContents().get(0);
} else {
logger.warn("File '{}' cannot be parsed correctly!", name);
return null;
}
} else {
logger.warn("File '{}' can not be found in folder {}");
return null;
}
}
@Override
public void addOrRefreshModel(String name, InputStream inputStream) {
Resource resource = getResource(name);
if(resource==null) {
// seems to be a new file
resource = resourceSet.createResource(URI.createURI(name));
try {
resource.load(inputStream, Collections.EMPTY_MAP);
notifyListeners(name, EventType.ADDED);
} catch (IOException e) {
- logger.warn("File '{}' cannot be parsed correctly!", name, e);
+ logger.warn("File '" + name + "' cannot be parsed correctly!", e);
}
} else {
resource.unload();
try {
resource.load(inputStream, Collections.EMPTY_MAP);
} catch (IOException e) {
- logger.warn("File '{}' cannot be parsed correctly!", name, e);
+ logger.warn("File '" + name + "' cannot be parsed correctly!", e);
}
notifyListeners(name, EventType.MODIFIED);
}
}
@Override
public boolean removeModel(String name) {
Resource resource = getResource(name);
if(resource!=null) {
// do not physically delete it, but remove it from the resource set
resourceSet.getResources().remove(resource);
notifyListeners(name, EventType.REMOVED);
return true;
} else {
return false;
}
}
@Override
public Iterable<String> getAllModelNamesOfType(final String modelType) {
Iterable<Resource> matchingResources = Iterables.filter(resourceSet.getResources(), new Predicate<Resource>() {
public boolean apply(Resource input) {
if(input!=null) {
return input.getURI().fileExtension().equalsIgnoreCase(modelType);
} else {
return false;
}
}});
return Iterables.transform(matchingResources, new Function<Resource, String>() {
public String apply(Resource from) {
return from.getURI().path();
}});
}
@Override
public void addModelRepositoryChangeListener(
ModelRepositoryChangeListener listener) {
listeners.add(listener);
}
@Override
public void removeModelRepositoryChangeListener(
ModelRepositoryChangeListener listener) {
listeners.remove(listener);
}
private Resource getResource(String name) {
return resourceSet.getResource(URI.createURI(name), false);
}
private void notifyListeners(String name, EventType type) {
for(ModelRepositoryChangeListener listener : listeners) {
listener.modelChanged(name, type);
}
}
}
| false | true | public void addOrRefreshModel(String name, InputStream inputStream) {
Resource resource = getResource(name);
if(resource==null) {
// seems to be a new file
resource = resourceSet.createResource(URI.createURI(name));
try {
resource.load(inputStream, Collections.EMPTY_MAP);
notifyListeners(name, EventType.ADDED);
} catch (IOException e) {
logger.warn("File '{}' cannot be parsed correctly!", name, e);
}
} else {
resource.unload();
try {
resource.load(inputStream, Collections.EMPTY_MAP);
} catch (IOException e) {
logger.warn("File '{}' cannot be parsed correctly!", name, e);
}
notifyListeners(name, EventType.MODIFIED);
}
}
| public void addOrRefreshModel(String name, InputStream inputStream) {
Resource resource = getResource(name);
if(resource==null) {
// seems to be a new file
resource = resourceSet.createResource(URI.createURI(name));
try {
resource.load(inputStream, Collections.EMPTY_MAP);
notifyListeners(name, EventType.ADDED);
} catch (IOException e) {
logger.warn("File '" + name + "' cannot be parsed correctly!", e);
}
} else {
resource.unload();
try {
resource.load(inputStream, Collections.EMPTY_MAP);
} catch (IOException e) {
logger.warn("File '" + name + "' cannot be parsed correctly!", e);
}
notifyListeners(name, EventType.MODIFIED);
}
}
|
diff --git a/src/com/android/mms/transaction/MmsSystemEventReceiver.java b/src/com/android/mms/transaction/MmsSystemEventReceiver.java
index 9b78ea08..d89a31a4 100644
--- a/src/com/android/mms/transaction/MmsSystemEventReceiver.java
+++ b/src/com/android/mms/transaction/MmsSystemEventReceiver.java
@@ -1,96 +1,99 @@
/*
* Copyright (C) 2007-2008 Esmertec AG.
* Copyright (C) 2007-2008 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.mms.transaction;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.Telephony.Mms;
import android.util.Log;
import com.android.mms.LogTag;
import com.android.mms.MmsApp;
/**
* MmsSystemEventReceiver receives the
* {@link android.content.intent.ACTION_BOOT_COMPLETED},
* {@link com.android.internal.telephony.TelephonyIntents.ACTION_ANY_DATA_CONNECTION_STATE_CHANGED}
* and performs a series of operations which may include:
* <ul>
* <li>Show/hide the icon in notification area which is used to indicate
* whether there is new incoming message.</li>
* <li>Resend the MM's in the outbox.</li>
* </ul>
*/
public class MmsSystemEventReceiver extends BroadcastReceiver {
private static final String TAG = "MmsSystemEventReceiver";
private static ConnectivityManager mConnMgr = null;
public static void wakeUpService(Context context) {
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "wakeUpService: start transaction service ...");
}
context.startService(new Intent(context, TransactionService.class));
}
@Override
public void onReceive(Context context, Intent intent) {
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "Intent received: " + intent);
}
String action = intent.getAction();
if (action.equals(Mms.Intents.CONTENT_CHANGED_ACTION)) {
Uri changed = (Uri) intent.getParcelableExtra(Mms.Intents.DELETED_CONTENTS);
MmsApp.getApplication().getPduLoaderManager().removePdu(changed);
} else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
if (mConnMgr == null) {
mConnMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
}
NetworkInfo mmsNetworkInfo = mConnMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
+ if (mmsNetworkInfo == null) {
+ return;
+ }
boolean available = mmsNetworkInfo.isAvailable();
boolean isConnected = mmsNetworkInfo.isConnected();
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "TYPE_MOBILE_MMS available = " + available +
", isConnected = " + isConnected);
}
// Wake up transact service when MMS data is available and isn't connected.
if (available && !isConnected) {
wakeUpService(context);
}
} else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
// We should check whether there are unread incoming
// messages in the Inbox and then update the notification icon.
// Called on the UI thread so don't block.
MessagingNotification.nonBlockingUpdateNewMessageIndicator(
context, MessagingNotification.THREAD_NONE, false);
// Scan and send pending Mms once after boot completed since
// ACTION_ANY_DATA_CONNECTION_STATE_CHANGED wasn't registered in a whole life cycle
wakeUpService(context);
}
}
}
| true | true | public void onReceive(Context context, Intent intent) {
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "Intent received: " + intent);
}
String action = intent.getAction();
if (action.equals(Mms.Intents.CONTENT_CHANGED_ACTION)) {
Uri changed = (Uri) intent.getParcelableExtra(Mms.Intents.DELETED_CONTENTS);
MmsApp.getApplication().getPduLoaderManager().removePdu(changed);
} else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
if (mConnMgr == null) {
mConnMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
}
NetworkInfo mmsNetworkInfo = mConnMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
boolean available = mmsNetworkInfo.isAvailable();
boolean isConnected = mmsNetworkInfo.isConnected();
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "TYPE_MOBILE_MMS available = " + available +
", isConnected = " + isConnected);
}
// Wake up transact service when MMS data is available and isn't connected.
if (available && !isConnected) {
wakeUpService(context);
}
} else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
// We should check whether there are unread incoming
// messages in the Inbox and then update the notification icon.
// Called on the UI thread so don't block.
MessagingNotification.nonBlockingUpdateNewMessageIndicator(
context, MessagingNotification.THREAD_NONE, false);
// Scan and send pending Mms once after boot completed since
// ACTION_ANY_DATA_CONNECTION_STATE_CHANGED wasn't registered in a whole life cycle
wakeUpService(context);
}
}
| public void onReceive(Context context, Intent intent) {
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "Intent received: " + intent);
}
String action = intent.getAction();
if (action.equals(Mms.Intents.CONTENT_CHANGED_ACTION)) {
Uri changed = (Uri) intent.getParcelableExtra(Mms.Intents.DELETED_CONTENTS);
MmsApp.getApplication().getPduLoaderManager().removePdu(changed);
} else if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
if (mConnMgr == null) {
mConnMgr = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
}
NetworkInfo mmsNetworkInfo = mConnMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE_MMS);
if (mmsNetworkInfo == null) {
return;
}
boolean available = mmsNetworkInfo.isAvailable();
boolean isConnected = mmsNetworkInfo.isConnected();
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE)) {
Log.v(TAG, "TYPE_MOBILE_MMS available = " + available +
", isConnected = " + isConnected);
}
// Wake up transact service when MMS data is available and isn't connected.
if (available && !isConnected) {
wakeUpService(context);
}
} else if (action.equals(Intent.ACTION_BOOT_COMPLETED)) {
// We should check whether there are unread incoming
// messages in the Inbox and then update the notification icon.
// Called on the UI thread so don't block.
MessagingNotification.nonBlockingUpdateNewMessageIndicator(
context, MessagingNotification.THREAD_NONE, false);
// Scan and send pending Mms once after boot completed since
// ACTION_ANY_DATA_CONNECTION_STATE_CHANGED wasn't registered in a whole life cycle
wakeUpService(context);
}
}
|
diff --git a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/PersonAttributeEditor.java b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/PersonAttributeEditor.java
index c8684824b..ac81b57d2 100644
--- a/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/PersonAttributeEditor.java
+++ b/org.eclipse.mylyn.tasks.ui/src/org/eclipse/mylyn/internal/tasks/ui/editors/PersonAttributeEditor.java
@@ -1,142 +1,142 @@
/*******************************************************************************
* Copyright (c) 2004, 2008 Tasktop Technologies 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:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.tasks.ui.editors;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.mylyn.internal.provisional.commons.ui.CommonImages;
import org.eclipse.mylyn.tasks.core.IRepositoryPerson;
import org.eclipse.mylyn.tasks.core.data.TaskAttribute;
import org.eclipse.mylyn.tasks.core.data.TaskDataModel;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseTrackAdapter;
import org.eclipse.swt.events.MouseTrackListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.forms.events.HyperlinkAdapter;
import org.eclipse.ui.forms.events.HyperlinkEvent;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.ImageHyperlink;
/**
* @author Steffen Pingel
*/
public class PersonAttributeEditor extends TextAttributeEditor {
public PersonAttributeEditor(TaskDataModel manager, TaskAttribute taskAttribute) {
super(manager, taskAttribute);
}
@Override
public Text getText() {
return super.getText();
}
@Override
public void createControl(Composite parent, FormToolkit toolkit) {
String userName = getModel().getTaskRepository().getUserName();
if (isReadOnly() || userName == null || userName.length() == 0) {
super.createControl(parent, toolkit);
} else {
final Composite composite = new Composite(parent, SWT.NONE);
GridLayout parentLayout = new GridLayout(2, false);
parentLayout.marginHeight = 0;
parentLayout.marginWidth = 0;
parentLayout.horizontalSpacing = 0;
composite.setLayout(parentLayout);
composite.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
super.createControl(composite, toolkit);
getText().setData(FormToolkit.KEY_DRAW_BORDER, Boolean.FALSE);
GridDataFactory.fillDefaults().grab(true, false).applyTo(getText());
final ImageHyperlink selfLink = new ImageHyperlink(composite, SWT.NO_FOCUS);
selfLink.setToolTipText(Messages.PersonAttributeEditor_Insert_My_User_Id_Tooltip);
selfLink.setActiveImage(CommonImages.getImage(CommonImages.PERSON_ME_SMALL));
selfLink.setHoverImage(CommonImages.getImage(CommonImages.PERSON_ME_SMALL));
selfLink.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
String userName = getModel().getTaskRepository().getUserName();
if (userName != null && userName.length() > 0) {
getText().setText(userName);
setValue(userName);
}
}
});
GridDataFactory.fillDefaults().exclude(true).applyTo(selfLink);
MouseTrackListener mouseListener = new MouseTrackAdapter() {
int version = 0;
@Override
public void mouseEnter(MouseEvent e) {
((GridData) selfLink.getLayoutData()).exclude = false;
composite.layout();
- selfLink.setImage(CommonImages.getImage(CommonImages.PERSON_ME));
+ selfLink.setImage(CommonImages.getImage(CommonImages.PERSON_ME_SMALL));
selfLink.redraw();
version++;
}
@Override
public void mouseExit(MouseEvent e) {
final int lastVersion = version;
Display.getDefault().asyncExec(new Runnable() {
public void run() {
if (version != lastVersion || selfLink.isDisposed()) {
return;
}
selfLink.setImage(null);
selfLink.redraw();
((GridData) selfLink.getLayoutData()).exclude = true;
composite.layout();
}
});
}
};
getText().addMouseTrackListener(mouseListener);
selfLink.addMouseTrackListener(mouseListener);
toolkit.paintBordersFor(composite);
setControl(composite);
}
}
@Override
public String getValue() {
IRepositoryPerson repositoryPerson = getAttributeMapper().getRepositoryPerson(getTaskAttribute());
if (repositoryPerson != null) {
return (isReadOnly()) ? repositoryPerson.toString() : repositoryPerson.getPersonId();
}
return ""; //$NON-NLS-1$
}
@Override
public void setValue(String text) {
IRepositoryPerson person = getAttributeMapper().getTaskRepository().createPerson(text);
getAttributeMapper().setRepositoryPerson(getTaskAttribute(), person);
attributeChanged();
}
@Override
protected void decorateIncoming(Color color) {
if (getControl() != null) {
getControl().setBackground(color);
}
if (getText() != null && getText() != getControl()) {
getText().setBackground(color);
}
}
}
| true | true | public void createControl(Composite parent, FormToolkit toolkit) {
String userName = getModel().getTaskRepository().getUserName();
if (isReadOnly() || userName == null || userName.length() == 0) {
super.createControl(parent, toolkit);
} else {
final Composite composite = new Composite(parent, SWT.NONE);
GridLayout parentLayout = new GridLayout(2, false);
parentLayout.marginHeight = 0;
parentLayout.marginWidth = 0;
parentLayout.horizontalSpacing = 0;
composite.setLayout(parentLayout);
composite.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
super.createControl(composite, toolkit);
getText().setData(FormToolkit.KEY_DRAW_BORDER, Boolean.FALSE);
GridDataFactory.fillDefaults().grab(true, false).applyTo(getText());
final ImageHyperlink selfLink = new ImageHyperlink(composite, SWT.NO_FOCUS);
selfLink.setToolTipText(Messages.PersonAttributeEditor_Insert_My_User_Id_Tooltip);
selfLink.setActiveImage(CommonImages.getImage(CommonImages.PERSON_ME_SMALL));
selfLink.setHoverImage(CommonImages.getImage(CommonImages.PERSON_ME_SMALL));
selfLink.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
String userName = getModel().getTaskRepository().getUserName();
if (userName != null && userName.length() > 0) {
getText().setText(userName);
setValue(userName);
}
}
});
GridDataFactory.fillDefaults().exclude(true).applyTo(selfLink);
MouseTrackListener mouseListener = new MouseTrackAdapter() {
int version = 0;
@Override
public void mouseEnter(MouseEvent e) {
((GridData) selfLink.getLayoutData()).exclude = false;
composite.layout();
selfLink.setImage(CommonImages.getImage(CommonImages.PERSON_ME));
selfLink.redraw();
version++;
}
@Override
public void mouseExit(MouseEvent e) {
final int lastVersion = version;
Display.getDefault().asyncExec(new Runnable() {
public void run() {
if (version != lastVersion || selfLink.isDisposed()) {
return;
}
selfLink.setImage(null);
selfLink.redraw();
((GridData) selfLink.getLayoutData()).exclude = true;
composite.layout();
}
});
}
};
getText().addMouseTrackListener(mouseListener);
selfLink.addMouseTrackListener(mouseListener);
toolkit.paintBordersFor(composite);
setControl(composite);
}
}
| public void createControl(Composite parent, FormToolkit toolkit) {
String userName = getModel().getTaskRepository().getUserName();
if (isReadOnly() || userName == null || userName.length() == 0) {
super.createControl(parent, toolkit);
} else {
final Composite composite = new Composite(parent, SWT.NONE);
GridLayout parentLayout = new GridLayout(2, false);
parentLayout.marginHeight = 0;
parentLayout.marginWidth = 0;
parentLayout.horizontalSpacing = 0;
composite.setLayout(parentLayout);
composite.setData(FormToolkit.KEY_DRAW_BORDER, FormToolkit.TEXT_BORDER);
super.createControl(composite, toolkit);
getText().setData(FormToolkit.KEY_DRAW_BORDER, Boolean.FALSE);
GridDataFactory.fillDefaults().grab(true, false).applyTo(getText());
final ImageHyperlink selfLink = new ImageHyperlink(composite, SWT.NO_FOCUS);
selfLink.setToolTipText(Messages.PersonAttributeEditor_Insert_My_User_Id_Tooltip);
selfLink.setActiveImage(CommonImages.getImage(CommonImages.PERSON_ME_SMALL));
selfLink.setHoverImage(CommonImages.getImage(CommonImages.PERSON_ME_SMALL));
selfLink.addHyperlinkListener(new HyperlinkAdapter() {
@Override
public void linkActivated(HyperlinkEvent e) {
String userName = getModel().getTaskRepository().getUserName();
if (userName != null && userName.length() > 0) {
getText().setText(userName);
setValue(userName);
}
}
});
GridDataFactory.fillDefaults().exclude(true).applyTo(selfLink);
MouseTrackListener mouseListener = new MouseTrackAdapter() {
int version = 0;
@Override
public void mouseEnter(MouseEvent e) {
((GridData) selfLink.getLayoutData()).exclude = false;
composite.layout();
selfLink.setImage(CommonImages.getImage(CommonImages.PERSON_ME_SMALL));
selfLink.redraw();
version++;
}
@Override
public void mouseExit(MouseEvent e) {
final int lastVersion = version;
Display.getDefault().asyncExec(new Runnable() {
public void run() {
if (version != lastVersion || selfLink.isDisposed()) {
return;
}
selfLink.setImage(null);
selfLink.redraw();
((GridData) selfLink.getLayoutData()).exclude = true;
composite.layout();
}
});
}
};
getText().addMouseTrackListener(mouseListener);
selfLink.addMouseTrackListener(mouseListener);
toolkit.paintBordersFor(composite);
setControl(composite);
}
}
|
diff --git a/software/camod/src/gov/nih/nci/camod/webapp/action/ChangeAnimalModelStatePopulateAction.java b/software/camod/src/gov/nih/nci/camod/webapp/action/ChangeAnimalModelStatePopulateAction.java
index 81abf088..d2e18885 100755
--- a/software/camod/src/gov/nih/nci/camod/webapp/action/ChangeAnimalModelStatePopulateAction.java
+++ b/software/camod/src/gov/nih/nci/camod/webapp/action/ChangeAnimalModelStatePopulateAction.java
@@ -1,228 +1,230 @@
/**
* @author dgeorge
*
* $Id: ChangeAnimalModelStatePopulateAction.java,v 1.15 2007-09-12 19:36:40 pandyas Exp $
*
* $Log: not supported by cvs2svn $
* Revision 1.14 2007/09/12 19:09:21 pandyas
* Added if statement to check for model_id from GUI - this used to work
*
* Revision 1.13 2007/08/14 12:04:53 pandyas
* Working on model id display on search results screen
*
* Revision 1.12 2006/10/17 16:11:00 pandyas
* modified during development of caMOD 2.2 - various
*
* Revision 1.11 2006/08/17 18:06:57 pandyas
* Defect# 410: Externalize properties files - Code changes to get properties
*
* Revision 1.10 2005/11/28 13:48:37 georgeda
* Defect #192, handle back arrow for curation changes
*
* Revision 1.9 2005/10/24 13:28:17 georgeda
* Cleanup changes
*
* Revision 1.8 2005/09/22 15:17:36 georgeda
* More changes
*
* Revision 1.7 2005/09/19 14:21:47 georgeda
* Added interface for URL parameters
*
* Revision 1.6 2005/09/19 13:38:42 georgeda
* Cleaned up parameter passing
*
* Revision 1.5 2005/09/19 13:09:52 georgeda
* Added header
*
*
*/
package gov.nih.nci.camod.webapp.action;
import gov.nih.nci.camod.Constants;
import gov.nih.nci.camod.domain.AnimalModel;
import gov.nih.nci.camod.domain.Log;
import gov.nih.nci.camod.service.AnimalModelManager;
import gov.nih.nci.camod.service.impl.LogManagerSingleton;
import gov.nih.nci.camod.webapp.form.AnimalModelStateForm;
import gov.nih.nci.camod.webapp.util.NewDropdownUtil;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
public class ChangeAnimalModelStatePopulateAction extends BaseAction {
/**
* Change the state for the curation model
*/
public ActionForward execute(ActionMapping inMapping, ActionForm inForm, HttpServletRequest inRequest,
HttpServletResponse inResponse) throws Exception {
log.debug("Entering ChangeAnimalModelStatePopulateAction.execute");
String theForward = "next";
String theModelId = null;
AnimalModel theAnimalModel = null;
try {
// Get the attributes from the request
/* Grab the current modelID from the session */
theModelId = (String) inRequest.getSession().getAttribute(Constants.Parameters.MODELID);
log.debug("theModelId: " + theModelId);
String theEvent = inRequest.getParameter(Constants.Parameters.EVENT);
log.debug("theEvent: " + theEvent);
AnimalModelManager theAnimalModelManager = (AnimalModelManager) getBean("animalModelManager");
log.debug("here1: " );
if (theModelId != null){
theAnimalModel = theAnimalModelManager.get(theModelId);
} else {
theModelId = inRequest.getParameter("aModelID");
log.debug("theModelId from getParameter: " + theModelId);
theAnimalModel = theAnimalModelManager.get(theModelId);
}
log.debug("here2: " );
// Set up the form
AnimalModelStateForm theForm = (AnimalModelStateForm) inForm;
theForm.setEvent(theEvent);
theForm.setModelId(theModelId);
theForm.setModelDescriptor(theAnimalModel.getModelDescriptor());
log.debug("here3: " );
// Null out the list in case it had been already set
inRequest.getSession().setAttribute(Constants.Dropdowns.USERSFORROLEDROP, null);
log.debug("<ChangeAnimalModelStatePopulateAction> The model id: " + theModelId + " and event: " + theEvent);
inRequest.setAttribute("wiki_cs_help", "");
// Setting the action. This is used to customize the jsp display
if (theEvent.equals(Constants.Admin.Actions.ASSIGN_SCREENER)) {
inRequest.setAttribute("action", "Assigning Screener to ");
inRequest.setAttribute("wiki_cs_help", "1");
NewDropdownUtil.populateDropdown(inRequest, Constants.Dropdowns.USERSFORROLEDROP,
Constants.Admin.Roles.SCREENER);
} else if (theEvent.equals(Constants.Admin.Actions.ASSIGN_EDITOR)) {
inRequest.setAttribute("action", "Assigning Editor to ");
inRequest.setAttribute("wiki_cs_help", "2");
NewDropdownUtil.populateDropdown(inRequest, Constants.Dropdowns.USERSFORROLEDROP,
Constants.Admin.Roles.EDITOR);
} else if (theEvent.equals(Constants.Admin.Actions.NEED_MORE_INFO)) {
// Assign to the current person
Log theLog = LogManagerSingleton.instance().getCurrentByModel(theAnimalModel);
theForm.setAssignedTo(theLog.getSubmitter().getUsername());
inRequest.setAttribute("action", "Requesting more information for ");
} else if (theEvent.equals(Constants.Admin.Actions.SCREENER_REJECT)) {
// Assign to the coordinator
Properties camodProperties = new Properties();
String camodPropertiesFileName = null;
camodPropertiesFileName = System.getProperty("gov.nih.nci.camod.camodProperties");
try {
FileInputStream in = new FileInputStream(camodPropertiesFileName);
camodProperties.load(in);
}
catch (FileNotFoundException e) {
log.error("Caught exception finding file for properties: ", e);
e.printStackTrace();
} catch (IOException e) {
log.error("Caught exception finding file for properties: ", e);
e.printStackTrace();
}
String theCoordinator = camodProperties.getProperty("coordinator.username");
theForm.setAssignedTo(theCoordinator);
inRequest.setAttribute("action", "Rejecting ");
+ inRequest.setAttribute("wiki_cs_help", "3");
} else if (theEvent.equals(Constants.Admin.Actions.SCREENER_APPROVE) || theEvent.equals(Constants.Admin.Actions.EDITOR_APPROVE)) {
// Assign to the coordinator
Properties camodProperties = new Properties();
String camodPropertiesFileName = null;
camodPropertiesFileName = System.getProperty("gov.nih.nci.camod.camodProperties");
try {
FileInputStream in = new FileInputStream(camodPropertiesFileName);
camodProperties.load(in);
}
catch (FileNotFoundException e) {
log.error("Caught exception finding file for properties: ", e);
e.printStackTrace();
} catch (IOException e) {
log.error("Caught exception finding file for properties: ", e);
e.printStackTrace();
}
String theCoordinator = camodProperties.getProperty("coordinator.username");
theForm.setAssignedTo(theCoordinator);
inRequest.setAttribute("action", "Approving ");
+ inRequest.setAttribute("wiki_cs_help", "4");
} else if (theEvent.equals(Constants.Admin.Actions.INACTIVATE)) {
log.debug("<ChangeAnimalModelStatePopulateAction> Inside inactive loop - the event is: " + theEvent);
// Assign to the coordinator
Properties camodProperties = new Properties();
String camodPropertiesFileName = null;
camodPropertiesFileName = System.getProperty("gov.nih.nci.camod.camodProperties");
try {
FileInputStream in = new FileInputStream(camodPropertiesFileName);
camodProperties.load(in);
}
catch (FileNotFoundException e) {
log.error("Caught exception finding file for properties: ", e);
e.printStackTrace();
} catch (IOException e) {
log.error("Caught exception finding file for properties: ", e);
e.printStackTrace();
}
String theCoordinator = camodProperties.getProperty("coordinator.username");
theForm.setAssignedTo(theCoordinator);
log.debug("<ChangeAnimalModelStatePopulateAction> setting the coordinator to: " + theCoordinator);
inRequest.setAttribute("action", "Inactivating ");
}
else {
throw new IllegalArgumentException("Unknown event type: " + theEvent);
}
} catch (Exception e) {
log.error("Caught an exception populating the data: ", e);
// Encountered an error
ActionMessages theMsg = new ActionMessages();
theMsg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.admin.message"));
saveErrors(inRequest, theMsg);
theForward = "failure";
}
log.debug("Exiting ChangeAnimalModelStatePopulateAction.execute");
return inMapping.findForward(theForward);
}
}
| false | true | public ActionForward execute(ActionMapping inMapping, ActionForm inForm, HttpServletRequest inRequest,
HttpServletResponse inResponse) throws Exception {
log.debug("Entering ChangeAnimalModelStatePopulateAction.execute");
String theForward = "next";
String theModelId = null;
AnimalModel theAnimalModel = null;
try {
// Get the attributes from the request
/* Grab the current modelID from the session */
theModelId = (String) inRequest.getSession().getAttribute(Constants.Parameters.MODELID);
log.debug("theModelId: " + theModelId);
String theEvent = inRequest.getParameter(Constants.Parameters.EVENT);
log.debug("theEvent: " + theEvent);
AnimalModelManager theAnimalModelManager = (AnimalModelManager) getBean("animalModelManager");
log.debug("here1: " );
if (theModelId != null){
theAnimalModel = theAnimalModelManager.get(theModelId);
} else {
theModelId = inRequest.getParameter("aModelID");
log.debug("theModelId from getParameter: " + theModelId);
theAnimalModel = theAnimalModelManager.get(theModelId);
}
log.debug("here2: " );
// Set up the form
AnimalModelStateForm theForm = (AnimalModelStateForm) inForm;
theForm.setEvent(theEvent);
theForm.setModelId(theModelId);
theForm.setModelDescriptor(theAnimalModel.getModelDescriptor());
log.debug("here3: " );
// Null out the list in case it had been already set
inRequest.getSession().setAttribute(Constants.Dropdowns.USERSFORROLEDROP, null);
log.debug("<ChangeAnimalModelStatePopulateAction> The model id: " + theModelId + " and event: " + theEvent);
inRequest.setAttribute("wiki_cs_help", "");
// Setting the action. This is used to customize the jsp display
if (theEvent.equals(Constants.Admin.Actions.ASSIGN_SCREENER)) {
inRequest.setAttribute("action", "Assigning Screener to ");
inRequest.setAttribute("wiki_cs_help", "1");
NewDropdownUtil.populateDropdown(inRequest, Constants.Dropdowns.USERSFORROLEDROP,
Constants.Admin.Roles.SCREENER);
} else if (theEvent.equals(Constants.Admin.Actions.ASSIGN_EDITOR)) {
inRequest.setAttribute("action", "Assigning Editor to ");
inRequest.setAttribute("wiki_cs_help", "2");
NewDropdownUtil.populateDropdown(inRequest, Constants.Dropdowns.USERSFORROLEDROP,
Constants.Admin.Roles.EDITOR);
} else if (theEvent.equals(Constants.Admin.Actions.NEED_MORE_INFO)) {
// Assign to the current person
Log theLog = LogManagerSingleton.instance().getCurrentByModel(theAnimalModel);
theForm.setAssignedTo(theLog.getSubmitter().getUsername());
inRequest.setAttribute("action", "Requesting more information for ");
} else if (theEvent.equals(Constants.Admin.Actions.SCREENER_REJECT)) {
// Assign to the coordinator
Properties camodProperties = new Properties();
String camodPropertiesFileName = null;
camodPropertiesFileName = System.getProperty("gov.nih.nci.camod.camodProperties");
try {
FileInputStream in = new FileInputStream(camodPropertiesFileName);
camodProperties.load(in);
}
catch (FileNotFoundException e) {
log.error("Caught exception finding file for properties: ", e);
e.printStackTrace();
} catch (IOException e) {
log.error("Caught exception finding file for properties: ", e);
e.printStackTrace();
}
String theCoordinator = camodProperties.getProperty("coordinator.username");
theForm.setAssignedTo(theCoordinator);
inRequest.setAttribute("action", "Rejecting ");
} else if (theEvent.equals(Constants.Admin.Actions.SCREENER_APPROVE) || theEvent.equals(Constants.Admin.Actions.EDITOR_APPROVE)) {
// Assign to the coordinator
Properties camodProperties = new Properties();
String camodPropertiesFileName = null;
camodPropertiesFileName = System.getProperty("gov.nih.nci.camod.camodProperties");
try {
FileInputStream in = new FileInputStream(camodPropertiesFileName);
camodProperties.load(in);
}
catch (FileNotFoundException e) {
log.error("Caught exception finding file for properties: ", e);
e.printStackTrace();
} catch (IOException e) {
log.error("Caught exception finding file for properties: ", e);
e.printStackTrace();
}
String theCoordinator = camodProperties.getProperty("coordinator.username");
theForm.setAssignedTo(theCoordinator);
inRequest.setAttribute("action", "Approving ");
} else if (theEvent.equals(Constants.Admin.Actions.INACTIVATE)) {
log.debug("<ChangeAnimalModelStatePopulateAction> Inside inactive loop - the event is: " + theEvent);
// Assign to the coordinator
Properties camodProperties = new Properties();
String camodPropertiesFileName = null;
camodPropertiesFileName = System.getProperty("gov.nih.nci.camod.camodProperties");
try {
FileInputStream in = new FileInputStream(camodPropertiesFileName);
camodProperties.load(in);
}
catch (FileNotFoundException e) {
log.error("Caught exception finding file for properties: ", e);
e.printStackTrace();
} catch (IOException e) {
log.error("Caught exception finding file for properties: ", e);
e.printStackTrace();
}
String theCoordinator = camodProperties.getProperty("coordinator.username");
theForm.setAssignedTo(theCoordinator);
log.debug("<ChangeAnimalModelStatePopulateAction> setting the coordinator to: " + theCoordinator);
inRequest.setAttribute("action", "Inactivating ");
}
else {
throw new IllegalArgumentException("Unknown event type: " + theEvent);
}
} catch (Exception e) {
log.error("Caught an exception populating the data: ", e);
// Encountered an error
ActionMessages theMsg = new ActionMessages();
theMsg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.admin.message"));
saveErrors(inRequest, theMsg);
theForward = "failure";
}
log.debug("Exiting ChangeAnimalModelStatePopulateAction.execute");
return inMapping.findForward(theForward);
}
| public ActionForward execute(ActionMapping inMapping, ActionForm inForm, HttpServletRequest inRequest,
HttpServletResponse inResponse) throws Exception {
log.debug("Entering ChangeAnimalModelStatePopulateAction.execute");
String theForward = "next";
String theModelId = null;
AnimalModel theAnimalModel = null;
try {
// Get the attributes from the request
/* Grab the current modelID from the session */
theModelId = (String) inRequest.getSession().getAttribute(Constants.Parameters.MODELID);
log.debug("theModelId: " + theModelId);
String theEvent = inRequest.getParameter(Constants.Parameters.EVENT);
log.debug("theEvent: " + theEvent);
AnimalModelManager theAnimalModelManager = (AnimalModelManager) getBean("animalModelManager");
log.debug("here1: " );
if (theModelId != null){
theAnimalModel = theAnimalModelManager.get(theModelId);
} else {
theModelId = inRequest.getParameter("aModelID");
log.debug("theModelId from getParameter: " + theModelId);
theAnimalModel = theAnimalModelManager.get(theModelId);
}
log.debug("here2: " );
// Set up the form
AnimalModelStateForm theForm = (AnimalModelStateForm) inForm;
theForm.setEvent(theEvent);
theForm.setModelId(theModelId);
theForm.setModelDescriptor(theAnimalModel.getModelDescriptor());
log.debug("here3: " );
// Null out the list in case it had been already set
inRequest.getSession().setAttribute(Constants.Dropdowns.USERSFORROLEDROP, null);
log.debug("<ChangeAnimalModelStatePopulateAction> The model id: " + theModelId + " and event: " + theEvent);
inRequest.setAttribute("wiki_cs_help", "");
// Setting the action. This is used to customize the jsp display
if (theEvent.equals(Constants.Admin.Actions.ASSIGN_SCREENER)) {
inRequest.setAttribute("action", "Assigning Screener to ");
inRequest.setAttribute("wiki_cs_help", "1");
NewDropdownUtil.populateDropdown(inRequest, Constants.Dropdowns.USERSFORROLEDROP,
Constants.Admin.Roles.SCREENER);
} else if (theEvent.equals(Constants.Admin.Actions.ASSIGN_EDITOR)) {
inRequest.setAttribute("action", "Assigning Editor to ");
inRequest.setAttribute("wiki_cs_help", "2");
NewDropdownUtil.populateDropdown(inRequest, Constants.Dropdowns.USERSFORROLEDROP,
Constants.Admin.Roles.EDITOR);
} else if (theEvent.equals(Constants.Admin.Actions.NEED_MORE_INFO)) {
// Assign to the current person
Log theLog = LogManagerSingleton.instance().getCurrentByModel(theAnimalModel);
theForm.setAssignedTo(theLog.getSubmitter().getUsername());
inRequest.setAttribute("action", "Requesting more information for ");
} else if (theEvent.equals(Constants.Admin.Actions.SCREENER_REJECT)) {
// Assign to the coordinator
Properties camodProperties = new Properties();
String camodPropertiesFileName = null;
camodPropertiesFileName = System.getProperty("gov.nih.nci.camod.camodProperties");
try {
FileInputStream in = new FileInputStream(camodPropertiesFileName);
camodProperties.load(in);
}
catch (FileNotFoundException e) {
log.error("Caught exception finding file for properties: ", e);
e.printStackTrace();
} catch (IOException e) {
log.error("Caught exception finding file for properties: ", e);
e.printStackTrace();
}
String theCoordinator = camodProperties.getProperty("coordinator.username");
theForm.setAssignedTo(theCoordinator);
inRequest.setAttribute("action", "Rejecting ");
inRequest.setAttribute("wiki_cs_help", "3");
} else if (theEvent.equals(Constants.Admin.Actions.SCREENER_APPROVE) || theEvent.equals(Constants.Admin.Actions.EDITOR_APPROVE)) {
// Assign to the coordinator
Properties camodProperties = new Properties();
String camodPropertiesFileName = null;
camodPropertiesFileName = System.getProperty("gov.nih.nci.camod.camodProperties");
try {
FileInputStream in = new FileInputStream(camodPropertiesFileName);
camodProperties.load(in);
}
catch (FileNotFoundException e) {
log.error("Caught exception finding file for properties: ", e);
e.printStackTrace();
} catch (IOException e) {
log.error("Caught exception finding file for properties: ", e);
e.printStackTrace();
}
String theCoordinator = camodProperties.getProperty("coordinator.username");
theForm.setAssignedTo(theCoordinator);
inRequest.setAttribute("action", "Approving ");
inRequest.setAttribute("wiki_cs_help", "4");
} else if (theEvent.equals(Constants.Admin.Actions.INACTIVATE)) {
log.debug("<ChangeAnimalModelStatePopulateAction> Inside inactive loop - the event is: " + theEvent);
// Assign to the coordinator
Properties camodProperties = new Properties();
String camodPropertiesFileName = null;
camodPropertiesFileName = System.getProperty("gov.nih.nci.camod.camodProperties");
try {
FileInputStream in = new FileInputStream(camodPropertiesFileName);
camodProperties.load(in);
}
catch (FileNotFoundException e) {
log.error("Caught exception finding file for properties: ", e);
e.printStackTrace();
} catch (IOException e) {
log.error("Caught exception finding file for properties: ", e);
e.printStackTrace();
}
String theCoordinator = camodProperties.getProperty("coordinator.username");
theForm.setAssignedTo(theCoordinator);
log.debug("<ChangeAnimalModelStatePopulateAction> setting the coordinator to: " + theCoordinator);
inRequest.setAttribute("action", "Inactivating ");
}
else {
throw new IllegalArgumentException("Unknown event type: " + theEvent);
}
} catch (Exception e) {
log.error("Caught an exception populating the data: ", e);
// Encountered an error
ActionMessages theMsg = new ActionMessages();
theMsg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.admin.message"));
saveErrors(inRequest, theMsg);
theForward = "failure";
}
log.debug("Exiting ChangeAnimalModelStatePopulateAction.execute");
return inMapping.findForward(theForward);
}
|
diff --git a/src/clientmanager/InternetService.java b/src/clientmanager/InternetService.java
index a15e929..8632ba7 100644
--- a/src/clientmanager/InternetService.java
+++ b/src/clientmanager/InternetService.java
@@ -1,119 +1,121 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package clientmanager;
/**
*
* @author Scare
*/
public class InternetService extends Service{
public enum internetOptions {M20,M100};
private internetOptions internetSpeed;
private String idAccount;
private static float monthlyCostM20;
private static float monthlyCostM100;
/**
* @Instantiate objects PhoneService
*/
private InternetService(String id, float cost) {
super(cost);
this.idAccount = id;
}
/**
* @Instantiate objects PhoneService
*/
public InternetService(String id, internetOptions speed){
super(0);
if(speed.equals(internetOptions.M20)){
this.setMonthlyCost(monthlyCostM20);
this.idAccount = id;
+ internetSpeed=speed;
}
else if(speed.equals(internetOptions.M100)){
this.setMonthlyCost(monthlyCostM100);
this.idAccount = id;
+ internetSpeed=speed;
}
}
/**
* @return the monthlyCostM20
*/
public static float getMonthlyCostM20() {
return monthlyCostM20;
}
/**
* @param aMonthlyCostM20 the monthlyCostM20 to set
*/
public static void setMonthlyCostM20(float aMonthlyCostM20) {
monthlyCostM20 = aMonthlyCostM20;
}
/**
* @return the monthlyCostM100
*/
public static float getMonthlyCostM100() {
return monthlyCostM100;
}
/**
* @param aMonthlyCostM100 the monthlyCostM100 to set
*/
public static void setMonthlyCostM100(float aMonthlyCostM100) {
monthlyCostM100 = aMonthlyCostM100;
}
/**
* @return the tipo
*/
public internetOptions getinternetOptions() {
return getInternetSpeed();
}
/**
* @return the internetSpeed
*/
public internetOptions getInternetSpeed() {
return internetSpeed;
}
/**
* @param internetSpeed the internetSpeed to set
*/
public void setInternetSpeed(internetOptions internetSpeed) {
this.internetSpeed = internetSpeed;
}
/**
* @return the idAccount
*/
public String getIdAccount() {
return idAccount;
}
/**
* @param idAccount the idAccount to set
*/
public void setIdAccount(String idAccount) {
this.idAccount = idAccount;
}
/**
*
* @return total cost of this internet service
*/
@Override
public float calculateServicePayment() {
float totalCost;
//In future internet service can have more taxes or something like that
totalCost = this.getMonthlyCost();
return totalCost;
}
}
| false | true | public InternetService(String id, internetOptions speed){
super(0);
if(speed.equals(internetOptions.M20)){
this.setMonthlyCost(monthlyCostM20);
this.idAccount = id;
}
else if(speed.equals(internetOptions.M100)){
this.setMonthlyCost(monthlyCostM100);
this.idAccount = id;
}
}
| public InternetService(String id, internetOptions speed){
super(0);
if(speed.equals(internetOptions.M20)){
this.setMonthlyCost(monthlyCostM20);
this.idAccount = id;
internetSpeed=speed;
}
else if(speed.equals(internetOptions.M100)){
this.setMonthlyCost(monthlyCostM100);
this.idAccount = id;
internetSpeed=speed;
}
}
|
diff --git a/rultor-web/src/main/java/com/rultor/web/Lifespan.java b/rultor-web/src/main/java/com/rultor/web/Lifespan.java
index 3be468f6a..cc2f69384 100644
--- a/rultor-web/src/main/java/com/rultor/web/Lifespan.java
+++ b/rultor-web/src/main/java/com/rultor/web/Lifespan.java
@@ -1,173 +1,173 @@
/**
* Copyright (c) 2009-2013, rultor.com
* 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) Neither the name of the rultor.com nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.rultor.web;
import com.jcabi.aspects.Loggable;
import com.jcabi.aspects.ScheduleWithFixedDelay;
import com.jcabi.dynamo.Credentials;
import com.jcabi.dynamo.Region;
import com.jcabi.manifests.Manifests;
import com.rultor.aws.DynamoUsers;
import com.rultor.aws.S3Log;
import com.rultor.conveyer.SimpleConveyer;
import com.rultor.repo.ClasspathRepo;
import com.rultor.spi.Queue;
import com.rultor.spi.Repo;
import com.rultor.spi.Unit;
import com.rultor.spi.User;
import com.rultor.spi.Users;
import com.rultor.spi.Work;
import java.io.Closeable;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import lombok.EqualsAndHashCode;
import org.apache.commons.io.IOUtils;
/**
* Lifespan.
*
* @author Yegor Bugayenko ([email protected])
* @version $Id$
* @checkstyle ClassDataAbstractionCoupling (500 lines)
*/
@Loggable(Loggable.INFO)
public final class Lifespan implements ServletContextListener {
/**
* SimpleConveyer.
*/
private transient SimpleConveyer conveyer;
/**
* Quartz the works.
*/
private transient Quartz quartz;
/**
* Log.
*/
private transient S3Log log;
/**
* {@inheritDoc}
*/
@Override
public void contextInitialized(final ServletContextEvent event) {
try {
Manifests.append(event.getServletContext());
} catch (java.io.IOException ex) {
throw new IllegalStateException(ex);
}
- final String key = Manifests.read("Rultor-AwsKey");
- final String secret = Manifests.read("Rultor-AwsSecret");
+ final String key = Manifests.read("Rultor-S3Key");
+ final String secret = Manifests.read("Rultor-S3Secret");
final Region region = new Region.Prefixed(
new Region.Simple(new Credentials.Simple(key, secret)),
Manifests.read("Rultor-DynamoPrefix")
);
this.log = new S3Log(
key, secret,
Manifests.read("Rultor-S3Bucket")
);
final Users users = new DynamoUsers(region, this.log);
final Repo repo = new ClasspathRepo();
event.getServletContext().setAttribute(Users.class.getName(), users);
event.getServletContext().setAttribute(Repo.class.getName(), repo);
final Queue queue = new Queue.Memory();
this.quartz = new Lifespan.Quartz(users, queue);
this.conveyer = new SimpleConveyer(queue, repo, this.log);
this.conveyer.start();
}
/**
* {@inheritDoc}
*/
@Override
public void contextDestroyed(final ServletContextEvent event) {
IOUtils.closeQuietly(this.quartz);
IOUtils.closeQuietly(this.conveyer);
IOUtils.closeQuietly(this.log);
}
/**
* Every minute feeds all specs to queue.
*/
@Loggable(Loggable.INFO)
@ScheduleWithFixedDelay(delay = 1, unit = TimeUnit.MINUTES)
@EqualsAndHashCode(of = { "users", "queue" })
@SuppressWarnings("PMD.DoNotUseThreads")
private static final class Quartz implements Runnable, Closeable {
/**
* Users.
*/
private final transient Users users;
/**
* Queue.
*/
private final transient Queue queue;
/**
* Public ctor.
* @param usr Users
* @param que Queue
*/
protected Quartz(final Users usr, final Queue que) {
this.users = usr;
this.queue = que;
}
/**
* {@inheritDoc}
*/
@Override
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
public void run() {
for (User user : this.users.everybody()) {
for (Map.Entry<String, Unit> entry : user.units().entrySet()) {
this.queue.push(
new Work.Simple(
user.urn(),
entry.getKey(),
entry.getValue().spec()
)
);
}
}
}
/**
* {@inheritDoc}
*/
@Override
public void close() throws IOException {
// nothing to do
}
}
}
| true | true | public void contextInitialized(final ServletContextEvent event) {
try {
Manifests.append(event.getServletContext());
} catch (java.io.IOException ex) {
throw new IllegalStateException(ex);
}
final String key = Manifests.read("Rultor-AwsKey");
final String secret = Manifests.read("Rultor-AwsSecret");
final Region region = new Region.Prefixed(
new Region.Simple(new Credentials.Simple(key, secret)),
Manifests.read("Rultor-DynamoPrefix")
);
this.log = new S3Log(
key, secret,
Manifests.read("Rultor-S3Bucket")
);
final Users users = new DynamoUsers(region, this.log);
final Repo repo = new ClasspathRepo();
event.getServletContext().setAttribute(Users.class.getName(), users);
event.getServletContext().setAttribute(Repo.class.getName(), repo);
final Queue queue = new Queue.Memory();
this.quartz = new Lifespan.Quartz(users, queue);
this.conveyer = new SimpleConveyer(queue, repo, this.log);
this.conveyer.start();
}
| public void contextInitialized(final ServletContextEvent event) {
try {
Manifests.append(event.getServletContext());
} catch (java.io.IOException ex) {
throw new IllegalStateException(ex);
}
final String key = Manifests.read("Rultor-S3Key");
final String secret = Manifests.read("Rultor-S3Secret");
final Region region = new Region.Prefixed(
new Region.Simple(new Credentials.Simple(key, secret)),
Manifests.read("Rultor-DynamoPrefix")
);
this.log = new S3Log(
key, secret,
Manifests.read("Rultor-S3Bucket")
);
final Users users = new DynamoUsers(region, this.log);
final Repo repo = new ClasspathRepo();
event.getServletContext().setAttribute(Users.class.getName(), users);
event.getServletContext().setAttribute(Repo.class.getName(), repo);
final Queue queue = new Queue.Memory();
this.quartz = new Lifespan.Quartz(users, queue);
this.conveyer = new SimpleConveyer(queue, repo, this.log);
this.conveyer.start();
}
|
diff --git a/src/aws/apps/underthehood/Main.java b/src/aws/apps/underthehood/Main.java
index 85621c6..af5a933 100644
--- a/src/aws/apps/underthehood/Main.java
+++ b/src/aws/apps/underthehood/Main.java
@@ -1,531 +1,531 @@
/*******************************************************************************
* Copyright 2010 Alexandros Schillings
*
* 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 aws.apps.underthehood;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.TableLayout;
import android.widget.TableLayout.LayoutParams;
import android.widget.TableRow;
import android.widget.TextView;
import aws.apps.underthehood.adapters.ViewPagerAdapter;
import aws.apps.underthehood.container.SavedData;
import aws.apps.underthehood.ui.GuiCreation;
import aws.apps.underthehood.util.ExecTerminal;
import aws.apps.underthehood.util.ExecuteThread;
import aws.apps.underthehood.util.UsefulBits;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.viewpagerindicator.TabPageIndicator;
public class Main extends SherlockActivity {
private static final int DIALOG_EXECUTING = 1;
final String TAG = this.getClass().getName();
private ViewPagerAdapter mAdapter;
private ViewPager mViewPager;
private TabPageIndicator mIndicator;
private String mTimeDate="";
private UsefulBits uB;
private TableLayout tableIpconfig;
private TableLayout tableIpRoute;
private TableLayout tablePs;
private TableLayout tableOther;
private TableLayout tableNetstat;
private TableLayout tableProc;
private TableLayout tableDeviceInfo;
private TableLayout tableSysProp;
private TextView lblRootStatus;
private TextView lblTimeDate;
private TextView lblDevice;
private boolean device_rooted = false;
private float mDataTextSize = 0;
private GuiCreation gui;
private ExecuteThread executeThread;
private ProgressDialog executeDialog;
private Bundle threadBundle;
final Handler handler = new Handler() {
@SuppressWarnings({ "unchecked", "deprecation", })
public void handleMessage(Message msg) {
final LayoutParams lp = new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ArrayList<String> l = new ArrayList<String>();
switch(msg.what){
case ExecuteThread.WORK_COMPLETED:
Log.d(TAG, "^ Worker Thread: WORK_COMPLETED");
l = (ArrayList<String>) msg.getData().getSerializable(ExecuteThread.MSG_OTHER);
listToTable(l, tableOther, lp);
l = (ArrayList<String>) msg.getData().getSerializable(ExecuteThread.MSG_IP_ROUTE);
listToTable(l, tableIpRoute, lp);
l = (ArrayList<String>) msg.getData().getSerializable(ExecuteThread.MSG_IPCONFIG);
listToTable(l, tableIpconfig, lp);
l = (ArrayList<String>) msg.getData().getSerializable(ExecuteThread.MSG_NETSTAT);
listToTable(l, tableNetstat, lp);
l = (ArrayList<String>) msg.getData().getSerializable(ExecuteThread.MSG_PS);
listToTable(l, tablePs, lp);
l = (ArrayList<String>) msg.getData().getSerializable(ExecuteThread.MSG_PROC);
listToTable(l, tableProc, lp);
l = (ArrayList<String>) msg.getData().getSerializable(ExecuteThread.MSG_SYSPROP);
listToTable(l, tableSysProp, lp);
executeThread.setState(ExecuteThread.STATE_DONE);
removeDialog(DIALOG_EXECUTING);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
case ExecuteThread.WORK_INTERUPTED:
executeThread.setState(ExecuteThread.STATE_DONE);
removeDialog(DIALOG_EXECUTING);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
break;
}
}
};
private void changeFontSize(TableLayout t, float fontSize){
for (int i=0; i <= t.getChildCount()-1; i++){
TableRow row = (TableRow) t.getChildAt(i);
for (int j=0; j <= row.getChildCount()-1; j++){
View v = row.getChildAt(j);
try {
if(v.getClass() == Class.forName("android.widget.TextView")){
TextView tv = (TextView) v;
if ( i % 2 == 0 ) {
}else {
tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, fontSize);
}
}
} catch (Exception e) {
Log.e(TAG, "^ changeFontSize: ");
}
}
}
}
private boolean checkIfSu(){
String res = "";
ExecTerminal et = new ExecTerminal();
res = et.execSu("su && echo 1");
if (res.trim().equals("1")){
Log.d(TAG, "^ Device can do SU");
return true;
}
Log.d(TAG, "^ Device can't do SU");
return false;
}
/** Clears the table and field contents */
public void clearInfo() {
tableIpconfig.removeAllViews();
tableIpRoute.removeAllViews();
tableNetstat.removeAllViews();
tableProc.removeAllViews();
tableOther.removeAllViews();
tablePs.removeAllViews();
tableSysProp.removeAllViews();
lblRootStatus.setText("");
lblTimeDate.setText("");
}
public void fontSizeDecrease(){
mDataTextSize = mDataTextSize - 2f;
if (mDataTextSize < getResources().getDimension(R.dimen.min_font_size)){
mDataTextSize = getResources().getDimension(R.dimen.min_font_size);
}
changeFontSize(tableIpconfig, mDataTextSize);
changeFontSize(tableIpRoute, mDataTextSize);
changeFontSize(tableNetstat, mDataTextSize);
changeFontSize(tableProc, mDataTextSize);
changeFontSize(tableOther, mDataTextSize);
changeFontSize(tablePs, mDataTextSize);
changeFontSize(tableSysProp, mDataTextSize);
}
public void fontSizeIncrease(){
mDataTextSize = mDataTextSize + 2f;
if (mDataTextSize > getResources().getDimension(R.dimen.max_font_size)){
mDataTextSize = getResources().getDimension(R.dimen.max_font_size);
}
changeFontSize(tableIpconfig, mDataTextSize);
changeFontSize(tableIpRoute, mDataTextSize);
changeFontSize(tableNetstat, mDataTextSize);
changeFontSize(tableProc, mDataTextSize);
changeFontSize(tableOther, mDataTextSize);
changeFontSize(tablePs, mDataTextSize);
changeFontSize(tableSysProp, mDataTextSize);
}
private void listToTable(List<String> l, TableLayout t, LayoutParams lp){
String chr;
String seperator = getString(R.string.seperator_identifier);
try{
if (l.size() == 0){
return;
}
for (int i=0; i < l.size();i++){
chr = l.get(i).substring(0, 1);
if ( chr.equals("#") || chr.equals("$") || chr.equals(">")) {
t.addView(gui.createTitleRow(l.get(i)),lp);
} else if (chr.equals(seperator)){
t.addView(gui.createSeperatorRow(l.get(i)),lp);
}else {
t.addView(gui.createDataRow(l.get(i)),lp);
}
}
} catch (Exception e){
Log.e(TAG, "^ listToTable() Exception: " + e.getMessage());
}
}
// Sets screen rotation as fixed to current rotation setting
private void mLockScreenRotation(){
// Stop the screen orientation changing during an event
switch (this.getResources().getConfiguration().orientation)
{
case Configuration.ORIENTATION_PORTRAIT:
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
break;
case Configuration.ORIENTATION_LANDSCAPE:
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
break;
}
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "^ Intent Started");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
uB = new UsefulBits(this);
//setup GUI
gui = new GuiCreation(this);
lblRootStatus= (TextView) findViewById(R.id.tvRootStatus);
lblTimeDate = (TextView) findViewById(R.id.tvTime);
lblDevice = (TextView) findViewById(R.id.tvDevice);
setupTabs();
populateInfo();
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_EXECUTING:
executeDialog = new ProgressDialog(this);
executeDialog.setMessage(getString(R.string.dialogue_text_please_wait));
executeThread = new ExecuteThread(handler, this, threadBundle);
executeThread.start();
return executeDialog;
default:
return null;
}
}
/** Creates the menu items */
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
private String collectDataForExport(){
StringBuffer sb = new StringBuffer();
sb.append(getString(R.string.text_under_the_hood) + " @ " + mTimeDate +"\n\n");
sb.append("---------------------------------\n\n");
sb.append(uB.tableToString(tableDeviceInfo));
sb.append(getString(R.string.label_ipconfig_info) + "\n");
sb.append(uB.tableToString(tableIpconfig));
sb.append(getString(R.string.label_ip_route_info) + "\n");
sb.append(uB.tableToString(tableIpRoute));
sb.append(getString(R.string.label_proc_info) + "\n");
sb.append(uB.tableToString(tableProc));
sb.append(getString(R.string.label_netlist_info) + "\n");
sb.append(uB.tableToString(tableNetstat));
sb.append(getString(R.string.label_ps_info) + "\n");
sb.append(uB.tableToString(tablePs));
sb.append(getString(R.string.label_sys_prop) + "\n");
sb.append(uB.tableToString(tableSysProp));
sb.append(getString(R.string.label_other_info) + "\n");
sb.append(uB.tableToString(tableOther));
sb.append("\n\n---------------------------------");
return sb.toString().trim();
}
/** Handles item selections */
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if(R.id.menu_about == id){
uB.showAboutDialogue();
return true;
}
else if(R.id.menu_share == id ){
uB.shareResults(
getString(R.string.text_under_the_hood) + " @ " + mTimeDate,
collectDataForExport());
return true;
}
else if(R.id.menu_to_sd == id){
try {
File folder = Environment.getExternalStorageDirectory();
String filename = "deviceinfo_" + mTimeDate + ".txt";
String contents = collectDataForExport();
uB.saveToFile(filename, folder, contents);
} catch (Exception e) {
Log.e(TAG, "^ " + e.getMessage());
}
}
// else if(R.id.menu_increase_font_size == id ){
// fontSizeIncrease();
// return true;
// }
// else if(R.id.menu_decrease_font_size == id ){
// fontSizeDecrease();
// return true;
// }
else if(R.id.menu_refresh == id ){
refreshInfo();
return true;
}
return false;
}
@Override
public Object onRetainNonConfigurationInstance() {
Log.d(TAG, "^ onRetainNonConfigurationInstance()");
final SavedData saved = new SavedData();
saved.populateOther(tableOther);
saved.populateNetlist(tableNetstat);
saved.populatePs(tablePs);
saved.populateRoute(tableProc);
saved.populateIp(tableIpRoute);
saved.populateIpConfig(tableIpconfig);
saved.populateSysProp(tableSysProp);
saved.setAreWeRooted(device_rooted);
saved.setDateTime(mTimeDate);
return saved;
}
/** Retrieves and displays info */
@SuppressWarnings("deprecation")
private void populateInfo(){
//HashMap<Integer, Boolean> actionMap) {
final Object data = getLastNonConfigurationInstance();
LayoutParams lp = new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
if (data == null) { // We need to do everything from scratch!
mTimeDate = uB.formatDateTime("yyyy-MM-dd-HHmmssZ", new Date());
lblTimeDate.setText(mTimeDate);
device_rooted = checkIfSu();
mDataTextSize = getResources().getDimension(R.dimen.terminal_data_font);
//showSelectionDialogue();
executeCommands();
} else {
final SavedData saved = (SavedData) data;
mTimeDate = saved.getDateTime();
device_rooted = saved.getAreWeRooted();
lblTimeDate.setText(mTimeDate);
mDataTextSize = saved.getTextSize();
listToTable(saved.gettIpConfig(), tableIpconfig, lp);
listToTable(saved.gettIp(),tableIpRoute, lp);
listToTable(saved.gettRoute(),tableProc, lp);
listToTable(saved.gettDf(),tableOther, lp);
listToTable(saved.gettPs(),tablePs, lp);
listToTable(saved.gettNetlist(),tableNetstat, lp);
- listToTable(saved.gettPs(), tableSysProp, lp);
+ listToTable(saved.gettSysProp(), tableSysProp, lp);
}
if(device_rooted){
device_rooted = true;
lblRootStatus.setText(getString(R.string.root_status_ok));
} else {
lblRootStatus.setText(getString(R.string.root_status_not_ok));
}
lblDevice.setText(Build.PRODUCT + " " + Build.DEVICE);
//String res = Build.HOST+ " " + Build.ID+ " " + Build.MODEL+ " " + Build.PRODUCT+ " " + Build.TAGS+ " " + Build.TIME+ " " + Build.TYPE+ " " + Build.USER;
}
/** Convenience function combining clearInfo and getInfo */
public void refreshInfo() {
clearInfo();
//showSelectionDialogue();
executeCommands();
}
/////////////////////////////////////////////
private void setupTabs(){
mAdapter = new ViewPagerAdapter();
mViewPager = (ViewPager) findViewById(R.id.pager);
mIndicator = (TabPageIndicator) findViewById(R.id.indicator);
tableDeviceInfo= (TableLayout) findViewById(R.id.main_table_device_info);
View v;
v = gui.getScrollableTable();
tableIpconfig = (TableLayout) v.findViewById(R.id.table);
mAdapter.addView(v, "netcfg / ipconfig");
v = gui.getScrollableTable();
tableIpRoute = (TableLayout) v.findViewById(R.id.table);
mAdapter.addView(v, "ip");
v = gui.getScrollableTable();
tableNetstat = (TableLayout) v.findViewById(R.id.table);
mAdapter.addView(v, "netstat");
v = gui.getScrollableTable();
tableProc = (TableLayout) v.findViewById(R.id.table);
mAdapter.addView(v, "proc");
v = gui.getScrollableTable();
tablePs = (TableLayout) v.findViewById(R.id.table);
mAdapter.addView(v, "ps");
v = gui.getScrollableTable();
tableSysProp = (TableLayout) v.findViewById(R.id.table);
mAdapter.addView(v, "prop");
v = gui.getScrollableTable();
tableOther = (TableLayout) v.findViewById(R.id.table);
mAdapter.addView(v, "other");
mViewPager.setAdapter(mAdapter);
mIndicator.setViewPager(mViewPager);
}
@SuppressWarnings("deprecation")
private void executeCommands(){
final CharSequence[] cb_items = getResources().getTextArray(R.array.shell_commands);
final Hashtable<CharSequence, Boolean> action_table = new Hashtable<CharSequence, Boolean>();
boolean[] cb_item_state = new boolean[cb_items.length];
Arrays.sort(cb_items, 0, cb_items.length);
for (int i=0;i < cb_items.length; i ++ ){
cb_item_state[i] = true;
action_table.put(cb_items[i], true);
}
threadBundle = new Bundle();
threadBundle.putSerializable("actions", action_table);
mLockScreenRotation();
showDialog(DIALOG_EXECUTING);
}
// private void showSelectionDialogue(){
// final CharSequence[] cb_items = getResources().getTextArray(R.array.shell_commands);
// final Hashtable<CharSequence, Boolean> action_table = new Hashtable<CharSequence, Boolean>();
//
// boolean[] cb_item_state = new boolean[cb_items.length];
//
// Arrays.sort(cb_items, 0, cb_items.length);
// for (int i=0;i < cb_items.length; i ++ ){
// cb_item_state[i] = true;
// action_table.put(cb_items[i], cb_item_state[i]);
// }
//
// AlertDialog.Builder builder = new AlertDialog.Builder(this);
// builder.setTitle(getString(R.string.dialogue_title_select_commands));
// builder.setMultiChoiceItems(cb_items, cb_item_state, new DialogInterface.OnMultiChoiceClickListener() {
//
// @Override
// public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// /* Used has clicked a check box */
//
// action_table.put(cb_items[which], isChecked);
//
// }}).setPositiveButton(getString(R.string.ok), new
// DialogInterface.OnClickListener() {
// @SuppressWarnings("deprecation")
// public void onClick(DialogInterface dialog, int whichButton) { /* User clicked Yes so do some stuff */
// threadBundle = new Bundle();
// threadBundle.putSerializable("actions", action_table);
// mLockScreenRotation();
// showDialog(DIALOG_EXECUTING);
// }
// })
// .setNegativeButton(getString(R.string.cancel), new
// DialogInterface.OnClickListener() {
// public void onClick(DialogInterface dialog, int whichButton) { /* User clicked No so do some stuff */
// }
// }) ;
// AlertDialog alert = builder.create();
// alert.show();
// }
}
| true | true | private void populateInfo(){
//HashMap<Integer, Boolean> actionMap) {
final Object data = getLastNonConfigurationInstance();
LayoutParams lp = new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
if (data == null) { // We need to do everything from scratch!
mTimeDate = uB.formatDateTime("yyyy-MM-dd-HHmmssZ", new Date());
lblTimeDate.setText(mTimeDate);
device_rooted = checkIfSu();
mDataTextSize = getResources().getDimension(R.dimen.terminal_data_font);
//showSelectionDialogue();
executeCommands();
} else {
final SavedData saved = (SavedData) data;
mTimeDate = saved.getDateTime();
device_rooted = saved.getAreWeRooted();
lblTimeDate.setText(mTimeDate);
mDataTextSize = saved.getTextSize();
listToTable(saved.gettIpConfig(), tableIpconfig, lp);
listToTable(saved.gettIp(),tableIpRoute, lp);
listToTable(saved.gettRoute(),tableProc, lp);
listToTable(saved.gettDf(),tableOther, lp);
listToTable(saved.gettPs(),tablePs, lp);
listToTable(saved.gettNetlist(),tableNetstat, lp);
listToTable(saved.gettPs(), tableSysProp, lp);
}
if(device_rooted){
device_rooted = true;
lblRootStatus.setText(getString(R.string.root_status_ok));
} else {
lblRootStatus.setText(getString(R.string.root_status_not_ok));
}
lblDevice.setText(Build.PRODUCT + " " + Build.DEVICE);
//String res = Build.HOST+ " " + Build.ID+ " " + Build.MODEL+ " " + Build.PRODUCT+ " " + Build.TAGS+ " " + Build.TIME+ " " + Build.TYPE+ " " + Build.USER;
}
| private void populateInfo(){
//HashMap<Integer, Boolean> actionMap) {
final Object data = getLastNonConfigurationInstance();
LayoutParams lp = new TableLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
if (data == null) { // We need to do everything from scratch!
mTimeDate = uB.formatDateTime("yyyy-MM-dd-HHmmssZ", new Date());
lblTimeDate.setText(mTimeDate);
device_rooted = checkIfSu();
mDataTextSize = getResources().getDimension(R.dimen.terminal_data_font);
//showSelectionDialogue();
executeCommands();
} else {
final SavedData saved = (SavedData) data;
mTimeDate = saved.getDateTime();
device_rooted = saved.getAreWeRooted();
lblTimeDate.setText(mTimeDate);
mDataTextSize = saved.getTextSize();
listToTable(saved.gettIpConfig(), tableIpconfig, lp);
listToTable(saved.gettIp(),tableIpRoute, lp);
listToTable(saved.gettRoute(),tableProc, lp);
listToTable(saved.gettDf(),tableOther, lp);
listToTable(saved.gettPs(),tablePs, lp);
listToTable(saved.gettNetlist(),tableNetstat, lp);
listToTable(saved.gettSysProp(), tableSysProp, lp);
}
if(device_rooted){
device_rooted = true;
lblRootStatus.setText(getString(R.string.root_status_ok));
} else {
lblRootStatus.setText(getString(R.string.root_status_not_ok));
}
lblDevice.setText(Build.PRODUCT + " " + Build.DEVICE);
//String res = Build.HOST+ " " + Build.ID+ " " + Build.MODEL+ " " + Build.PRODUCT+ " " + Build.TAGS+ " " + Build.TIME+ " " + Build.TYPE+ " " + Build.USER;
}
|
diff --git a/Osm2GpsMid/src/de/ueller/osmToGpsMid/MyMath.java b/Osm2GpsMid/src/de/ueller/osmToGpsMid/MyMath.java
index 47391e23..43d92734 100644
--- a/Osm2GpsMid/src/de/ueller/osmToGpsMid/MyMath.java
+++ b/Osm2GpsMid/src/de/ueller/osmToGpsMid/MyMath.java
@@ -1,331 +1,331 @@
/**
* This file is part of OSM2GpsMid
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* Copyright (C) 2007 Harald Mueller
* Copyright (C) 2007 Kai Krueger
*
*/
package de.ueller.osmToGpsMid;
import de.ueller.osmToGpsMid.model.Node;
/**
* Provides some constants and functions for sphere calculations.
* @author Harald Mueller
*/
public class MyMath {
/**
* Average earth radius of the WGS84 geoid in meters.
* The old value was 6378159.81 = circumference of the earth in meters / 2 pi.
*/
public static final double PLANET_RADIUS = 6371000.8d;
/**
* This constant is used as fixed point multiplier to convert
* latitude / longitude from radians to fixpoint representation.
* With this multiplier, one should get a resolution of 1 m at the equator.
*
* This constant has to be in synchrony with the value in GpsMid.
*/
public static final double FIXPT_MULT = PLANET_RADIUS;
public static final float FEET_TO_METER = 0.3048f;
public static final float CIRCUMMAX = 40075004f;
public static final float CIRCUMMAX_PI = (float)(40075004.0 / (Math.PI * 2));
final public static transient double HALF_PI=Math.PI/2d;
public static float degToRad(double deg) {
return (float) (deg * (Math.PI / 180.0d));
}
/**
* Calculate spherical arc distance between two points.
* <p>
* Computes arc distance `c' on the sphere. equation (5-3a). (0
* <= c <= PI)
* <p>
*
* @param phi1 latitude in radians of start point
* @param lambda0 longitude in radians of start point
* @param phi latitude in radians of end point
* @param lambda longitude in radians of end point
* @return arc distance `c' in meters
*
*/
// final public static float spherical_distance(float phi1, float lambda0,
// float phi, float lambda) {
// float pdiff = (float) Math.sin(((phi - phi1) / 2f));
// float ldiff = (float) Math.sin((lambda - lambda0) / 2f);
// float rval = (float) Math.sqrt((pdiff * pdiff) + (float) Math.cos(phi1)
// * (float) Math.cos(phi) * (ldiff * ldiff));
//
// return 2.0f * (float) Math.asin(rval);
// }
final public static double spherical_distance(double lat1, double lon1,
double lat2, double lon2) {
double c = Math.acos(Math.sin(lat1)*Math.sin(lat2) +
Math.cos(lat1)*Math.cos(lat2) *
Math.cos(lon2-lon1));
return PLANET_RADIUS * c;
}
/** TODO: Explain: What is a haversine distance?
*
* @param lat1
* @param lon1
* @param lat2
* @param lon2
* @return
*/
final public static double haversine_distance(double lat1, double lon1,
double lat2, double lon2) {
double latSin = Math.sin((lat2 - lat1) / 2d);
double longSin = Math.sin((lon2 - lon1) / 2d);
double a = (latSin * latSin) +
(Math.cos(lat1) * Math.cos(lat2) * longSin * longSin);
double c = 2d * Math.atan2(Math.sqrt(a), Math.sqrt(1d - a));
return PLANET_RADIUS * c;
}
final private static double bearing_int(double lat1, double lon1,
double lat2, double lon2) {
double dLon = lon2 - lon1;
double y = Math.sin(dLon) * Math.cos(lat2);
double x = Math.cos(lat1) * Math.sin(lat2) -
Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
return Math.atan2(y, x);
}
// public final static long dist(Node from,Node to){
// float c=spherical_distance(
// (float)Math.toRadians(from.lat),
// (float)Math.toRadians(from.lon),
// (float)Math.toRadians(to.lat),
// (float)Math.toRadians(to.lon));
// return (long)(c*CIRCUMMAX_PI);
// }
public final static long dist(Node from,Node to){
return (long)( spherical_distance(
Math.toRadians(from.lat),
Math.toRadians(from.lon),
Math.toRadians(to.lat),
Math.toRadians(to.lon)));
}
public final static long dist(Node from,Node to,double factor) {
return (long)( factor * spherical_distance(
Math.toRadians(from.lat),
Math.toRadians(from.lon),
Math.toRadians(to.lat),
Math.toRadians(to.lon)));
}
/**
* calculate the start bearing in 1/2 degree so result 90 indicates 180 degree.
* @param from
* @param to
* @return
*/
public final static byte bearing_start(Node from, Node to) {
double b = bearing_int(
Math.toRadians(from.lat),
Math.toRadians(from.lon),
Math.toRadians(to.lat),
Math.toRadians(to.lon));
return (byte) Math.round(Math.toDegrees(b)/2);
}
public final static byte inverseBearing(byte bearing) {
int invBearing = bearing + 90;
if (invBearing > 90) {
invBearing -=180;
}
return (byte) invBearing;
}
/** Calculates X, Y and Z coordinates from latitude and longitude
*
* @param n Node with latitude and longitude in degrees
* @return Array containing X, Y and Z in this order
*/
public final static double [] latlon2XYZ(Node n) {
double lat = Math.toRadians(n.lat);
double lon = Math.toRadians(n.lon);
double [] res = new double[3];
res[0] = PLANET_RADIUS * Math.cos(lat) * Math.cos(lon);
res[1] = PLANET_RADIUS * Math.cos(lat) * Math.sin(lon);
res[2] = PLANET_RADIUS * Math.sin(lat);
return res;
}
/**
* calculate the destination point if you travel from n with initial bearing and dist in meters
* @param n startpoint
* @param bearing initial direction (great circle) in degree
* @param dist distance in meters
* @return the final destination
*/
public final static Node moveBearingDist(Node n,double bearing, double dist ){
double lat1 = Math.toRadians(n.lat);
double lon1 = Math.toRadians(n.lon);
bearing= Math.toRadians(bearing);
double cosDist = Math.cos(dist/PLANET_RADIUS);
double sinLat1 = Math.sin(lat1);
double sinDist = Math.sin(dist/PLANET_RADIUS);
double lat2 = Math.asin( sinLat1*cosDist + Math.cos(lat1)*sinDist*Math.cos(bearing) );
double lon2 = lon1 + Math.atan2(Math.sin(bearing)*sinDist*Math.cos(lat1),cosDist-sinLat1*Math.sin(lat2));
return new Node((float)Math.toDegrees(lat2),(float)Math.toDegrees(lon2),-1);
}
/**
* Calculates the great circle distance between two nodes.
* @param lat1 Latitude of first point in radians
* @param lon1 Longitude of first point in radians
* @param lat2 Latitude of second point in radians
* @param lon2 Longitude of second point in radians
* @return Angular distance in radians
*/
private static double calcDistance(double lat1, double lon1, double lat2, double lon2) {
// Taken from http://williams.best.vwh.net/avform.htm
double p1 = Math.sin((lat1 - lat2) / 2);
double p2 = Math.sin((lon1 - lon2) / 2);
double d = 2 * Math.asin(Math.sqrt(p1 * p1
+ Math.cos(lat1) * Math.cos(lat2) * p2 * p2));
return d;
}
/**
* Calculates the great circle distance and course between two nodes.
* @param lat1 Latitude of first point in radians
* @param lon1 Longitude of first point in radians
* @param lat2 Latitude of second point in radians
* @param lon2 Longitude of second point in radians
* @return double array, with the distance in meters at [0]
* and the course in radians at [1]
*/
private static double[] calcDistanceAndCourse(double lat1, double lon1, double lat2,
double lon2) {
double fDist = calcDistance(lat1, lon1, lat2, lon2);
double fCourse;
// Also taken from http://williams.best.vwh.net/avform.htm
// The original formula checks for (cos(lat1) < double.MIN_VALUE) but I think
// it's worth to save a cosine.
if (lat1 > (HALF_PI - 0.0001)) {
// At the north pole, all points are south.
fCourse = Math.PI;
} else if (lat1 < -(HALF_PI - 0.0001)) {
// And at the south pole, all points are north.
fCourse = 0;
} else {
double tc = Math.acos(((Math.sin(lat2) -
Math.sin(lat1) * Math.cos(fDist)) / (Math.sin(fDist) * Math.cos(lat1))));
// The original formula has sin(lon2 - lon1) but that's if western
// longitudes are positive (mentioned at the beginning of the page).
if (Math.sin(lon1 - lon2) < 0) {
fCourse = tc;
} else {
fCourse = Math.PI*2 - tc;
}
}
fDist *= PLANET_RADIUS;
double[] result = new double[2];
result[0] = fDist;
result[1] = fCourse;
return result;
}
/**
* Calculates the great circle distance and course between two nodes.
* @param n1 start point
* @param n2 end point
* @return double array, with the distance in meters at [0]
* and the course in degrees at [1]
*/
public static double[] calcDistanceAndCourse(Node n1,Node n2) {
double ret[]=calcDistanceAndCourse(Math.toRadians(n1.lat), Math.toRadians(n1.lon), Math.toRadians(n2.lat), Math.toRadians(n2.lon));
ret[1]=Math.toDegrees(ret[1]);
return ret;
}
/**
* Returns the point of intersection of two paths defined by point and bearing
*
* see http://williams.best.vwh.net/avform.htm#Intersection
*
* @param {LatLon} p1: First point
* @param {Number} brng1: Initial bearing from first point
* @param {LatLon} p2: Second point
* @param {Number} brng2: Initial bearing from second point
* @returns {LatLon} Destination point (null if no unique intersection defined)
*/
public static Node intersection(Node p1, double b1g, Node p2, double b2g) {
double lat1 = Math.toRadians(p1.lat), lon1 = Math.toRadians(p1.lon);
double lat2 = Math.toRadians(p2.lat), lon2 = Math.toRadians(p2.lon);
double b1 = Math.toRadians(b1g), b2 = Math.toRadians(b2g);
double dLat = lat2-lat1, dLon = lon2-lon1;
double dist12=calcDistance(lat1, lon1, lat2, lon2);
// double dist12 = 2*Math.asin( Math.sqrt( Math.sin(dLat/2)*Math.sin(dLat/2) +
// Math.cos(lat1)*Math.cos(lat2)*Math.sin(dLon/2)*Math.sin(dLon/2) ) );
// if (dist12-dist12T > 0.0001d){
// System.out.println("not the same");
// }
if (dist12 == 0) return null;
// initial/final bearings between points
double brngA = Math.acos( ( Math.sin(lat2) - Math.sin(lat1)*Math.cos(dist12) ) /
( Math.sin(dist12)*Math.cos(lat1) ) );
if (Double.isNaN(brngA)) brngA = 0; // protect against rounding
double brngB = Math.acos( ( Math.sin(lat1) - Math.sin(lat2)*Math.cos(dist12) ) /
( Math.sin(dist12)*Math.cos(lat2) ) );
double brng12;
double brng21;
if (Math.sin(lon2-lon1) > 0) {
brng12 = brngA;
brng21 = 2*Math.PI - brngB;
} else {
brng12 = 2*Math.PI - brngA;
brng21 = brngB;
}
double alpha1 = (b1 - brng12 + Math.PI) % (2*Math.PI) - Math.PI; // angle 2-1-3
double alpha2 = (brng21 - b2 + Math.PI) % (2*Math.PI) - Math.PI; // angle 1-2-3
if (Math.sin(alpha1)==0 && Math.sin(alpha2)==0) return null; // infinite intersections
if (Math.sin(alpha1)*Math.sin(alpha2) < 0) return null; // ambiguous intersection
//alpha1 = Math.abs(alpha1);
//alpha2 = Math.abs(alpha2);
// ... Ed Williams takes abs of alpha1/alpha2, but seems to break calculation?
double alpha3 = Math.acos( -Math.cos(alpha1)*Math.cos(alpha2) +
Math.sin(alpha1)*Math.sin(alpha2)*Math.cos(dist12) );
double dist13 = Math.atan2( Math.sin(dist12)*Math.sin(alpha1)*Math.sin(alpha2),
Math.cos(alpha2)+Math.cos(alpha1)*Math.cos(alpha3) );
double lat3 = Math.asin( Math.sin(lat1)*Math.cos(dist13) +
Math.cos(lat1)*Math.sin(dist13)*Math.cos(b1) );
double dLon13 = Math.atan2( Math.sin(b1)*Math.sin(dist13)*Math.cos(lat1),
Math.cos(dist13)-Math.sin(lat1)*Math.sin(lat3) );
double lon3 = lon1+dLon13;
- lon3 = (lon3+Math.PI) % (2*Math.PI) - Math.PI; // normalise to -180..180�
+ lon3 = (lon3+Math.PI) % (2*Math.PI) - Math.PI; // normalize to -180..180 degrees
return new Node((float)Math.toDegrees(lat3), (float)Math.toDegrees(lon3),-1);
}
}
| true | true | public static Node intersection(Node p1, double b1g, Node p2, double b2g) {
double lat1 = Math.toRadians(p1.lat), lon1 = Math.toRadians(p1.lon);
double lat2 = Math.toRadians(p2.lat), lon2 = Math.toRadians(p2.lon);
double b1 = Math.toRadians(b1g), b2 = Math.toRadians(b2g);
double dLat = lat2-lat1, dLon = lon2-lon1;
double dist12=calcDistance(lat1, lon1, lat2, lon2);
// double dist12 = 2*Math.asin( Math.sqrt( Math.sin(dLat/2)*Math.sin(dLat/2) +
// Math.cos(lat1)*Math.cos(lat2)*Math.sin(dLon/2)*Math.sin(dLon/2) ) );
// if (dist12-dist12T > 0.0001d){
// System.out.println("not the same");
// }
if (dist12 == 0) return null;
// initial/final bearings between points
double brngA = Math.acos( ( Math.sin(lat2) - Math.sin(lat1)*Math.cos(dist12) ) /
( Math.sin(dist12)*Math.cos(lat1) ) );
if (Double.isNaN(brngA)) brngA = 0; // protect against rounding
double brngB = Math.acos( ( Math.sin(lat1) - Math.sin(lat2)*Math.cos(dist12) ) /
( Math.sin(dist12)*Math.cos(lat2) ) );
double brng12;
double brng21;
if (Math.sin(lon2-lon1) > 0) {
brng12 = brngA;
brng21 = 2*Math.PI - brngB;
} else {
brng12 = 2*Math.PI - brngA;
brng21 = brngB;
}
double alpha1 = (b1 - brng12 + Math.PI) % (2*Math.PI) - Math.PI; // angle 2-1-3
double alpha2 = (brng21 - b2 + Math.PI) % (2*Math.PI) - Math.PI; // angle 1-2-3
if (Math.sin(alpha1)==0 && Math.sin(alpha2)==0) return null; // infinite intersections
if (Math.sin(alpha1)*Math.sin(alpha2) < 0) return null; // ambiguous intersection
//alpha1 = Math.abs(alpha1);
//alpha2 = Math.abs(alpha2);
// ... Ed Williams takes abs of alpha1/alpha2, but seems to break calculation?
double alpha3 = Math.acos( -Math.cos(alpha1)*Math.cos(alpha2) +
Math.sin(alpha1)*Math.sin(alpha2)*Math.cos(dist12) );
double dist13 = Math.atan2( Math.sin(dist12)*Math.sin(alpha1)*Math.sin(alpha2),
Math.cos(alpha2)+Math.cos(alpha1)*Math.cos(alpha3) );
double lat3 = Math.asin( Math.sin(lat1)*Math.cos(dist13) +
Math.cos(lat1)*Math.sin(dist13)*Math.cos(b1) );
double dLon13 = Math.atan2( Math.sin(b1)*Math.sin(dist13)*Math.cos(lat1),
Math.cos(dist13)-Math.sin(lat1)*Math.sin(lat3) );
double lon3 = lon1+dLon13;
lon3 = (lon3+Math.PI) % (2*Math.PI) - Math.PI; // normalise to -180..180�
return new Node((float)Math.toDegrees(lat3), (float)Math.toDegrees(lon3),-1);
}
| public static Node intersection(Node p1, double b1g, Node p2, double b2g) {
double lat1 = Math.toRadians(p1.lat), lon1 = Math.toRadians(p1.lon);
double lat2 = Math.toRadians(p2.lat), lon2 = Math.toRadians(p2.lon);
double b1 = Math.toRadians(b1g), b2 = Math.toRadians(b2g);
double dLat = lat2-lat1, dLon = lon2-lon1;
double dist12=calcDistance(lat1, lon1, lat2, lon2);
// double dist12 = 2*Math.asin( Math.sqrt( Math.sin(dLat/2)*Math.sin(dLat/2) +
// Math.cos(lat1)*Math.cos(lat2)*Math.sin(dLon/2)*Math.sin(dLon/2) ) );
// if (dist12-dist12T > 0.0001d){
// System.out.println("not the same");
// }
if (dist12 == 0) return null;
// initial/final bearings between points
double brngA = Math.acos( ( Math.sin(lat2) - Math.sin(lat1)*Math.cos(dist12) ) /
( Math.sin(dist12)*Math.cos(lat1) ) );
if (Double.isNaN(brngA)) brngA = 0; // protect against rounding
double brngB = Math.acos( ( Math.sin(lat1) - Math.sin(lat2)*Math.cos(dist12) ) /
( Math.sin(dist12)*Math.cos(lat2) ) );
double brng12;
double brng21;
if (Math.sin(lon2-lon1) > 0) {
brng12 = brngA;
brng21 = 2*Math.PI - brngB;
} else {
brng12 = 2*Math.PI - brngA;
brng21 = brngB;
}
double alpha1 = (b1 - brng12 + Math.PI) % (2*Math.PI) - Math.PI; // angle 2-1-3
double alpha2 = (brng21 - b2 + Math.PI) % (2*Math.PI) - Math.PI; // angle 1-2-3
if (Math.sin(alpha1)==0 && Math.sin(alpha2)==0) return null; // infinite intersections
if (Math.sin(alpha1)*Math.sin(alpha2) < 0) return null; // ambiguous intersection
//alpha1 = Math.abs(alpha1);
//alpha2 = Math.abs(alpha2);
// ... Ed Williams takes abs of alpha1/alpha2, but seems to break calculation?
double alpha3 = Math.acos( -Math.cos(alpha1)*Math.cos(alpha2) +
Math.sin(alpha1)*Math.sin(alpha2)*Math.cos(dist12) );
double dist13 = Math.atan2( Math.sin(dist12)*Math.sin(alpha1)*Math.sin(alpha2),
Math.cos(alpha2)+Math.cos(alpha1)*Math.cos(alpha3) );
double lat3 = Math.asin( Math.sin(lat1)*Math.cos(dist13) +
Math.cos(lat1)*Math.sin(dist13)*Math.cos(b1) );
double dLon13 = Math.atan2( Math.sin(b1)*Math.sin(dist13)*Math.cos(lat1),
Math.cos(dist13)-Math.sin(lat1)*Math.sin(lat3) );
double lon3 = lon1+dLon13;
lon3 = (lon3+Math.PI) % (2*Math.PI) - Math.PI; // normalize to -180..180 degrees
return new Node((float)Math.toDegrees(lat3), (float)Math.toDegrees(lon3),-1);
}
|
diff --git a/src/pxchat/util/Config.java b/src/pxchat/util/Config.java
index 6ea0232..35673de 100644
--- a/src/pxchat/util/Config.java
+++ b/src/pxchat/util/Config.java
@@ -1,353 +1,353 @@
package pxchat.util;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Vector;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.ErrorHandler;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
/**
* This static class contains the client configuration. It provides a mapping of
* keys to values and a list of connection profiles. The configuration file can
* be loaded by calling {@link #init(String)} with a proper file name. By
* calling {@link #save()}, the current configuration state is saved to the file
* this class was initialized with.
*
* @author Markus Döllinger
* @author Markus Holtermann
*/
public final class Config {
/**
* The config file.
*/
private static File file = null;
/**
* A key value mapping.
*/
private static HashMap<String, String> config = new HashMap<String, String>();
/**
* A list of profiles.
*/
private static Vector<Profile> profiles = new Vector<Config.Profile>();
/**
* Private default constructor.
*/
private Config() {
}
/**
* Saves the config the the file it was loaded from.
*/
public static void save() {
try {
DocumentBuilder b = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document doc = b.newDocument();
Node nClient = doc.createElement("client");
doc.appendChild(nClient);
Node nConfig = doc.createElement("config");
nClient.appendChild(nConfig);
// save key value mapping
for (String key : config.keySet()) {
Element setting = doc.createElement("setting");
setting.setAttribute("key", key);
setting.setAttribute("value", config.get(key));
nConfig.appendChild(setting);
}
Node nProfiles = doc.createElement("profiles");
nClient.appendChild(nProfiles);
// save profiles
for (Profile prof : profiles) {
Element profile = doc.createElement("profile");
profile.setAttribute("name", prof.name);
profile.setAttribute("host", prof.host);
profile.setAttribute("port", prof.port);
profile.setAttribute("username", prof.userName);
profile.setAttribute("password", prof.password);
nProfiles.appendChild(profile);
}
// save document to file
FileOutputStream fos = new FileOutputStream(file);
OutputFormat of = new OutputFormat("XML", "UTF-8", true);
of.setIndent(4);
of.setLineWidth(0);
of.setLineSeparator("\r\n");
of.setDoctype(null, "../xml/client.dtd");
XMLSerializer serializer = new XMLSerializer(fos, of);
serializer.asDOMSerializer();
serializer.serialize(doc.getDocumentElement());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Returns the value associated with the key.
*
* @param key The key
* @return The associated value
*/
public static String get(String key) {
return config.get(key);
}
/**
* Puts a new key value pair into the mapping. If the key is already
* available, its value is replaced.
*
* @param key The key
* @param value The associated value
*/
public static void put(String key, String value) {
config.put(key, value);
}
/**
* Returns an array of profiles.
*
* @return The profile array
*/
public static Profile[] getProfiles() {
return profiles.toArray(new Profile[profiles.size()]);
}
/**
* Returns the default profile. The default profile is the profile with the
* name specified in the key value mapping with the key defaultProfile.
*
* @return The default profile
*/
public static Profile getDefaultProfile() {
for (Profile prof : profiles) {
if (prof.equals(config.get("defaultProfile")))
return prof;
}
return null;
}
/**
* Adds a profile the the list of profiles.
*
* @param profile The new profile.
*/
public static void addProfile(Profile profile) {
profiles.add(profile);
}
/**
* This class represents a connection profile.
*
* @author Markus Döllinger
*/
public static class Profile {
private String name;
private String host;
private String port;
private String userName;
private String password;
/**
* Constructs a new profile with the specified values.
*
* @param name The name of the profile
* @param host The host
* @param port The port
* @param userName The user name
* @param password The password
*/
public Profile(String name, String host, String port, String userName, String password) {
this.name = name;
this.host = host;
this.port = port;
this.userName = userName;
this.password = password;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
public String toString() {
return name == null ? "null" : name;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (obj instanceof String)
return name.equals(obj);
if (obj instanceof Profile) {
Profile that = (Profile) obj;
return this.name.equals(that.name) && this.host.equals(that.host) &&
this.port.equals(that.port) && this.userName.equals(that.userName) &&
this.password.equals(that.password);
}
return false;
}
/**
* @return the host
*/
public String getHost() {
return host;
}
/**
* @param host the host to set
*/
public void setHost(String host) {
this.host = host;
}
/**
* @return the port
*/
public String getPort() {
return port;
}
/**
* @param port the port to set
*/
public void setPort(String port) {
this.port = port;
}
/**
* @return the userName
*/
public String getUserName() {
return userName;
}
/**
* @param userName the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
}
/**
* Loads the client config from the specified file.
*
* @param fileName The config file
*/
public static void init(String fileName) {
config.clear();
profiles.clear();
config.put("defaultProfile", "default");
- config.put("masterServer","http://localhost/servers.php?&action=list");
+ config.put("masterServer","http://localhost/servers.php?&action=list");
file = new File(fileName);
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new ErrorHandler() {
@Override
public void error(SAXParseException e) throws SAXException {
throw e;
}
@Override
public void fatalError(SAXParseException e) throws SAXException {
System.out.println("Fatal error validating the config file:");
e.printStackTrace();
System.exit(0);
}
@Override
public void warning(SAXParseException e) throws SAXException {
System.out.println("Warning validating the config file:");
e.printStackTrace();
}
});
Document document = builder.parse(file);
Node node = document.getDocumentElement();
Node configNode = XMLUtil.getChildByName(node, "config");
NodeList listConfig = configNode.getChildNodes();
if (listConfig != null) {
for (int i = 0; i < listConfig.getLength(); i++) {
if (listConfig.item(i).getNodeName().equals("setting")) {
config.put(XMLUtil.getAttributeValue(listConfig.item(i), "key"), XMLUtil
.getAttributeValue(listConfig.item(i), "value"));
}
}
}
Node profilesNode = XMLUtil.getChildByName(node, "profiles");
NodeList listProfiles = profilesNode.getChildNodes();
if (listProfiles != null) {
for (int i = 0; i < listProfiles.getLength(); i++) {
if (listProfiles.item(i).getNodeName().equals("profile")) {
String host = XMLUtil.getAttributeValue(listProfiles.item(i), "host");
String port = XMLUtil.getAttributeValue(listProfiles.item(i), "port");
String userName = XMLUtil.getAttributeValue(listProfiles.item(i), "username");
String password = XMLUtil.getAttributeValue(listProfiles.item(i), "password");
String name = XMLUtil.getAttributeValue(listProfiles.item(i), "name");
profiles.add(new Profile(name, host, port, userName, password));
}
}
}
boolean hasDefault = false;
for (Profile prof : profiles) {
if (prof.equals(config.get("defaultProfile"))) {
hasDefault = true;
break;
}
}
if (!hasDefault) {
profiles.add(new Profile(config.get("defaultProfile"), "localhost", "12345", "", ""));
}
} catch (Exception e) {
System.out.println("An error ocurred loading the config file");
}
}
}
| true | true | public static void init(String fileName) {
config.clear();
profiles.clear();
config.put("defaultProfile", "default");
config.put("masterServer","http://localhost/servers.php?&action=list");
file = new File(fileName);
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new ErrorHandler() {
@Override
public void error(SAXParseException e) throws SAXException {
throw e;
}
@Override
public void fatalError(SAXParseException e) throws SAXException {
System.out.println("Fatal error validating the config file:");
e.printStackTrace();
System.exit(0);
}
@Override
public void warning(SAXParseException e) throws SAXException {
System.out.println("Warning validating the config file:");
e.printStackTrace();
}
});
Document document = builder.parse(file);
Node node = document.getDocumentElement();
Node configNode = XMLUtil.getChildByName(node, "config");
NodeList listConfig = configNode.getChildNodes();
if (listConfig != null) {
for (int i = 0; i < listConfig.getLength(); i++) {
if (listConfig.item(i).getNodeName().equals("setting")) {
config.put(XMLUtil.getAttributeValue(listConfig.item(i), "key"), XMLUtil
.getAttributeValue(listConfig.item(i), "value"));
}
}
}
Node profilesNode = XMLUtil.getChildByName(node, "profiles");
NodeList listProfiles = profilesNode.getChildNodes();
if (listProfiles != null) {
for (int i = 0; i < listProfiles.getLength(); i++) {
if (listProfiles.item(i).getNodeName().equals("profile")) {
String host = XMLUtil.getAttributeValue(listProfiles.item(i), "host");
String port = XMLUtil.getAttributeValue(listProfiles.item(i), "port");
String userName = XMLUtil.getAttributeValue(listProfiles.item(i), "username");
String password = XMLUtil.getAttributeValue(listProfiles.item(i), "password");
String name = XMLUtil.getAttributeValue(listProfiles.item(i), "name");
profiles.add(new Profile(name, host, port, userName, password));
}
}
}
boolean hasDefault = false;
for (Profile prof : profiles) {
if (prof.equals(config.get("defaultProfile"))) {
hasDefault = true;
break;
}
}
if (!hasDefault) {
profiles.add(new Profile(config.get("defaultProfile"), "localhost", "12345", "", ""));
}
} catch (Exception e) {
System.out.println("An error ocurred loading the config file");
}
}
| public static void init(String fileName) {
config.clear();
profiles.clear();
config.put("defaultProfile", "default");
config.put("masterServer","http://localhost/servers.php?&action=list");
file = new File(fileName);
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(true);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setErrorHandler(new ErrorHandler() {
@Override
public void error(SAXParseException e) throws SAXException {
throw e;
}
@Override
public void fatalError(SAXParseException e) throws SAXException {
System.out.println("Fatal error validating the config file:");
e.printStackTrace();
System.exit(0);
}
@Override
public void warning(SAXParseException e) throws SAXException {
System.out.println("Warning validating the config file:");
e.printStackTrace();
}
});
Document document = builder.parse(file);
Node node = document.getDocumentElement();
Node configNode = XMLUtil.getChildByName(node, "config");
NodeList listConfig = configNode.getChildNodes();
if (listConfig != null) {
for (int i = 0; i < listConfig.getLength(); i++) {
if (listConfig.item(i).getNodeName().equals("setting")) {
config.put(XMLUtil.getAttributeValue(listConfig.item(i), "key"), XMLUtil
.getAttributeValue(listConfig.item(i), "value"));
}
}
}
Node profilesNode = XMLUtil.getChildByName(node, "profiles");
NodeList listProfiles = profilesNode.getChildNodes();
if (listProfiles != null) {
for (int i = 0; i < listProfiles.getLength(); i++) {
if (listProfiles.item(i).getNodeName().equals("profile")) {
String host = XMLUtil.getAttributeValue(listProfiles.item(i), "host");
String port = XMLUtil.getAttributeValue(listProfiles.item(i), "port");
String userName = XMLUtil.getAttributeValue(listProfiles.item(i), "username");
String password = XMLUtil.getAttributeValue(listProfiles.item(i), "password");
String name = XMLUtil.getAttributeValue(listProfiles.item(i), "name");
profiles.add(new Profile(name, host, port, userName, password));
}
}
}
boolean hasDefault = false;
for (Profile prof : profiles) {
if (prof.equals(config.get("defaultProfile"))) {
hasDefault = true;
break;
}
}
if (!hasDefault) {
profiles.add(new Profile(config.get("defaultProfile"), "localhost", "12345", "", ""));
}
} catch (Exception e) {
System.out.println("An error ocurred loading the config file");
}
}
|
diff --git a/src/com/stackframe/pattymelt/PattyMelt.java b/src/com/stackframe/pattymelt/PattyMelt.java
index da590f8..ff608cf 100644
--- a/src/com/stackframe/pattymelt/PattyMelt.java
+++ b/src/com/stackframe/pattymelt/PattyMelt.java
@@ -1,276 +1,276 @@
/*
* Copyright 2012, Gene McCulley
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
package com.stackframe.pattymelt;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import javax.swing.*;
/**
* A simple command line driver for DCPU-16.
*
* @author mcculley
*/
public class PattyMelt {
/**
* Load a binary file into memory.
*
* @param memory a ShortBuffer to read the file into
* @param file a File to read from
* @throws IOException
*/
private static void loadBinary(short[] memory, File file) throws IOException {
// FIXME: Close streams correctly.
int i = 0;
InputStream inputStream = new FileInputStream(file);
while (true) {
int v1 = inputStream.read();
if (v1 == -1) {
return;
}
int v2 = inputStream.read();
if (v2 == -1) {
return;
}
short value = (short) ((v2 << 8) | v1);
memory[i++] = value;
}
}
/**
* Load a file into memory. The file is assumed to be lines of hexadecimal
* 16-bit words.
*
* @param memory a ShortBuffer to read the file into
* @param reader a BufferedReader to read from
* @throws IOException
*/
private static void loadHex(short[] memory, BufferedReader reader) throws IOException {
// FIXME: Close streams correctly.
int i = 0;
while (true) {
String line = reader.readLine();
if (line == null) {
return;
}
short value = (short) Integer.parseInt(line, 16);
memory[i++] = value;
}
}
private static boolean isBinary(File file) throws IOException {
// FIXME: Close streams correctly.
InputStream inputStream = new FileInputStream(file);
while (true) {
int value = inputStream.read();
if (value == -1) {
return false;
}
char c = (char) value;
boolean isLetterOrDigit = Character.isLetterOrDigit(c);
boolean isWhitespace = Character.isWhitespace(c);
if (!(isLetterOrDigit || isWhitespace)) {
return true;
}
}
}
private static String dumpMemory(int address, int numWords, short[] memory) {
// FIXME: Make this better. It is a crude bit of debugging right now.
StringBuilder buf = new StringBuilder();
for (int i = 0; i < numWords; i++) {
short value = memory[address + i];
char c = (char) value;
if (!(Character.isLetterOrDigit(c) || Character.isWhitespace(c))) {
c = '.';
}
buf.append(c);
}
return buf.toString();
}
private Console console;
private StateViewer stateViewer;
private final DCPU16 cpu = new DCPU16Emulator();
private final JButton stepButton = new JButton("Step");
private final JButton runButton = new JButton("Run");
private final JButton stopButton = new JButton("Stop");
private volatile boolean running;
private void launch(String filename) throws Exception {
final short[] memory = cpu.memory();
System.err.println("Loading " + filename);
File file = new File(filename);
// Try to guess if this is binary or not. Should add an option to be explicit.
if (isBinary(file)) {
loadBinary(memory, file);
} else {
// FIXME: Close streams correctly.
BufferedReader reader = new BufferedReader(new FileReader(filename));
loadHex(memory, reader);
}
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
console = new Console(0x8000, memory);
JFrame frame = new JFrame("PattyMelt");
- frame.setSize(640, 480);
+ frame.setSize(240, 240);
frame.getContentPane().add(console.getWidget());
frame.setVisible(true);
stateViewer = new StateViewer(cpu);
JFrame stateFrame = new JFrame("CPU State");
stateFrame.getContentPane().setLayout(new BorderLayout());
stateFrame.getContentPane().add(stateViewer.getWidget(), BorderLayout.SOUTH);
JComponent controlBox = new JPanel();
controlBox.add(stepButton);
controlBox.add(runButton);
stopButton.setEnabled(false);
controlBox.add(stopButton);
stateFrame.getContentPane().add(controlBox, BorderLayout.NORTH);
stepButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
try {
stepCPU();
} catch (IllegalOpcodeException ioe) {
// FIXME: reflect in GUI
System.err.printf("Illegal opcode 0x%04x encountered.\n", ioe.opcode);
}
}
});
runButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
runButton.setEnabled(false);
stopButton.setEnabled(true);
stepButton.setEnabled(false);
running = true;
Thread thread = new Thread(
new Runnable() {
@Override
public void run() {
runCPU();
}
}, "DCPU-16");
thread.start();
}
});
stopButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
running = false;
runButton.setEnabled(true);
stopButton.setEnabled(false);
stepButton.setEnabled(true);
}
});
stateFrame.pack();
stateFrame.setLocation(0, 100);
stateFrame.setVisible(true);
}
});
updatePeripherals();
}
private void updatePeripheralsInSwingThread() {
assert SwingUtilities.isEventDispatchThread();
console.update();
stateViewer.update();
}
private void updatePeripherals() {
if (SwingUtilities.isEventDispatchThread()) {
updatePeripheralsInSwingThread();
} else {
try {
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
updatePeripheralsInSwingThread();
}
});
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
private void stepCPU() throws IllegalOpcodeException {
cpu.step();
updatePeripherals();
}
private void runCPU() {
try {
while (running) {
stepCPU();
}
} catch (IllegalOpcodeException ioe) {
// FIXME: reflect in GUI
System.err.printf("Illegal opcode 0x%04x encountered.\n", ioe.opcode);
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws Exception {
PattyMelt application = new PattyMelt();
String filename = args[0];
application.launch(filename);
}
// FIXE: Add support for undoing/going back in time to debug.
}
| true | true | private void launch(String filename) throws Exception {
final short[] memory = cpu.memory();
System.err.println("Loading " + filename);
File file = new File(filename);
// Try to guess if this is binary or not. Should add an option to be explicit.
if (isBinary(file)) {
loadBinary(memory, file);
} else {
// FIXME: Close streams correctly.
BufferedReader reader = new BufferedReader(new FileReader(filename));
loadHex(memory, reader);
}
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
console = new Console(0x8000, memory);
JFrame frame = new JFrame("PattyMelt");
frame.setSize(640, 480);
frame.getContentPane().add(console.getWidget());
frame.setVisible(true);
stateViewer = new StateViewer(cpu);
JFrame stateFrame = new JFrame("CPU State");
stateFrame.getContentPane().setLayout(new BorderLayout());
stateFrame.getContentPane().add(stateViewer.getWidget(), BorderLayout.SOUTH);
JComponent controlBox = new JPanel();
controlBox.add(stepButton);
controlBox.add(runButton);
stopButton.setEnabled(false);
controlBox.add(stopButton);
stateFrame.getContentPane().add(controlBox, BorderLayout.NORTH);
stepButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
try {
stepCPU();
} catch (IllegalOpcodeException ioe) {
// FIXME: reflect in GUI
System.err.printf("Illegal opcode 0x%04x encountered.\n", ioe.opcode);
}
}
});
runButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
runButton.setEnabled(false);
stopButton.setEnabled(true);
stepButton.setEnabled(false);
running = true;
Thread thread = new Thread(
new Runnable() {
@Override
public void run() {
runCPU();
}
}, "DCPU-16");
thread.start();
}
});
stopButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
running = false;
runButton.setEnabled(true);
stopButton.setEnabled(false);
stepButton.setEnabled(true);
}
});
stateFrame.pack();
stateFrame.setLocation(0, 100);
stateFrame.setVisible(true);
}
});
updatePeripherals();
}
| private void launch(String filename) throws Exception {
final short[] memory = cpu.memory();
System.err.println("Loading " + filename);
File file = new File(filename);
// Try to guess if this is binary or not. Should add an option to be explicit.
if (isBinary(file)) {
loadBinary(memory, file);
} else {
// FIXME: Close streams correctly.
BufferedReader reader = new BufferedReader(new FileReader(filename));
loadHex(memory, reader);
}
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
console = new Console(0x8000, memory);
JFrame frame = new JFrame("PattyMelt");
frame.setSize(240, 240);
frame.getContentPane().add(console.getWidget());
frame.setVisible(true);
stateViewer = new StateViewer(cpu);
JFrame stateFrame = new JFrame("CPU State");
stateFrame.getContentPane().setLayout(new BorderLayout());
stateFrame.getContentPane().add(stateViewer.getWidget(), BorderLayout.SOUTH);
JComponent controlBox = new JPanel();
controlBox.add(stepButton);
controlBox.add(runButton);
stopButton.setEnabled(false);
controlBox.add(stopButton);
stateFrame.getContentPane().add(controlBox, BorderLayout.NORTH);
stepButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
try {
stepCPU();
} catch (IllegalOpcodeException ioe) {
// FIXME: reflect in GUI
System.err.printf("Illegal opcode 0x%04x encountered.\n", ioe.opcode);
}
}
});
runButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
runButton.setEnabled(false);
stopButton.setEnabled(true);
stepButton.setEnabled(false);
running = true;
Thread thread = new Thread(
new Runnable() {
@Override
public void run() {
runCPU();
}
}, "DCPU-16");
thread.start();
}
});
stopButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
running = false;
runButton.setEnabled(true);
stopButton.setEnabled(false);
stepButton.setEnabled(true);
}
});
stateFrame.pack();
stateFrame.setLocation(0, 100);
stateFrame.setVisible(true);
}
});
updatePeripherals();
}
|
diff --git a/examples/fixengine/examples/console/commands/Logon.java b/examples/fixengine/examples/console/commands/Logon.java
index 2b6655d4..d8502a3d 100644
--- a/examples/fixengine/examples/console/commands/Logon.java
+++ b/examples/fixengine/examples/console/commands/Logon.java
@@ -1,131 +1,131 @@
/*
* Copyright 2010 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package fixengine.examples.console.commands;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.util.Iterator;
import java.util.Scanner;
import fixengine.Config;
import fixengine.Version;
import fixengine.session.Session;
import fixengine.session.HeartBtIntValue;
import fixengine.examples.console.ConsoleClient;
import fixengine.messages.DefaultMessageVisitor;
import silvertip.Connection;
import silvertip.Message;
import silvertip.protocols.FixMessageParser;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
/**
* @author Karim Osman
*/
public class Logon implements Command {
private static final Version VERSION = Version.FIX_4_2;
private static final String SENDER_COMP_ID = "initiator";
private static final String TARGET_COMP_ID = "OPENFIX";
private static final Logger logger = Logger.getLogger("ConsoleClient");
static {
logger.setUseParentHandlers(false);
try {
logger.addHandler(new FileHandler("fixengine.log"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public void execute(final ConsoleClient client, Scanner scanner) throws CommandArgException {
try {
Connection conn = Connection.connect(new InetSocketAddress(host(scanner), port(scanner)),
new FixMessageParser(), new Connection.Callback() {
@Override public void messages(Connection conn, Iterator<Message> messages) {
while (messages.hasNext()) {
Message msg = messages.next();
client.getSession().receive(conn, msg, new DefaultMessageVisitor() {
@Override public void defaultAction(fixengine.messages.Message message) {
logger.info(message.toString());
}
});
}
}
@Override public void idle(Connection conn) {
client.getSession().keepAlive(conn);
}
@Override public void closed(Connection conn) {
}
});
client.setConnection(conn);
- Session session = new Session(getHeartBtInt(), getConfig(), client.getSessionStore()) {
+ Session session = new Session(getHeartBtInt(), getConfig(), client.getSessionStore(), client.getMessageFactory()) {
@Override
protected boolean checkSeqResetSeqNum() {
/* Do not verify that the sequence numbers of SeqReset messages as
* test scenarios of OpenFIX certification sets MsgSeqNum to 1
* despite the value of GapFillFlag.
*/
return false;
}
};
client.setSession(session);
session.logon(conn);
client.getEvents().register(conn);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private HeartBtIntValue getHeartBtInt() {
return new HeartBtIntValue(30);
}
private Config getConfig() {
Config config = new Config();
config.setSenderCompId(SENDER_COMP_ID);
config.setTargetCompId(TARGET_COMP_ID);
config.setVersion(VERSION);
return config;
}
private InetAddress host(Scanner scanner) throws CommandArgException {
if (!scanner.hasNext())
throw new CommandArgException("hostname must be specified");
try {
return InetAddress.getByName(scanner.next());
} catch (UnknownHostException e) {
throw new CommandArgException("unknown hostname");
}
}
private int port(Scanner scanner) throws CommandArgException {
if (!scanner.hasNext())
throw new CommandArgException("port must be specified");
try {
return Integer.parseInt(scanner.next());
} catch (NumberFormatException e) {
throw new CommandArgException("invalid port");
}
}
}
| true | true | public void execute(final ConsoleClient client, Scanner scanner) throws CommandArgException {
try {
Connection conn = Connection.connect(new InetSocketAddress(host(scanner), port(scanner)),
new FixMessageParser(), new Connection.Callback() {
@Override public void messages(Connection conn, Iterator<Message> messages) {
while (messages.hasNext()) {
Message msg = messages.next();
client.getSession().receive(conn, msg, new DefaultMessageVisitor() {
@Override public void defaultAction(fixengine.messages.Message message) {
logger.info(message.toString());
}
});
}
}
@Override public void idle(Connection conn) {
client.getSession().keepAlive(conn);
}
@Override public void closed(Connection conn) {
}
});
client.setConnection(conn);
Session session = new Session(getHeartBtInt(), getConfig(), client.getSessionStore()) {
@Override
protected boolean checkSeqResetSeqNum() {
/* Do not verify that the sequence numbers of SeqReset messages as
* test scenarios of OpenFIX certification sets MsgSeqNum to 1
* despite the value of GapFillFlag.
*/
return false;
}
};
client.setSession(session);
session.logon(conn);
client.getEvents().register(conn);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
| public void execute(final ConsoleClient client, Scanner scanner) throws CommandArgException {
try {
Connection conn = Connection.connect(new InetSocketAddress(host(scanner), port(scanner)),
new FixMessageParser(), new Connection.Callback() {
@Override public void messages(Connection conn, Iterator<Message> messages) {
while (messages.hasNext()) {
Message msg = messages.next();
client.getSession().receive(conn, msg, new DefaultMessageVisitor() {
@Override public void defaultAction(fixengine.messages.Message message) {
logger.info(message.toString());
}
});
}
}
@Override public void idle(Connection conn) {
client.getSession().keepAlive(conn);
}
@Override public void closed(Connection conn) {
}
});
client.setConnection(conn);
Session session = new Session(getHeartBtInt(), getConfig(), client.getSessionStore(), client.getMessageFactory()) {
@Override
protected boolean checkSeqResetSeqNum() {
/* Do not verify that the sequence numbers of SeqReset messages as
* test scenarios of OpenFIX certification sets MsgSeqNum to 1
* despite the value of GapFillFlag.
*/
return false;
}
};
client.setSession(session);
session.logon(conn);
client.getEvents().register(conn);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
|
diff --git a/src/org/pentaho/agilebi/platform/JettyServer.java b/src/org/pentaho/agilebi/platform/JettyServer.java
index 8981cbe..36410ac 100755
--- a/src/org/pentaho/agilebi/platform/JettyServer.java
+++ b/src/org/pentaho/agilebi/platform/JettyServer.java
@@ -1,116 +1,117 @@
/*
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* 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.
*
* Copyright (c) 2009 Pentaho Corporation.. All rights reserved.
*/
package org.pentaho.agilebi.platform;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Handler;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.handler.DefaultHandler;
import org.mortbay.jetty.handler.HandlerCollection;
import org.mortbay.jetty.webapp.WebAppContext;
import org.pentaho.di.core.logging.LogWriter;
public class JettyServer {
private static Class<?> PKG = JettyServer.class; // for i18n purposes, needed by Translator2!! $NON-NLS-1$
private static LogWriter log = LogWriter.getInstance();
public static final int PORT = 80;
private Server server;
private String hostname;
private int port;
private String webappsFolder = "plugins/spoon/agile-bi/platform/webapps"; //$NON-NLS-1$
public JettyServer(String hostname, int port) throws Exception {
this.hostname = hostname;
this.port = port;
}
public void setWebappsFolder(String webappsFolder) {
this.webappsFolder = webappsFolder;
}
public Server getServer() {
return server;
}
public void startServer() throws Exception {
server = new Server();
WebAppContext pentahoContext = new WebAppContext();
+ pentahoContext.setClassLoader(getClass().getClassLoader());
pentahoContext.setContextPath("/pentaho"); //$NON-NLS-1$
pentahoContext.setWar(webappsFolder + "/pentaho"); //$NON-NLS-1$
pentahoContext.setParentLoaderPriority(true);
HandlerCollection handlers= new HandlerCollection();
handlers.setHandlers(new Handler[]{pentahoContext, new DefaultHandler()});
server.setHandler(handlers);
// Start execution
createListeners();
server.start();
}
protected void setupListeners() {
}
public void stopServer() {
try {
if (server != null) {
server.stop();
}
} catch (Exception e) {
LogWriter.getInstance(LogWriter.LOG_LEVEL_ERROR).logBasic(toString(), "WebServer.Error.FailedToStop.Title", null);
}
}
private void createListeners() {
SocketConnector connector = new SocketConnector();
connector.setPort(port);
connector.setHost(hostname);
connector.setName(hostname);
LogWriter.getInstance(LogWriter.LOG_LEVEL_ERROR).logBasic(toString(), "WebServer.Log.CreateListener" + hostname + ":" + port, null);
server.setConnectors(new Connector[] { connector });
}
/**
* @return the hostname
*/
public String getHostname() {
return hostname;
}
/**
* @param hostname the hostname to set
*/
public void setHostname(String hostname) {
this.hostname = hostname;
}
}
| true | true | public void startServer() throws Exception {
server = new Server();
WebAppContext pentahoContext = new WebAppContext();
pentahoContext.setContextPath("/pentaho"); //$NON-NLS-1$
pentahoContext.setWar(webappsFolder + "/pentaho"); //$NON-NLS-1$
pentahoContext.setParentLoaderPriority(true);
HandlerCollection handlers= new HandlerCollection();
handlers.setHandlers(new Handler[]{pentahoContext, new DefaultHandler()});
server.setHandler(handlers);
// Start execution
createListeners();
server.start();
}
| public void startServer() throws Exception {
server = new Server();
WebAppContext pentahoContext = new WebAppContext();
pentahoContext.setClassLoader(getClass().getClassLoader());
pentahoContext.setContextPath("/pentaho"); //$NON-NLS-1$
pentahoContext.setWar(webappsFolder + "/pentaho"); //$NON-NLS-1$
pentahoContext.setParentLoaderPriority(true);
HandlerCollection handlers= new HandlerCollection();
handlers.setHandlers(new Handler[]{pentahoContext, new DefaultHandler()});
server.setHandler(handlers);
// Start execution
createListeners();
server.start();
}
|
diff --git a/deegree-core/deegree-core-cs/src/main/java/org/deegree/cs/coordinatesystems/CRS.java b/deegree-core/deegree-core-cs/src/main/java/org/deegree/cs/coordinatesystems/CRS.java
index 2258a798be..42ef6b731a 100644
--- a/deegree-core/deegree-core-cs/src/main/java/org/deegree/cs/coordinatesystems/CRS.java
+++ b/deegree-core/deegree-core-cs/src/main/java/org/deegree/cs/coordinatesystems/CRS.java
@@ -1,580 +1,580 @@
//$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
Department of Geography, University of Bonn
and
lat/lon GmbH
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
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: [email protected]
----------------------------------------------------------------------------*/
package org.deegree.cs.coordinatesystems;
import static org.slf4j.LoggerFactory.getLogger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import javax.vecmath.Point3d;
import org.deegree.cs.CRSCodeType;
import org.deegree.cs.CRSIdentifiable;
import org.deegree.cs.CRSResource;
import org.deegree.cs.CoordinateTransformer;
import org.deegree.cs.components.Axis;
import org.deegree.cs.components.IAxis;
import org.deegree.cs.components.IDatum;
import org.deegree.cs.components.IGeodeticDatum;
import org.deegree.cs.components.IUnit;
import org.deegree.cs.components.Unit;
import org.deegree.cs.persistence.CRSManager;
import org.deegree.cs.refs.coordinatesystem.CRSRef;
import org.deegree.cs.transformations.Transformation;
import org.slf4j.Logger;
/**
* Three kinds of <code>CoordinateSystem</code>s (in this class abbreviated with CRS) are supported in this lib.
* <ul>
* <li>Geographic CRS: A position (on the ellipsoid) is given in Lattitude / Longitude (Polar Cooridnates) given in rad°
* min''sec. The order of the position's coordinates are to be contrued to the axis order of the CRS. These lat/lon
* coordinates are to be tranformed to x,y,z values to define their location on the underlying datum.</li>
* <li>GeoCentric CRS: A position (on the ellipsoid) is given in x, y, z (cartesian) coordinates with the same units
* defined as the ones in the underlying datum. The order of the position's coordinates are to be contrued to the axis
* order of the datum.</li>
* <li>Projected CRS: The position (on the map) is given in a 2D-tuple in pre-defined units. The Axis of the CRS are
* defined (through a transformation) for an underlying Datum, which can have it's own axis with their own units. The
* order of the position's coordinates are to be contrued to the axis order of the CRS</li>
* </ul>
*
* Summarizing it can be said, that each CRS has following features
* <ul>
* <li>A reference code (an casesensitive String identifying this CRS, for example 'EPGS:4326' or
* 'urn:ogc:def:crs:OGC:2:84' or 'luref')</li>
* <li>An optional version.</li>
* <li>A humanly readable name.</li>
* <li>An optional description.</li>
* <li>An optional area of use, describing where this CRS is used.</li>
* <li>The order in which the axis of ther crs are defined.</li>
* <li>The underlying Datum</li>
*
* @author <a href="mailto:[email protected]">Rutger Bezema</a>
*
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*
*/
public abstract class CRS extends CRSIdentifiable implements ICRS {
private static final Logger LOG = getLogger( ICRS.class );
private final Object LOCK = new Object();
private IAxis[] axisOrder;
private IDatum usedDatum;
private final List<Transformation> transformations;
private transient double[] validDomain = null;
/**
*
* Simple enum defining the currently known Coordinate System types.
*
* @author <a href="mailto:[email protected]">Rutger Bezema</a>
* @author last edited by: $Author: rutger $
*
* @version $Revision: $, $Date: $
*/
public enum CRSType {
/** Defines this CRS as a GeoCentric one. */
GEOCENTRIC( "Geocentric CRS" ),
/** Defines this CRS as a Geographic one. */
GEOGRAPHIC( "Geographic CRS" ),
/** Defines this CRS as a Projected one. */
PROJECTED( "Projected CRS" ),
/** Defines this CRS as a Compound one. */
COMPOUND( "Compound CRS" ),
/** Defines this CRS as a Vertical one. */
VERTICAL( "Vertical CRS" );
private String name;
private CRSType( String name ) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
/**
* @param datum
* of this coordinate system.
* @param axisOrder
* the axisorder of this coordinate system.
* @param identity
*/
public CRS( IDatum datum, IAxis[] axisOrder, CRSResource identity ) {
this( null, datum, axisOrder, identity );
}
/**
* @param datum
* of this coordinate system.
* @param axisOrder
* the axisorder of this coordinate system.
* @param codes
* of this coordinate system.
* @param names
* @param versions
* @param descriptions
* @param areasOfUse
*/
public CRS( IDatum datum, IAxis[] axisOrder, CRSCodeType[] codes, String[] names, String[] versions,
String[] descriptions, String[] areasOfUse ) {
super( codes, names, versions, descriptions, areasOfUse );
this.axisOrder = axisOrder;
this.usedDatum = datum;
this.transformations = new LinkedList<Transformation>();
}
/**
* @param transformations
* to use instead of the helmert transformation(s).
* @param datum
* of this crs
* @param axisOrder
* @param identity
*/
public CRS( List<Transformation> transformations, IDatum datum, IAxis[] axisOrder, CRSResource identity ) {
super( identity );
if ( axisOrder != null ) {
this.axisOrder = new Axis[axisOrder.length];
for ( int i = 0; i < axisOrder.length; ++i ) {
this.axisOrder[i] = axisOrder[i];
}
} else {
// rb: what to do
this.axisOrder = null;
}
this.usedDatum = datum;
if ( transformations == null ) {
transformations = new LinkedList<Transformation>();
}
this.transformations = transformations;
}
/**
* @return (all) axis' in their defined order.
*/
public IAxis[] getAxis() {
IAxis[] result = new Axis[axisOrder.length];
for ( int i = 0; i < axisOrder.length; ++i ) {
result[i] = axisOrder[i];
}
return result;
}
/**
* @return the usedDatum or <code>null</code> if the datum was not a Geodetic one.
*/
public final IGeodeticDatum getGeodeticDatum() {
return ( usedDatum instanceof IGeodeticDatum ) ? (IGeodeticDatum) usedDatum : null;
}
/**
* @return the datum of this coordinate system.
*/
public final IDatum getDatum() {
return usedDatum;
}
/**
* @return the units of all axis of the ICoordinateSystem.
*/
public IUnit[] getUnits() {
IAxis[] allAxis = getAxis();
IUnit[] result = new Unit[allAxis.length];
for ( int i = 0; i < allAxis.length; ++i ) {
result[i] = allAxis[i].getUnits();
}
return result;
}
/**
* @param targetCRS
* to get the alternative Transformation for.
* @return true if this crs has an alternative transformation for the given ICoordinateSystem, false otherwise.
*/
public boolean hasDirectTransformation( ICRS targetCRS ) {
if ( targetCRS == null ) {
return false;
}
for ( Transformation transformation : transformations ) {
if ( transformation != null && transformation.canTransform( this, targetCRS ) ) {
return true;
}
}
return false;
}
/**
* @param targetCRS
* to get the alternative transformation for.
* @return the transformation associated with the given crs, <code>null</code> otherwise.
*/
public Transformation getDirectTransformation( ICRS targetCRS ) {
if ( targetCRS == null ) {
return null;
}
for ( Transformation transformation : transformations ) {
if ( transformation.canTransform( this, targetCRS ) ) {
return transformation;
}
}
return null;
}
/**
* Converts the given coordinates in given to the unit of the respective axis.
*
* @param coordinates
* to convert to.
* @param units
* in which the coordinates were given.
* @param invert
* if the operation should be inverted, e.g. the coordinates are given in the axis units and should be
* converted to the given units.
* @return the converted coordinates.
*/
public Point3d convertToAxis( Point3d coordinates, IUnit[] units, boolean invert ) {
if ( units != null && units.length < getDimension() && units.length > 0 ) {
IUnit[] axisUnits = getUnits();
for ( int i = 0; i < axisUnits.length; i++ ) {
IUnit axisUnit = axisUnits[i];
double value = ( i == 0 ) ? coordinates.x : ( i == 1 ) ? coordinates.y : coordinates.z;
if ( i < units.length ) {
IUnit coordinateUnit = units[i];
if ( invert ) {
value = axisUnit.convert( value, coordinateUnit );
} else {
value = coordinateUnit.convert( value, axisUnit );
}
}
if ( i == 0 ) {
coordinates.x = value;
} else if ( i == 1 ) {
coordinates.y = value;
} else {
coordinates.z = value;
}
}
}
return coordinates;
}
/**
* Helper function to get the typename as a String.
*
* @return either the type as a name or 'Unknown' if the type is not known.
*/
protected String getTypeName() {
return getType().toString();
}
/**
* Checks if the given axis match this.axisOrder[] in length, but flipped x/y ([0]/[1]) order.
*
* @param otherAxis
* the axis to check
* @return true if the given axis match this.axisOrder[] false otherwise.
*/
private boolean matchAxisWithFlippedOrder( IAxis[] otherAxis ) {
IAxis[] allAxis = getAxis();
if ( otherAxis.length != allAxis.length || otherAxis.length < 2 ) {
return false;
}
IAxis aX = allAxis[0];
IAxis bY = otherAxis[0];
IAxis aY = allAxis[1];
IAxis bX = otherAxis[1];
if ( !aX.equals( bX ) && !aY.equals( bY ) ) {
return false;
}
for ( int i = 2; i < allAxis.length; ++i ) {
IAxis a = allAxis[i];
IAxis b = otherAxis[i];
if ( !a.equals( b ) ) {
return false;
}
}
return true;
}
/**
* Checks if the given axis match this.axisOrder[] in length and order.
*
* @param otherAxis
* the axis to check
* @return true if the given axis match this.axisOrder[] false otherwise.
*/
private boolean matchAxis( IAxis[] otherAxis ) {
IAxis[] allAxis = getAxis();
if ( otherAxis.length != allAxis.length ) {
return false;
}
for ( int i = 0; i < allAxis.length; ++i ) {
IAxis a = allAxis[i];
IAxis b = otherAxis[i];
if ( !a.equals( b ) ) {
return false;
}
}
return true;
}
@Override
public boolean equals( Object other ) {
if ( other instanceof CRSRef ) {
other = ( (CRSRef) other ).getReferencedObject();
}
if ( other != null && other instanceof ICRS ) {
final ICRS that = (CRS) other;
return that.getType() == this.getType() && that.getDimension() == this.getDimension()
&& matchAxis( that.getAxis() ) && super.equals( that ) && that.getDatum().equals( this.getDatum() );
}
return false;
}
public boolean equalsWithFlippedAxis( Object other ) {
if ( other instanceof CRSRef ) {
other = ( (CRSRef) other ).getReferencedObject();
}
if ( other != null && other instanceof ICRS ) {
final ICRS that = (CRS) other;
return that.getType() == this.getType() && that.getDimension() == this.getDimension()
&& matchAxisWithFlippedOrder( that.getAxis() ) && that.getDatum().equals( this.getDatum() );
}
return false;
}
/**
* Implementation as proposed by Joshua Block in Effective Java (Addison-Wesley 2001), which supplies an even
* distribution and is relatively fast. It is created from field <b>f</b> as follows:
* <ul>
* <li>boolean -- code = (f ? 0 : 1)</li>
* <li>byte, char, short, int -- code = (int)f</li>
* <li>long -- code = (int)(f ^ (f >>>32))</li>
* <li>float -- code = Float.floatToIntBits(f);</li>
* <li>double -- long l = Double.doubleToLongBits(f); code = (int)(l ^ (l >>> 32))</li>
* <li>all Objects, (where equals( ) calls equals( ) for this field) -- code = f.hashCode( )</li>
* <li>Array -- Apply above rules to each element</li>
* </ul>
* <p>
* Combining the hash code(s) computed above: result = 37 * result + code;
* </p>
*
* @return (int) ( result >>> 32 ) ^ (int) result;
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
// the 2.nd million th. prime, :-)
long code = 32452843;
if ( getAxis() != null ) {
for ( IAxis ax : getAxis() ) {
code = code * 37 + ax.hashCode();
}
}
if ( usedDatum != null ) {
code = code * 37 + usedDatum.hashCode();
}
code = getType().name().hashCode();
code = code * 37 + getDimension();
return (int) ( code >>> 32 ) ^ (int) code;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder( super.toString() );
sb.append( "\n - type: " ).append( getTypeName() );
sb.append( "\n - datum: " ).append( usedDatum );
sb.append( "\n - dimension: " ).append( getDimension() );
for ( IAxis a : getAxis() ) {
sb.append( "\n - axis: " ).append( a.toString() );
}
return sb.toString();
}
/**
* @return the polynomial transformations.
*/
public final List<Transformation> getTransformations() {
return transformations;
}
// public void setDefaultIdentifier( CRSCodeType crsCode ) {
// super.setDefaultIdentifier( crsCode );
// }
/**
* Return the axis index associated with an easting value, if the axis could not be determined {@link Axis#AO_OTHER}
* 0 will be returned.
*
* @return the index of the axis which represents the easting/westing component of a coordinate tuple.
*/
public int getEasting() {
IAxis[] axis = getAxis();
for ( int i = 0; i < axis.length; ++i ) {
IAxis a = axis[i];
if ( a != null ) {
if ( a.getOrientation() == Axis.AO_EAST || a.getOrientation() == Axis.AO_WEST ) {
return i;
}
}
}
return 0;
}
/**
* Return the axis index associated with a northing value, if the axis could not be determined (e.g not is
* {@link Axis#AO_NORTH} {@link Axis#AO_SOUTH} or {@link Axis#AO_UP} or {@link Axis#AO_DOWN}) 1 will be returned.
*
* @return the index of the axis which represents the easting/westing component of a coordinate tuple.
*/
public int getNorthing() {
IAxis[] axis = getAxis();
for ( int i = 0; i < axis.length; ++i ) {
IAxis a = axis[i];
if ( a != null ) {
if ( a.getOrientation() == Axis.AO_NORTH || a.getOrientation() == Axis.AO_SOUTH
|| a.getOrientation() == Axis.AO_DOWN || a.getOrientation() == Axis.AO_UP ) {
return i;
}
}
}
return 1;
}
/**
* Returns the approximate domain of validity of this coordinate system. The returned array will contain the values
* in the appropriate coordinate system and with the appropriate axis order.
*
* @return the real world coordinates of the domain of validity of this crs, or <code>null</code> if the valid
* domain could not be determined
*/
public double[] getValidDomain() {
synchronized ( LOCK ) {
if ( this.validDomain == null ) {
double[] bbox = getAreaOfUseBBox();
// transform world to coordinates in sourceCRS;
CoordinateTransformer t = new CoordinateTransformer( this );
try {
ICRS defWGS = GeographicCRS.WGS84;
try {
// rb: lookup the default WGS84 in the registry, it may be, that the axis are swapped.
defWGS = CRSManager.lookup( GeographicCRS.WGS84.getCode() );
} catch ( Exception e ) {
// catch any exceptions and use the default.
}
int xAxis = defWGS.getEasting();
int yAxis = 1 - xAxis;
int pointsPerSide = 5;
double axis0Min = bbox[xAxis];
double axis1Min = bbox[yAxis];
double axis0Max = bbox[xAxis + 2];
double axis1Max = bbox[yAxis + 2];
double span0 = Math.abs( axis0Max - axis0Min );
double span1 = Math.abs( axis1Max - axis1Min );
double axis0Step = span0 / ( pointsPerSide + 1 );
double axis1Step = span1 / ( pointsPerSide + 1 );
List<Point3d> points = new ArrayList<Point3d>( pointsPerSide * 4 + 4 );
double zValue = getDimension() == 3 ? 0 : Double.NaN;
for ( int i = 0; i <= pointsPerSide + 1; i++ ) {
points.add( new Point3d( axis0Min + i * axis0Step, axis1Min, zValue ) );
points.add( new Point3d( axis0Min + i * axis0Step, axis1Max, zValue ) );
points.add( new Point3d( axis0Min, axis1Min + i * axis1Step, zValue ) );
points.add( new Point3d( axis0Max, axis1Min + i * axis1Step, zValue ) );
}
points = t.transform( defWGS, points );
axis0Min = Double.MAX_VALUE;
axis1Min = Double.MAX_VALUE;
axis0Max = Double.NEGATIVE_INFINITY;
axis1Max = Double.NEGATIVE_INFINITY;
for ( Point3d p : points ) {
axis0Min = Math.min( p.x, axis0Min );
axis1Min = Math.min( p.y, axis1Min );
axis0Max = Math.max( p.x, axis0Max );
axis1Max = Math.max( p.y, axis1Max );
}
this.validDomain = new double[4];
validDomain[0] = axis0Min;
validDomain[1] = axis1Min;
validDomain[2] = axis0Max;
validDomain[3] = axis1Max;
} catch ( IllegalArgumentException e ) {
LOG.debug( "Exception occurred: " + e.getLocalizedMessage(), e );
LOG.debug( "Exception occurred: " + e.getLocalizedMessage() );
} catch ( org.deegree.cs.exceptions.TransformationException e ) {
LOG.debug( "Exception occurred: " + e.getLocalizedMessage(), e );
LOG.debug( "Exception occurred: " + e.getLocalizedMessage() );
}
}
}
- return Arrays.copyOf( validDomain, 4 );
+ return validDomain != null ? Arrays.copyOf( validDomain, 4 ) : null;
}
/**
* @return the alias of a concrete CRS is the first Code
*/
@Override
public String getAlias() {
return getCode().getOriginal();
}
}
| true | true | public double[] getValidDomain() {
synchronized ( LOCK ) {
if ( this.validDomain == null ) {
double[] bbox = getAreaOfUseBBox();
// transform world to coordinates in sourceCRS;
CoordinateTransformer t = new CoordinateTransformer( this );
try {
ICRS defWGS = GeographicCRS.WGS84;
try {
// rb: lookup the default WGS84 in the registry, it may be, that the axis are swapped.
defWGS = CRSManager.lookup( GeographicCRS.WGS84.getCode() );
} catch ( Exception e ) {
// catch any exceptions and use the default.
}
int xAxis = defWGS.getEasting();
int yAxis = 1 - xAxis;
int pointsPerSide = 5;
double axis0Min = bbox[xAxis];
double axis1Min = bbox[yAxis];
double axis0Max = bbox[xAxis + 2];
double axis1Max = bbox[yAxis + 2];
double span0 = Math.abs( axis0Max - axis0Min );
double span1 = Math.abs( axis1Max - axis1Min );
double axis0Step = span0 / ( pointsPerSide + 1 );
double axis1Step = span1 / ( pointsPerSide + 1 );
List<Point3d> points = new ArrayList<Point3d>( pointsPerSide * 4 + 4 );
double zValue = getDimension() == 3 ? 0 : Double.NaN;
for ( int i = 0; i <= pointsPerSide + 1; i++ ) {
points.add( new Point3d( axis0Min + i * axis0Step, axis1Min, zValue ) );
points.add( new Point3d( axis0Min + i * axis0Step, axis1Max, zValue ) );
points.add( new Point3d( axis0Min, axis1Min + i * axis1Step, zValue ) );
points.add( new Point3d( axis0Max, axis1Min + i * axis1Step, zValue ) );
}
points = t.transform( defWGS, points );
axis0Min = Double.MAX_VALUE;
axis1Min = Double.MAX_VALUE;
axis0Max = Double.NEGATIVE_INFINITY;
axis1Max = Double.NEGATIVE_INFINITY;
for ( Point3d p : points ) {
axis0Min = Math.min( p.x, axis0Min );
axis1Min = Math.min( p.y, axis1Min );
axis0Max = Math.max( p.x, axis0Max );
axis1Max = Math.max( p.y, axis1Max );
}
this.validDomain = new double[4];
validDomain[0] = axis0Min;
validDomain[1] = axis1Min;
validDomain[2] = axis0Max;
validDomain[3] = axis1Max;
} catch ( IllegalArgumentException e ) {
LOG.debug( "Exception occurred: " + e.getLocalizedMessage(), e );
LOG.debug( "Exception occurred: " + e.getLocalizedMessage() );
} catch ( org.deegree.cs.exceptions.TransformationException e ) {
LOG.debug( "Exception occurred: " + e.getLocalizedMessage(), e );
LOG.debug( "Exception occurred: " + e.getLocalizedMessage() );
}
}
}
return Arrays.copyOf( validDomain, 4 );
}
| public double[] getValidDomain() {
synchronized ( LOCK ) {
if ( this.validDomain == null ) {
double[] bbox = getAreaOfUseBBox();
// transform world to coordinates in sourceCRS;
CoordinateTransformer t = new CoordinateTransformer( this );
try {
ICRS defWGS = GeographicCRS.WGS84;
try {
// rb: lookup the default WGS84 in the registry, it may be, that the axis are swapped.
defWGS = CRSManager.lookup( GeographicCRS.WGS84.getCode() );
} catch ( Exception e ) {
// catch any exceptions and use the default.
}
int xAxis = defWGS.getEasting();
int yAxis = 1 - xAxis;
int pointsPerSide = 5;
double axis0Min = bbox[xAxis];
double axis1Min = bbox[yAxis];
double axis0Max = bbox[xAxis + 2];
double axis1Max = bbox[yAxis + 2];
double span0 = Math.abs( axis0Max - axis0Min );
double span1 = Math.abs( axis1Max - axis1Min );
double axis0Step = span0 / ( pointsPerSide + 1 );
double axis1Step = span1 / ( pointsPerSide + 1 );
List<Point3d> points = new ArrayList<Point3d>( pointsPerSide * 4 + 4 );
double zValue = getDimension() == 3 ? 0 : Double.NaN;
for ( int i = 0; i <= pointsPerSide + 1; i++ ) {
points.add( new Point3d( axis0Min + i * axis0Step, axis1Min, zValue ) );
points.add( new Point3d( axis0Min + i * axis0Step, axis1Max, zValue ) );
points.add( new Point3d( axis0Min, axis1Min + i * axis1Step, zValue ) );
points.add( new Point3d( axis0Max, axis1Min + i * axis1Step, zValue ) );
}
points = t.transform( defWGS, points );
axis0Min = Double.MAX_VALUE;
axis1Min = Double.MAX_VALUE;
axis0Max = Double.NEGATIVE_INFINITY;
axis1Max = Double.NEGATIVE_INFINITY;
for ( Point3d p : points ) {
axis0Min = Math.min( p.x, axis0Min );
axis1Min = Math.min( p.y, axis1Min );
axis0Max = Math.max( p.x, axis0Max );
axis1Max = Math.max( p.y, axis1Max );
}
this.validDomain = new double[4];
validDomain[0] = axis0Min;
validDomain[1] = axis1Min;
validDomain[2] = axis0Max;
validDomain[3] = axis1Max;
} catch ( IllegalArgumentException e ) {
LOG.debug( "Exception occurred: " + e.getLocalizedMessage(), e );
LOG.debug( "Exception occurred: " + e.getLocalizedMessage() );
} catch ( org.deegree.cs.exceptions.TransformationException e ) {
LOG.debug( "Exception occurred: " + e.getLocalizedMessage(), e );
LOG.debug( "Exception occurred: " + e.getLocalizedMessage() );
}
}
}
return validDomain != null ? Arrays.copyOf( validDomain, 4 ) : null;
}
|
diff --git a/src/java/main/org/jaxen/function/StringLengthFunction.java b/src/java/main/org/jaxen/function/StringLengthFunction.java
index cdf480d..08e26d5 100644
--- a/src/java/main/org/jaxen/function/StringLengthFunction.java
+++ b/src/java/main/org/jaxen/function/StringLengthFunction.java
@@ -1,156 +1,156 @@
/*
* $Header$
* $Revision$
* $Date$
*
* ====================================================================
*
* Copyright 2000-2002 bob mcwhirter & James Strachan.
* 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 Jaxen Project nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
* IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER
* OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ====================================================================
* This software consists of voluntary contributions made by many
* individuals on behalf of the Jaxen Project and was originally
* created by bob mcwhirter <[email protected]> and
* James Strachan <[email protected]>. For more information on the
* Jaxen Project, please see <http://www.jaxen.org/>.
*
* $Id$
*/
package org.jaxen.function;
import java.util.List;
import org.jaxen.Context;
import org.jaxen.Function;
import org.jaxen.FunctionCallException;
import org.jaxen.Navigator;
/**
* <p><b>4.2</b> <code><i>number</i> string-length(<i>string</i>)</code></p>
*
* <p>
* The <b>string-length</b> function returns the number of <strong>Unicode characters</strong>
* in its argument. This is <strong>not</strong> necessarily
* the same as the number <strong>Java chars</strong>
* in the corresponding Java string. In particular, if the Java <code>String</code>
* contains surrogate pairs each such pair will be counted as only one character
* by this function. If the argument is omitted,
* it returns the length of the string-value of the context node.
* </p>
*
* @author bob mcwhirter (bob @ werken.com)
* @see <a href="http://www.w3.org/TR/xpath#function-string-length" target="_top">Section
* 4.2 of the XPath Specification</a>
*/
public class StringLengthFunction implements Function
{
/**
* Create a new <code>StringLengthFunction</code> object.
*/
public StringLengthFunction() {}
/**
* <p>
* Returns the number of Unicode characters in the string-value of the argument.
* </p>
*
* @param context the context at the point in the
* expression when the function is called
* @param args a list containing the item whose string-value is to be counted.
* If empty, the length of the context node's string-value is returned.
*
* @return a <code>Double</code> giving the number of Unicode characters
*
* @throws FunctionCallException if args has more than one item
*/
public Object call(Context context,
List args) throws FunctionCallException
{
if (args.size() == 0)
{
return evaluate( context.getNodeSet(),
context.getNavigator() );
}
else if (args.size() == 1)
{
return evaluate( args.get(0),
context.getNavigator() );
}
throw new FunctionCallException( "string-length() requires one argument." );
}
/**
* <p>
* Returns the number of Unicode characters in the string-value of
* an object.
* </p>
*
* @param obj the object whose string-value is counted
* @param nav used to calculate the string-values of the first two arguments
*
* @return a <code>Double</code> giving the number of Unicode characters
*
* @throws FunctionCallException if the string contains mismatched surrogates
*/
public static Double evaluate(Object obj, Navigator nav) throws FunctionCallException
{
String str = StringFunction.evaluate( obj, nav );
// String.length() counts UTF-16 code points; not Unicode characters
char[] data = str.toCharArray();
int length = 0;
for (int i = 0; i < data.length; i++) {
char c = data[i];
length++;
// if this is a high surrogate; assume the next character is
// is a low surrogate and skip it
- if (c >= 0xD800) {
+ if (c >= 0xD800 && c <= 0xDFFF) {
try {
char low = data[i+1];
if (low < 0xDC00 || low > 0xDFFF) {
throw new FunctionCallException("Bad surrogate pair in string " + str);
}
i++; // increment past low surrogate
}
catch (ArrayIndexOutOfBoundsException ex) {
throw new FunctionCallException("Bad surrogate pair in string " + str);
}
}
}
return new Double(length);
}
}
| true | true | public static Double evaluate(Object obj, Navigator nav) throws FunctionCallException
{
String str = StringFunction.evaluate( obj, nav );
// String.length() counts UTF-16 code points; not Unicode characters
char[] data = str.toCharArray();
int length = 0;
for (int i = 0; i < data.length; i++) {
char c = data[i];
length++;
// if this is a high surrogate; assume the next character is
// is a low surrogate and skip it
if (c >= 0xD800) {
try {
char low = data[i+1];
if (low < 0xDC00 || low > 0xDFFF) {
throw new FunctionCallException("Bad surrogate pair in string " + str);
}
i++; // increment past low surrogate
}
catch (ArrayIndexOutOfBoundsException ex) {
throw new FunctionCallException("Bad surrogate pair in string " + str);
}
}
}
return new Double(length);
}
| public static Double evaluate(Object obj, Navigator nav) throws FunctionCallException
{
String str = StringFunction.evaluate( obj, nav );
// String.length() counts UTF-16 code points; not Unicode characters
char[] data = str.toCharArray();
int length = 0;
for (int i = 0; i < data.length; i++) {
char c = data[i];
length++;
// if this is a high surrogate; assume the next character is
// is a low surrogate and skip it
if (c >= 0xD800 && c <= 0xDFFF) {
try {
char low = data[i+1];
if (low < 0xDC00 || low > 0xDFFF) {
throw new FunctionCallException("Bad surrogate pair in string " + str);
}
i++; // increment past low surrogate
}
catch (ArrayIndexOutOfBoundsException ex) {
throw new FunctionCallException("Bad surrogate pair in string " + str);
}
}
}
return new Double(length);
}
|
diff --git a/src/us/Myles/DP/Plug.java b/src/us/Myles/DP/Plug.java
index 50fb2c7..3937511 100644
--- a/src/us/Myles/DP/Plug.java
+++ b/src/us/Myles/DP/Plug.java
@@ -1,25 +1,24 @@
package us.Myles.DP;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.entity.Minecart;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryOpenEvent;
import org.bukkit.plugin.java.JavaPlugin;
public class Plug extends JavaPlugin implements Listener{
public void onEnable(){
Bukkit.getPluginManager().registerEvents(this, this);
}
@EventHandler
public void onOpen(InventoryOpenEvent e){
- System.out.println(e.getInventory().getHolder().getClass());
if(e.getPlayer().isInsideVehicle() && e.getInventory().getHolder() instanceof Minecart){
((Player) e.getPlayer()).sendMessage(ChatColor.RED + "You may not open Minecart Inventories while in a vehicle.");
System.out.println("[Alert] " + e.getPlayer().getName() + " just tried to use a duplication glitch.");
e.setCancelled(true);
}
}
}
| true | true | public void onOpen(InventoryOpenEvent e){
System.out.println(e.getInventory().getHolder().getClass());
if(e.getPlayer().isInsideVehicle() && e.getInventory().getHolder() instanceof Minecart){
((Player) e.getPlayer()).sendMessage(ChatColor.RED + "You may not open Minecart Inventories while in a vehicle.");
System.out.println("[Alert] " + e.getPlayer().getName() + " just tried to use a duplication glitch.");
e.setCancelled(true);
}
}
| public void onOpen(InventoryOpenEvent e){
if(e.getPlayer().isInsideVehicle() && e.getInventory().getHolder() instanceof Minecart){
((Player) e.getPlayer()).sendMessage(ChatColor.RED + "You may not open Minecart Inventories while in a vehicle.");
System.out.println("[Alert] " + e.getPlayer().getName() + " just tried to use a duplication glitch.");
e.setCancelled(true);
}
}
|
diff --git a/web-nutsNbolts/src/main/java/org/intalio/tempo/web/controller/SecuredController.java b/web-nutsNbolts/src/main/java/org/intalio/tempo/web/controller/SecuredController.java
index 541a485..34df623 100644
--- a/web-nutsNbolts/src/main/java/org/intalio/tempo/web/controller/SecuredController.java
+++ b/web-nutsNbolts/src/main/java/org/intalio/tempo/web/controller/SecuredController.java
@@ -1,84 +1,84 @@
/**
* Copyright (c) 2005-2008 Intalio inc.
*
* 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:
* Intalio inc. - initial API and implementation
*
* $Id: XFormsManager.java 2764 2006-03-16 18:34:41Z ozenzin $
* $Log:$
*/
package org.intalio.tempo.web.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.intalio.tempo.web.ApplicationState;
import org.intalio.tempo.web.Constants;
import org.intalio.tempo.web.User;
import org.springframework.validation.BindException;
import org.springframework.web.servlet.ModelAndView;
public class SecuredController extends UIController {
private static final Logger LOG = LogManager.getLogger(SecuredController.class);
@Override
protected final ModelAndView showForm(HttpServletRequest request, HttpServletResponse response, BindException errors)
throws Exception {
ModelAndView mav = Constants.REDIRECTION_TO_LOGIN;
ApplicationState state = getApplicationState(request);
User currentUser = state.getCurrentUser();
if (currentUser != null) {
if (_defaultAction == null) {
mav = securedShowForm(request, response, errors);
} else {
// Do default action
Action<Object> action = instantiateDefaultAction();
action.setRequest(request);
action.setResponse(response);
action.setCommand(getCommand(request));
action.setBindErrors(errors);
mav = action.doExecution();
}
}
fillAuthorization(request, mav);
- state.setPreviousAction(request.getRequestURL().toString());
+ state.setPreviousAction(request.getRequestURL().append("?").append(request.getQueryString()).toString());
return mav;
}
@Override
protected final ModelAndView processFormSubmission(HttpServletRequest request, HttpServletResponse response,
Object command, BindException errors) throws Exception {
ApplicationState state = getApplicationState(request);
User currentUser = state.getCurrentUser();
if (currentUser != null) {
return super.processFormSubmission(request, response, command, errors);
}
// save request position
state.setPreviousAction(request.getRequestURL().toString());
// redirect to login page
return Constants.REDIRECTION_TO_LOGIN;
}
protected ModelAndView securedShowForm(HttpServletRequest request, HttpServletResponse response,
BindException errors) throws Exception {
return null;
}
public static String getCurrentUserName(HttpServletRequest request) {
ApplicationState state = ApplicationState.getCurrentInstance(new HttpServletRequestWrapper(request));
if (state == null || state.getCurrentUser() == null) {
return "UnknownUser";
}
return state.getCurrentUser().getName();
}
}
| true | true | protected final ModelAndView showForm(HttpServletRequest request, HttpServletResponse response, BindException errors)
throws Exception {
ModelAndView mav = Constants.REDIRECTION_TO_LOGIN;
ApplicationState state = getApplicationState(request);
User currentUser = state.getCurrentUser();
if (currentUser != null) {
if (_defaultAction == null) {
mav = securedShowForm(request, response, errors);
} else {
// Do default action
Action<Object> action = instantiateDefaultAction();
action.setRequest(request);
action.setResponse(response);
action.setCommand(getCommand(request));
action.setBindErrors(errors);
mav = action.doExecution();
}
}
fillAuthorization(request, mav);
state.setPreviousAction(request.getRequestURL().toString());
return mav;
}
| protected final ModelAndView showForm(HttpServletRequest request, HttpServletResponse response, BindException errors)
throws Exception {
ModelAndView mav = Constants.REDIRECTION_TO_LOGIN;
ApplicationState state = getApplicationState(request);
User currentUser = state.getCurrentUser();
if (currentUser != null) {
if (_defaultAction == null) {
mav = securedShowForm(request, response, errors);
} else {
// Do default action
Action<Object> action = instantiateDefaultAction();
action.setRequest(request);
action.setResponse(response);
action.setCommand(getCommand(request));
action.setBindErrors(errors);
mav = action.doExecution();
}
}
fillAuthorization(request, mav);
state.setPreviousAction(request.getRequestURL().append("?").append(request.getQueryString()).toString());
return mav;
}
|
diff --git a/src/main/java/com/alexrnl/commons/arguments/Arguments.java b/src/main/java/com/alexrnl/commons/arguments/Arguments.java
index a855d5a..6b9acb8 100644
--- a/src/main/java/com/alexrnl/commons/arguments/Arguments.java
+++ b/src/main/java/com/alexrnl/commons/arguments/Arguments.java
@@ -1,116 +1,119 @@
package com.alexrnl.commons.arguments;
import java.io.PrintStream;
import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.logging.Logger;
import com.alexrnl.commons.utils.StringUtils;
import com.alexrnl.commons.utils.object.ReflectUtils;
/**
* Class which allow to parse string arguments and store them in a target object.
* @author Alex
*/
public class Arguments {
/** Logger */
private static Logger lg = Logger.getLogger(Arguments.class.getName());
/** The tab character */
private static final Character TAB = '\t';
/** The number of tabs between the name of the argument and their description */
private static final int NB_TABS_BEFORE_DESCRIPTION = 4;
/** The name of the program. */
private final String programName;
/** The object which holds the target */
private final Object target;
/** The list of parameters in the target */
private final SortedSet<Parameter> parameters;
/**
* Constructor #1.<br />
* @param programName
* the name of the program.
* @param target
* the object which holds the target.
*/
public Arguments (final String programName, final Object target) {
super();
this.programName = programName;
this.target = target;
this.parameters = retrieveParameters(target);
}
/**
* Parse and build a list with the parameters field marked with the {@link Param} annotation in
* the object specified.
* @param obj
* the object to parse for parameters.
* @return the list of parameters associated to this object.
*/
private static SortedSet<Parameter> retrieveParameters (final Object obj) {
final SortedSet<Parameter> params = new TreeSet<>();
for (final Field field : ReflectUtils.retrieveFields(obj.getClass(), Param.class)) {
field.setAccessible(true);
params.add(new Parameter(field, field.getAnnotation(Param.class)));
}
return params;
}
/**
* Parse the arguments and set the target in the target object.
* @param arguments
* the arguments to parse.
*/
public void parse (final String... arguments) {
parse(Arrays.asList(arguments));
}
/**
* Parse the arguments and set the target in the target object.
* @param arguments
* the arguments to parse.
*/
public void parse (final Iterable<String> arguments) {
// TODO
}
/**
* Display the parameter's usage on specified output.
* @param out
* the stream to use to display the parameters.
*/
public void usage (final PrintStream out) {
out.println(this);
}
/**
* Display the parameter's usage on the standard output.
*/
public void usage () {
usage(System.out);
}
@Override
public String toString () {
final StringBuilder usage = new StringBuilder(programName).append(" usage as follow:");
for (final Parameter param : parameters) {
- usage.append(TAB);
+ usage.append(StringUtils.NEW_LINE).append(TAB);
if (!param.isRequired()) {
usage.append('[');
} else {
usage.append(' ');
}
usage.append(" ").append(StringUtils.separateWith(", ", param.getNames()));
int nbTabs = NB_TABS_BEFORE_DESCRIPTION;
while (nbTabs-- > 0) {
usage.append(TAB);
}
usage.append(param.getDescription());
+ if (!param.isRequired()) {
+ usage.append(" ]");
+ }
}
return usage.toString();
}
}
| false | true | public String toString () {
final StringBuilder usage = new StringBuilder(programName).append(" usage as follow:");
for (final Parameter param : parameters) {
usage.append(TAB);
if (!param.isRequired()) {
usage.append('[');
} else {
usage.append(' ');
}
usage.append(" ").append(StringUtils.separateWith(", ", param.getNames()));
int nbTabs = NB_TABS_BEFORE_DESCRIPTION;
while (nbTabs-- > 0) {
usage.append(TAB);
}
usage.append(param.getDescription());
}
return usage.toString();
}
| public String toString () {
final StringBuilder usage = new StringBuilder(programName).append(" usage as follow:");
for (final Parameter param : parameters) {
usage.append(StringUtils.NEW_LINE).append(TAB);
if (!param.isRequired()) {
usage.append('[');
} else {
usage.append(' ');
}
usage.append(" ").append(StringUtils.separateWith(", ", param.getNames()));
int nbTabs = NB_TABS_BEFORE_DESCRIPTION;
while (nbTabs-- > 0) {
usage.append(TAB);
}
usage.append(param.getDescription());
if (!param.isRequired()) {
usage.append(" ]");
}
}
return usage.toString();
}
|
diff --git a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/TextField.java b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/TextField.java
index 1ed79fb75..55dbc172c 100644
--- a/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/TextField.java
+++ b/gdx/src/com/badlogic/gdx/scenes/scene2d/ui/TextField.java
@@ -1,890 +1,889 @@
/*******************************************************************************
* Copyright 2011 See AUTHORS file.
*
* 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.badlogic.gdx.scenes.scene2d.ui;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.graphics.g2d.BitmapFont.TextBounds;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.scenes.scene2d.Actor;
import com.badlogic.gdx.scenes.scene2d.Group;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.InputListener;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Clipboard;
import com.badlogic.gdx.utils.FloatArray;
import com.badlogic.gdx.utils.TimeUtils;
import com.badlogic.gdx.utils.Timer;
import com.badlogic.gdx.utils.Timer.Task;
/** A single-line text input field.
* <p>
* The preferred height of a text field is the height of the {@link TextFieldStyle#font} and {@link TextFieldStyle#background}.
* The preferred width of a text field is 150, a relatively arbitrary size.
* <p>
* The text field will copy the currently selected text when ctrl+c is pressed, and paste any text in the clipboard when ctrl+v is
* pressed. Clipboard functionality is provided via the {@link Clipboard} interface. Currently there are two standard
* implementations, one for the desktop and one for Android. The Android clipboard is a stub, as copy & pasting on Android is not
* supported yet.
* <p>
* The text field allows you to specify an {@link OnscreenKeyboard} for displaying a softkeyboard and piping all key events
* generated by the keyboard to the text field. There are two standard implementations, one for the desktop and one for Android.
* The desktop keyboard is a stub, as a softkeyboard is not needed on the desktop. The Android {@link OnscreenKeyboard}
* implementation will bring up the default IME.
* @author mzechner
* @author Nathan Sweet */
public class TextField extends Widget {
static private final char BACKSPACE = 8;
static private final char ENTER_DESKTOP = '\r';
static private final char ENTER_ANDROID = '\n';
static private final char TAB = '\t';
static private final char DELETE = 127;
static private final char BULLET = 149;
static private final Vector2 tmp1 = new Vector2();
static private final Vector2 tmp2 = new Vector2();
static private final Vector2 tmp3 = new Vector2();
TextFieldStyle style;
String text, messageText;
private CharSequence displayText;
int cursor;
private Clipboard clipboard;
TextFieldListener listener;
TextFieldFilter filter;
OnscreenKeyboard keyboard = new DefaultOnscreenKeyboard();
boolean focusTraversal = true;
boolean disabled;
boolean onlyFontChars = true;
private boolean passwordMode;
private StringBuilder passwordBuffer;
private final Rectangle fieldBounds = new Rectangle();
private final TextBounds textBounds = new TextBounds();
private final Rectangle scissor = new Rectangle();
float renderOffset, textOffset;
private int visibleTextStart, visibleTextEnd;
private final FloatArray glyphAdvances = new FloatArray();
final FloatArray glyphPositions = new FloatArray();
boolean cursorOn = true;
private float blinkTime = 0.32f;
long lastBlink;
boolean hasSelection;
int selectionStart;
private float selectionX, selectionWidth;
private char passwordCharacter = BULLET;
InputListener inputListener;
KeyRepeatTask keyRepeatTask = new KeyRepeatTask();
float keyRepeatInitialTime = 0.4f;
float keyRepeatTime = 0.1f;
boolean rightAligned;
int maxLength = 0;
public TextField (String text, Skin skin) {
this(text, skin.get(TextFieldStyle.class));
}
public TextField (String text, Skin skin, String styleName) {
this(text, skin.get(styleName, TextFieldStyle.class));
}
public TextField (String text, TextFieldStyle style) {
setStyle(style);
this.clipboard = Gdx.app.getClipboard();
setText(text);
setWidth(getPrefWidth());
setHeight(getPrefHeight());
initialize();
}
private void initialize () {
addListener(inputListener = new ClickListener() {
public void clicked (InputEvent event, float x, float y) {
if (getTapCount() > 1) setSelection(0, text.length());
}
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
if (!super.touchDown(event, x, y, pointer, button)) return false;
if (pointer == 0 && button != 0) return false;
if (disabled) return true;
clearSelection();
setCursorPosition(x);
selectionStart = cursor;
Stage stage = getStage();
if (stage != null) stage.setKeyboardFocus(TextField.this);
keyboard.show(true);
return true;
}
public void touchDragged (InputEvent event, float x, float y, int pointer) {
super.touchDragged(event, x, y, pointer);
lastBlink = 0;
cursorOn = false;
setCursorPosition(x);
hasSelection = true;
}
private void setCursorPosition (float x) {
lastBlink = 0;
cursorOn = false;
x -= renderOffset + textOffset;
for (int i = 0; i < glyphPositions.size; i++) {
if (glyphPositions.items[i] > x) {
cursor = Math.max(0, i - 1);
return;
}
}
cursor = Math.max(0, glyphPositions.size - 1);
}
public boolean keyDown (InputEvent event, int keycode) {
if (disabled) return false;
final BitmapFont font = style.font;
lastBlink = 0;
cursorOn = false;
Stage stage = getStage();
if (stage != null && stage.getKeyboardFocus() == TextField.this) {
boolean repeat = false;
boolean ctrl = Gdx.input.isKeyPressed(Keys.CONTROL_LEFT) || Gdx.input.isKeyPressed(Keys.CONTROL_RIGHT);
if (ctrl) {
// paste
if (keycode == Keys.V) {
paste();
return true;
}
// copy
if (keycode == Keys.C || keycode == Keys.INSERT) {
copy();
return true;
}
// cut
if (keycode == Keys.X || keycode == Keys.DEL) {
cut();
return true;
}
}
if (Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT)) {
// paste
if (keycode == Keys.INSERT) paste();
// cut
if (keycode == Keys.FORWARD_DEL) {
if (hasSelection) {
copy();
delete();
}
}
// selection
if (keycode == Keys.LEFT) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
while (--cursor > 0 && ctrl) {
char c = text.charAt(cursor);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
repeat = true;
}
if (keycode == Keys.RIGHT) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
int length = text.length();
while (++cursor < length && ctrl) {
char c = text.charAt(cursor - 1);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
repeat = true;
}
if (keycode == Keys.HOME) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
cursor = 0;
}
if (keycode == Keys.END) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
cursor = text.length();
}
cursor = Math.max(0, cursor);
cursor = Math.min(text.length(), cursor);
} else {
// cursor movement or other keys (kill selection)
if (keycode == Keys.LEFT) {
while (cursor-- > 1 && ctrl) {
char c = text.charAt(cursor - 1);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
clearSelection();
repeat = true;
}
if (keycode == Keys.RIGHT) {
int length = text.length();
while (++cursor < length && ctrl) {
char c = text.charAt(cursor - 1);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
clearSelection();
repeat = true;
}
if (keycode == Keys.HOME) {
cursor = 0;
clearSelection();
}
if (keycode == Keys.END) {
cursor = text.length();
clearSelection();
}
cursor = Math.max(0, cursor);
cursor = Math.min(text.length(), cursor);
}
if (repeat && (!keyRepeatTask.isScheduled() || keyRepeatTask.keycode != keycode)) {
keyRepeatTask.keycode = keycode;
keyRepeatTask.cancel();
Timer.schedule(keyRepeatTask, keyRepeatInitialTime, keyRepeatTime);
}
return true;
}
return false;
}
public boolean keyUp (InputEvent event, int keycode) {
if (disabled) return false;
keyRepeatTask.cancel();
return true;
}
public boolean keyTyped (InputEvent event, char character) {
if (disabled) return false;
final BitmapFont font = style.font;
Stage stage = getStage();
if (stage != null && stage.getKeyboardFocus() == TextField.this) {
if (character == BACKSPACE && (cursor > 0 || hasSelection)) {
if (!hasSelection) {
text = text.substring(0, cursor - 1) + text.substring(cursor);
updateDisplayText();
cursor--;
renderOffset = 0;
} else {
delete();
}
}
if (character == DELETE) {
if (cursor < text.length() || hasSelection) {
if (!hasSelection) {
text = text.substring(0, cursor) + text.substring(cursor + 1);
updateDisplayText();
} else {
delete();
}
}
- return true;
}
if (character != ENTER_DESKTOP && character != ENTER_ANDROID) {
if (filter != null && !filter.acceptChar(TextField.this, character)) return true;
}
if ((character == TAB || character == ENTER_ANDROID) && focusTraversal)
next(Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT));
if (font.containsCharacter(character)) {
if (maxLength > 0 && text.length() + 1 > maxLength) {
return true;
}
if (!hasSelection) {
text = text.substring(0, cursor) + character + text.substring(cursor, text.length());
updateDisplayText();
cursor++;
} else {
int minIndex = Math.min(cursor, selectionStart);
int maxIndex = Math.max(cursor, selectionStart);
text = (minIndex > 0 ? text.substring(0, minIndex) : "")
+ (maxIndex < text.length() ? text.substring(maxIndex, text.length()) : "");
cursor = minIndex;
text = text.substring(0, cursor) + character + text.substring(cursor, text.length());
updateDisplayText();
cursor++;
clearSelection();
}
}
if (listener != null) listener.keyTyped(TextField.this, character);
return true;
} else
return false;
}
});
}
public void setMaxLength (int maxLength) {
this.maxLength = maxLength;
}
public int getMaxLength () {
return this.maxLength;
}
/** When false, text set by {@link #setText(String)} may contain characters not in the font, a space will be displayed instead.
* When true (the default), characters not in the font are stripped by setText. Characters not in the font are always stripped
* when typed or pasted. */
public void setOnlyFontChars (boolean onlyFontChars) {
this.onlyFontChars = onlyFontChars;
}
public void setStyle (TextFieldStyle style) {
if (style == null) throw new IllegalArgumentException("style cannot be null.");
this.style = style;
invalidateHierarchy();
}
/** Sets the password character for the text field. The character must be present in the {@link BitmapFont} */
public void setPasswordCharacter (char passwordCharacter) {
this.passwordCharacter = passwordCharacter;
if (passwordMode) updateDisplayText();
}
/** Returns the text field's style. Modifying the returned style may not have an effect until {@link #setStyle(TextFieldStyle)}
* is called. */
public TextFieldStyle getStyle () {
return style;
}
private void calculateOffsets () {
float visibleWidth = getWidth();
if (style.background != null) visibleWidth -= style.background.getLeftWidth() + style.background.getRightWidth();
// Check if the cursor has gone out the left or right side of the visible area and adjust renderoffset.
float position = glyphPositions.get(cursor);
float distance = position - Math.abs(renderOffset);
if (distance <= 0) {
if (cursor > 0)
renderOffset = -glyphPositions.get(cursor - 1);
else
renderOffset = 0;
} else if (distance > visibleWidth) {
renderOffset -= distance - visibleWidth;
}
// calculate first visible char based on render offset
visibleTextStart = 0;
textOffset = 0;
float start = Math.abs(renderOffset);
int len = glyphPositions.size;
float startPos = 0;
for (int i = 0; i < len; i++) {
if (glyphPositions.items[i] >= start) {
visibleTextStart = i;
startPos = glyphPositions.items[i];
textOffset = startPos - start;
break;
}
}
// calculate last visible char based on visible width and render offset
visibleTextEnd = Math.min(displayText.length(), cursor + 1);
for (; visibleTextEnd <= displayText.length(); visibleTextEnd++) {
if (glyphPositions.items[visibleTextEnd] - startPos > visibleWidth) break;
}
visibleTextEnd = Math.max(0, visibleTextEnd - 1);
// calculate selection x position and width
if (hasSelection) {
int minIndex = Math.min(cursor, selectionStart);
int maxIndex = Math.max(cursor, selectionStart);
float minX = Math.max(glyphPositions.get(minIndex), startPos);
float maxX = Math.min(glyphPositions.get(maxIndex), glyphPositions.get(visibleTextEnd));
selectionX = minX;
selectionWidth = maxX - minX;
}
if (rightAligned) {
textOffset = visibleWidth - (glyphPositions.items[visibleTextEnd] - startPos);
if (hasSelection) selectionX += textOffset;
}
}
@Override
public void draw (SpriteBatch batch, float parentAlpha) {
Stage stage = getStage();
boolean focused = stage != null && stage.getKeyboardFocus() == this;
final BitmapFont font = style.font;
final Color fontColor = (disabled && style.disabledFontColor != null) ? style.disabledFontColor
: ((focused && style.focusedFontColor != null) ? style.focusedFontColor : style.fontColor);
final Drawable selection = style.selection;
final Drawable cursorPatch = style.cursor;
final Drawable background = (disabled && style.disabledBackground != null) ? style.disabledBackground
: ((focused && style.focusedBackground != null) ? style.focusedBackground : style.background);
Color color = getColor();
float x = getX();
float y = getY();
float width = getWidth();
float height = getHeight();
float textY = textBounds.height / 2 + font.getDescent();
batch.setColor(color.r, color.g, color.b, color.a * parentAlpha);
float bgLeftWidth = 0;
if (background != null) {
background.draw(batch, x, y, width, height);
bgLeftWidth = background.getLeftWidth();
float bottom = background.getBottomHeight();
textY = (int)(textY + (height - background.getTopHeight() - bottom) / 2 + bottom);
} else
textY = (int)(textY + height / 2);
calculateOffsets();
if (focused && hasSelection && selection != null) {
selection.draw(batch, x + selectionX + bgLeftWidth + renderOffset, y + textY - textBounds.height - font.getDescent(),
selectionWidth, textBounds.height + font.getDescent() / 2);
}
float yOffset = font.isFlipped() ? -textBounds.height : 0;
if (displayText.length() == 0) {
if (!focused && messageText != null) {
if (style.messageFontColor != null) {
font.setColor(style.messageFontColor.r, style.messageFontColor.g, style.messageFontColor.b,
style.messageFontColor.a * parentAlpha);
} else
font.setColor(0.7f, 0.7f, 0.7f, parentAlpha);
BitmapFont messageFont = style.messageFont != null ? style.messageFont : font;
messageFont.draw(batch, messageText, x + bgLeftWidth, y + textY + yOffset);
}
} else {
font.setColor(fontColor.r, fontColor.g, fontColor.b, fontColor.a * parentAlpha);
font.draw(batch, displayText, x + bgLeftWidth + textOffset, y + textY + yOffset, visibleTextStart, visibleTextEnd);
}
if (focused && !disabled) {
blink();
if (cursorOn && cursorPatch != null) {
cursorPatch.draw(batch, x + bgLeftWidth + textOffset + glyphPositions.get(cursor)
- glyphPositions.items[visibleTextStart] - 1, y + textY - textBounds.height - font.getDescent(),
cursorPatch.getMinWidth(), textBounds.height + font.getDescent() / 2);
}
}
}
void updateDisplayText () {
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
buffer.append(style.font.containsCharacter(c) ? c : ' ');
}
String text = buffer.toString();
if (passwordMode && style.font.containsCharacter(passwordCharacter)) {
if (passwordBuffer == null) passwordBuffer = new StringBuilder(text.length());
if (passwordBuffer.length() > text.length()) //
passwordBuffer.setLength(text.length());
else {
for (int i = passwordBuffer.length(), n = text.length(); i < n; i++)
passwordBuffer.append(passwordCharacter);
}
displayText = passwordBuffer;
} else
displayText = text;
style.font.computeGlyphAdvancesAndPositions(displayText, glyphAdvances, glyphPositions);
if (selectionStart > text.length()) selectionStart = text.length();
}
private void blink () {
long time = TimeUtils.nanoTime();
if ((time - lastBlink) / 1000000000.0f > blinkTime) {
cursorOn = !cursorOn;
lastBlink = time;
}
}
/** Copies the contents of this TextField to the {@link Clipboard} implementation set on this TextField. */
public void copy () {
if (hasSelection) {
int minIndex = Math.min(cursor, selectionStart);
int maxIndex = Math.max(cursor, selectionStart);
clipboard.setContents(text.substring(minIndex, maxIndex));
}
}
/** Copies the selected contents of this TextField to the {@link Clipboard} implementation set on this TextField, then removes
* it. */
public void cut () {
if (hasSelection) {
copy();
delete();
}
}
/** Pastes the content of the {@link Clipboard} implementation set on this Textfield to this TextField. */
void paste () {
String content = clipboard.getContents();
if (content != null) {
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < content.length(); i++) {
if (maxLength > 0 && text.length() + buffer.length() + 1 > maxLength) break;
char c = content.charAt(i);
if (!style.font.containsCharacter(c)) continue;
if (filter != null && !filter.acceptChar(this, c)) continue;
buffer.append(c);
}
content = buffer.toString();
if (!hasSelection) {
text = text.substring(0, cursor) + content + text.substring(cursor, text.length());
updateDisplayText();
cursor += content.length();
} else {
int minIndex = Math.min(cursor, selectionStart);
int maxIndex = Math.max(cursor, selectionStart);
text = (minIndex > 0 ? text.substring(0, minIndex) : "")
+ (maxIndex < text.length() ? text.substring(maxIndex, text.length()) : "");
cursor = minIndex;
text = text.substring(0, cursor) + content + text.substring(cursor, text.length());
updateDisplayText();
cursor = minIndex + content.length();
clearSelection();
}
}
}
void delete () {
int minIndex = Math.min(cursor, selectionStart);
int maxIndex = Math.max(cursor, selectionStart);
text = (minIndex > 0 ? text.substring(0, minIndex) : "")
+ (maxIndex < text.length() ? text.substring(maxIndex, text.length()) : "");
updateDisplayText();
cursor = minIndex;
clearSelection();
}
/** Focuses the next TextField. If none is found, the keyboard is hidden. Does nothing if the text field is not in a stage.
* @param up If true, the TextField with the same or next smallest y coordinate is found, else the next highest. */
public void next (boolean up) {
Stage stage = getStage();
if (stage == null) return;
getParent().localToStageCoordinates(tmp1.set(getX(), getY()));
TextField textField = findNextTextField(stage.getActors(), null, tmp2, tmp1, up);
if (textField == null) { // Try to wrap around.
if (up)
tmp1.set(Float.MIN_VALUE, Float.MIN_VALUE);
else
tmp1.set(Float.MAX_VALUE, Float.MAX_VALUE);
textField = findNextTextField(getStage().getActors(), null, tmp2, tmp1, up);
}
if (textField != null)
stage.setKeyboardFocus(textField);
else
Gdx.input.setOnscreenKeyboardVisible(false);
}
private TextField findNextTextField (Array<Actor> actors, TextField best, Vector2 bestCoords, Vector2 currentCoords, boolean up) {
for (int i = 0, n = actors.size; i < n; i++) {
Actor actor = actors.get(i);
if (actor == this) continue;
if (actor instanceof TextField) {
TextField textField = (TextField)actor;
if (textField.isDisabled() || !textField.focusTraversal) continue;
Vector2 actorCoords = actor.getParent().localToStageCoordinates(tmp3.set(actor.getX(), actor.getY()));
if ((actorCoords.y < currentCoords.y || (actorCoords.y == currentCoords.y && actorCoords.x > currentCoords.x)) ^ up) {
if (best == null
|| (actorCoords.y > bestCoords.y || (actorCoords.y == bestCoords.y && actorCoords.x < bestCoords.x)) ^ up) {
best = (TextField)actor;
bestCoords.set(actorCoords);
}
}
} else if (actor instanceof Group)
best = findNextTextField(((Group)actor).getChildren(), best, bestCoords, currentCoords, up);
}
return best;
}
/** @param listener May be null. */
public void setTextFieldListener (TextFieldListener listener) {
this.listener = listener;
}
/** @param filter May be null. */
public void setTextFieldFilter (TextFieldFilter filter) {
this.filter = filter;
}
/** If true (the default), tab/shift+tab will move to the next text field. */
public void setFocusTraversal (boolean focusTraversal) {
this.focusTraversal = focusTraversal;
}
/** @return May be null. */
public String getMessageText () {
return messageText;
}
/** Sets the text that will be drawn in the text field if no text has been entered.
* @param messageText may be null. */
public void setMessageText (String messageText) {
this.messageText = messageText;
}
public void setText (String text) {
if (text == null) throw new IllegalArgumentException("text cannot be null.");
BitmapFont font = style.font;
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < text.length(); i++) {
if (maxLength > 0 && buffer.length() + 1 > maxLength) break;
char c = text.charAt(i);
if (onlyFontChars && !style.font.containsCharacter(c)) continue;
if (filter != null && !filter.acceptChar(this, c)) continue;
buffer.append(c);
}
this.text = buffer.toString();
updateDisplayText();
cursor = 0;
clearSelection();
textBounds.set(font.getBounds(displayText));
textBounds.height -= font.getDescent() * 2;
font.computeGlyphAdvancesAndPositions(displayText, glyphAdvances, glyphPositions);
}
/** @return Never null, might be an empty string. */
public String getText () {
return text;
}
/** Sets the selected text. */
public void setSelection (int selectionStart, int selectionEnd) {
if (selectionStart < 0) throw new IllegalArgumentException("selectionStart must be >= 0");
if (selectionEnd < 0) throw new IllegalArgumentException("selectionEnd must be >= 0");
selectionStart = Math.min(text.length(), selectionStart);
selectionEnd = Math.min(text.length(), selectionEnd);
if (selectionEnd == selectionStart) {
clearSelection();
return;
}
if (selectionEnd < selectionStart) {
int temp = selectionEnd;
selectionEnd = selectionStart;
selectionStart = temp;
}
hasSelection = true;
this.selectionStart = selectionStart;
cursor = selectionEnd;
}
public void selectAll () {
setSelection(0, text.length());
}
public void clearSelection () {
hasSelection = false;
}
/** Sets the cursor position and clears any selection. */
public void setCursorPosition (int cursorPosition) {
if (cursorPosition < 0) throw new IllegalArgumentException("cursorPosition must be >= 0");
clearSelection();
cursor = Math.min(cursorPosition, text.length());
}
public int getCursorPosition () {
return cursor;
}
/** Default is an instance of {@link DefaultOnscreenKeyboard}. */
public OnscreenKeyboard getOnscreenKeyboard () {
return keyboard;
}
public void setOnscreenKeyboard (OnscreenKeyboard keyboard) {
this.keyboard = keyboard;
}
public void setClipboard (Clipboard clipboard) {
this.clipboard = clipboard;
}
public float getPrefWidth () {
return 150;
}
public float getPrefHeight () {
float prefHeight = textBounds.height;
if (style.background != null) {
prefHeight = Math.max(prefHeight + style.background.getBottomHeight() + style.background.getTopHeight(),
style.background.getMinHeight());
}
return prefHeight;
}
public void setRightAligned (boolean rightAligned) {
this.rightAligned = rightAligned;
}
/** If true, the text in this text field will be shown as bullet characters. The font must have character 149 or this will have
* no affect. */
public void setPasswordMode (boolean passwordMode) {
this.passwordMode = passwordMode;
updateDisplayText();
}
public void setBlinkTime (float blinkTime) {
this.blinkTime = blinkTime;
}
public void setDisabled (boolean disabled) {
this.disabled = disabled;
}
public boolean isDisabled () {
return disabled;
}
public boolean isPasswordMode () {
return passwordMode;
}
public TextFieldFilter getTextFieldFilter () {
return filter;
}
class KeyRepeatTask extends Task {
int keycode;
public void run () {
inputListener.keyDown(null, keycode);
}
}
/** Interface for listening to typed characters.
* @author mzechner */
static public interface TextFieldListener {
public void keyTyped (TextField textField, char key);
}
/** Interface for filtering characters entered into the text field.
* @author mzechner */
static public interface TextFieldFilter {
/** @param textField
* @param key
* @return whether to accept the character */
public boolean acceptChar (TextField textField, char key);
static public class DigitsOnlyFilter implements TextFieldFilter {
@Override
public boolean acceptChar (TextField textField, char key) {
return Character.isDigit(key);
}
}
}
/** An interface for onscreen keyboards. Can invoke the default keyboard or render your own keyboard!
* @author mzechner */
static public interface OnscreenKeyboard {
public void show (boolean visible);
}
/** The default {@link OnscreenKeyboard} used by all {@link TextField} instances. Just uses
* {@link Input#setOnscreenKeyboardVisible(boolean)} as appropriate. Might overlap your actual rendering, so use with care!
* @author mzechner */
static public class DefaultOnscreenKeyboard implements OnscreenKeyboard {
@Override
public void show (boolean visible) {
Gdx.input.setOnscreenKeyboardVisible(visible);
}
}
/** The style for a text field, see {@link TextField}.
* @author mzechner
* @author Nathan Sweet */
static public class TextFieldStyle {
public BitmapFont font;
public Color fontColor, focusedFontColor, disabledFontColor;
/** Optional. */
public Drawable background, focusedBackground, disabledBackground, cursor, selection;
/** Optional. */
public BitmapFont messageFont;
/** Optional. */
public Color messageFontColor;
public TextFieldStyle () {
}
public TextFieldStyle (BitmapFont font, Color fontColor, Drawable cursor, Drawable selection, Drawable background) {
this.background = background;
this.cursor = cursor;
this.font = font;
this.fontColor = fontColor;
this.selection = selection;
}
public TextFieldStyle (TextFieldStyle style) {
this.messageFont = style.messageFont;
if (style.messageFontColor != null) this.messageFontColor = new Color(style.messageFontColor);
this.background = style.background;
this.focusedBackground = style.focusedBackground;
this.disabledBackground = style.disabledBackground;
this.cursor = style.cursor;
this.font = style.font;
if (style.fontColor != null) this.fontColor = new Color(style.fontColor);
if (style.focusedFontColor != null) this.focusedFontColor = new Color(style.focusedFontColor);
if (style.disabledFontColor != null) this.disabledFontColor = new Color(style.disabledFontColor);
this.selection = style.selection;
}
}
}
| true | true | private void initialize () {
addListener(inputListener = new ClickListener() {
public void clicked (InputEvent event, float x, float y) {
if (getTapCount() > 1) setSelection(0, text.length());
}
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
if (!super.touchDown(event, x, y, pointer, button)) return false;
if (pointer == 0 && button != 0) return false;
if (disabled) return true;
clearSelection();
setCursorPosition(x);
selectionStart = cursor;
Stage stage = getStage();
if (stage != null) stage.setKeyboardFocus(TextField.this);
keyboard.show(true);
return true;
}
public void touchDragged (InputEvent event, float x, float y, int pointer) {
super.touchDragged(event, x, y, pointer);
lastBlink = 0;
cursorOn = false;
setCursorPosition(x);
hasSelection = true;
}
private void setCursorPosition (float x) {
lastBlink = 0;
cursorOn = false;
x -= renderOffset + textOffset;
for (int i = 0; i < glyphPositions.size; i++) {
if (glyphPositions.items[i] > x) {
cursor = Math.max(0, i - 1);
return;
}
}
cursor = Math.max(0, glyphPositions.size - 1);
}
public boolean keyDown (InputEvent event, int keycode) {
if (disabled) return false;
final BitmapFont font = style.font;
lastBlink = 0;
cursorOn = false;
Stage stage = getStage();
if (stage != null && stage.getKeyboardFocus() == TextField.this) {
boolean repeat = false;
boolean ctrl = Gdx.input.isKeyPressed(Keys.CONTROL_LEFT) || Gdx.input.isKeyPressed(Keys.CONTROL_RIGHT);
if (ctrl) {
// paste
if (keycode == Keys.V) {
paste();
return true;
}
// copy
if (keycode == Keys.C || keycode == Keys.INSERT) {
copy();
return true;
}
// cut
if (keycode == Keys.X || keycode == Keys.DEL) {
cut();
return true;
}
}
if (Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT)) {
// paste
if (keycode == Keys.INSERT) paste();
// cut
if (keycode == Keys.FORWARD_DEL) {
if (hasSelection) {
copy();
delete();
}
}
// selection
if (keycode == Keys.LEFT) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
while (--cursor > 0 && ctrl) {
char c = text.charAt(cursor);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
repeat = true;
}
if (keycode == Keys.RIGHT) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
int length = text.length();
while (++cursor < length && ctrl) {
char c = text.charAt(cursor - 1);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
repeat = true;
}
if (keycode == Keys.HOME) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
cursor = 0;
}
if (keycode == Keys.END) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
cursor = text.length();
}
cursor = Math.max(0, cursor);
cursor = Math.min(text.length(), cursor);
} else {
// cursor movement or other keys (kill selection)
if (keycode == Keys.LEFT) {
while (cursor-- > 1 && ctrl) {
char c = text.charAt(cursor - 1);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
clearSelection();
repeat = true;
}
if (keycode == Keys.RIGHT) {
int length = text.length();
while (++cursor < length && ctrl) {
char c = text.charAt(cursor - 1);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
clearSelection();
repeat = true;
}
if (keycode == Keys.HOME) {
cursor = 0;
clearSelection();
}
if (keycode == Keys.END) {
cursor = text.length();
clearSelection();
}
cursor = Math.max(0, cursor);
cursor = Math.min(text.length(), cursor);
}
if (repeat && (!keyRepeatTask.isScheduled() || keyRepeatTask.keycode != keycode)) {
keyRepeatTask.keycode = keycode;
keyRepeatTask.cancel();
Timer.schedule(keyRepeatTask, keyRepeatInitialTime, keyRepeatTime);
}
return true;
}
return false;
}
public boolean keyUp (InputEvent event, int keycode) {
if (disabled) return false;
keyRepeatTask.cancel();
return true;
}
public boolean keyTyped (InputEvent event, char character) {
if (disabled) return false;
final BitmapFont font = style.font;
Stage stage = getStage();
if (stage != null && stage.getKeyboardFocus() == TextField.this) {
if (character == BACKSPACE && (cursor > 0 || hasSelection)) {
if (!hasSelection) {
text = text.substring(0, cursor - 1) + text.substring(cursor);
updateDisplayText();
cursor--;
renderOffset = 0;
} else {
delete();
}
}
if (character == DELETE) {
if (cursor < text.length() || hasSelection) {
if (!hasSelection) {
text = text.substring(0, cursor) + text.substring(cursor + 1);
updateDisplayText();
} else {
delete();
}
}
return true;
}
if (character != ENTER_DESKTOP && character != ENTER_ANDROID) {
if (filter != null && !filter.acceptChar(TextField.this, character)) return true;
}
if ((character == TAB || character == ENTER_ANDROID) && focusTraversal)
next(Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT));
if (font.containsCharacter(character)) {
if (maxLength > 0 && text.length() + 1 > maxLength) {
return true;
}
if (!hasSelection) {
text = text.substring(0, cursor) + character + text.substring(cursor, text.length());
updateDisplayText();
cursor++;
} else {
int minIndex = Math.min(cursor, selectionStart);
int maxIndex = Math.max(cursor, selectionStart);
text = (minIndex > 0 ? text.substring(0, minIndex) : "")
+ (maxIndex < text.length() ? text.substring(maxIndex, text.length()) : "");
cursor = minIndex;
text = text.substring(0, cursor) + character + text.substring(cursor, text.length());
updateDisplayText();
cursor++;
clearSelection();
}
}
if (listener != null) listener.keyTyped(TextField.this, character);
return true;
} else
return false;
}
});
}
| private void initialize () {
addListener(inputListener = new ClickListener() {
public void clicked (InputEvent event, float x, float y) {
if (getTapCount() > 1) setSelection(0, text.length());
}
public boolean touchDown (InputEvent event, float x, float y, int pointer, int button) {
if (!super.touchDown(event, x, y, pointer, button)) return false;
if (pointer == 0 && button != 0) return false;
if (disabled) return true;
clearSelection();
setCursorPosition(x);
selectionStart = cursor;
Stage stage = getStage();
if (stage != null) stage.setKeyboardFocus(TextField.this);
keyboard.show(true);
return true;
}
public void touchDragged (InputEvent event, float x, float y, int pointer) {
super.touchDragged(event, x, y, pointer);
lastBlink = 0;
cursorOn = false;
setCursorPosition(x);
hasSelection = true;
}
private void setCursorPosition (float x) {
lastBlink = 0;
cursorOn = false;
x -= renderOffset + textOffset;
for (int i = 0; i < glyphPositions.size; i++) {
if (glyphPositions.items[i] > x) {
cursor = Math.max(0, i - 1);
return;
}
}
cursor = Math.max(0, glyphPositions.size - 1);
}
public boolean keyDown (InputEvent event, int keycode) {
if (disabled) return false;
final BitmapFont font = style.font;
lastBlink = 0;
cursorOn = false;
Stage stage = getStage();
if (stage != null && stage.getKeyboardFocus() == TextField.this) {
boolean repeat = false;
boolean ctrl = Gdx.input.isKeyPressed(Keys.CONTROL_LEFT) || Gdx.input.isKeyPressed(Keys.CONTROL_RIGHT);
if (ctrl) {
// paste
if (keycode == Keys.V) {
paste();
return true;
}
// copy
if (keycode == Keys.C || keycode == Keys.INSERT) {
copy();
return true;
}
// cut
if (keycode == Keys.X || keycode == Keys.DEL) {
cut();
return true;
}
}
if (Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT)) {
// paste
if (keycode == Keys.INSERT) paste();
// cut
if (keycode == Keys.FORWARD_DEL) {
if (hasSelection) {
copy();
delete();
}
}
// selection
if (keycode == Keys.LEFT) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
while (--cursor > 0 && ctrl) {
char c = text.charAt(cursor);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
repeat = true;
}
if (keycode == Keys.RIGHT) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
int length = text.length();
while (++cursor < length && ctrl) {
char c = text.charAt(cursor - 1);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
repeat = true;
}
if (keycode == Keys.HOME) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
cursor = 0;
}
if (keycode == Keys.END) {
if (!hasSelection) {
selectionStart = cursor;
hasSelection = true;
}
cursor = text.length();
}
cursor = Math.max(0, cursor);
cursor = Math.min(text.length(), cursor);
} else {
// cursor movement or other keys (kill selection)
if (keycode == Keys.LEFT) {
while (cursor-- > 1 && ctrl) {
char c = text.charAt(cursor - 1);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
clearSelection();
repeat = true;
}
if (keycode == Keys.RIGHT) {
int length = text.length();
while (++cursor < length && ctrl) {
char c = text.charAt(cursor - 1);
if (c >= 'A' && c <= 'Z') continue;
if (c >= 'a' && c <= 'z') continue;
if (c >= '0' && c <= '9') continue;
break;
}
clearSelection();
repeat = true;
}
if (keycode == Keys.HOME) {
cursor = 0;
clearSelection();
}
if (keycode == Keys.END) {
cursor = text.length();
clearSelection();
}
cursor = Math.max(0, cursor);
cursor = Math.min(text.length(), cursor);
}
if (repeat && (!keyRepeatTask.isScheduled() || keyRepeatTask.keycode != keycode)) {
keyRepeatTask.keycode = keycode;
keyRepeatTask.cancel();
Timer.schedule(keyRepeatTask, keyRepeatInitialTime, keyRepeatTime);
}
return true;
}
return false;
}
public boolean keyUp (InputEvent event, int keycode) {
if (disabled) return false;
keyRepeatTask.cancel();
return true;
}
public boolean keyTyped (InputEvent event, char character) {
if (disabled) return false;
final BitmapFont font = style.font;
Stage stage = getStage();
if (stage != null && stage.getKeyboardFocus() == TextField.this) {
if (character == BACKSPACE && (cursor > 0 || hasSelection)) {
if (!hasSelection) {
text = text.substring(0, cursor - 1) + text.substring(cursor);
updateDisplayText();
cursor--;
renderOffset = 0;
} else {
delete();
}
}
if (character == DELETE) {
if (cursor < text.length() || hasSelection) {
if (!hasSelection) {
text = text.substring(0, cursor) + text.substring(cursor + 1);
updateDisplayText();
} else {
delete();
}
}
}
if (character != ENTER_DESKTOP && character != ENTER_ANDROID) {
if (filter != null && !filter.acceptChar(TextField.this, character)) return true;
}
if ((character == TAB || character == ENTER_ANDROID) && focusTraversal)
next(Gdx.input.isKeyPressed(Keys.SHIFT_LEFT) || Gdx.input.isKeyPressed(Keys.SHIFT_RIGHT));
if (font.containsCharacter(character)) {
if (maxLength > 0 && text.length() + 1 > maxLength) {
return true;
}
if (!hasSelection) {
text = text.substring(0, cursor) + character + text.substring(cursor, text.length());
updateDisplayText();
cursor++;
} else {
int minIndex = Math.min(cursor, selectionStart);
int maxIndex = Math.max(cursor, selectionStart);
text = (minIndex > 0 ? text.substring(0, minIndex) : "")
+ (maxIndex < text.length() ? text.substring(maxIndex, text.length()) : "");
cursor = minIndex;
text = text.substring(0, cursor) + character + text.substring(cursor, text.length());
updateDisplayText();
cursor++;
clearSelection();
}
}
if (listener != null) listener.keyTyped(TextField.this, character);
return true;
} else
return false;
}
});
}
|
diff --git a/omod/src/main/java/org/openmrs/module/errorlogging/web/controller/ManageErrorLoggingController.java b/omod/src/main/java/org/openmrs/module/errorlogging/web/controller/ManageErrorLoggingController.java
index c0298fe..56f49eb 100644
--- a/omod/src/main/java/org/openmrs/module/errorlogging/web/controller/ManageErrorLoggingController.java
+++ b/omod/src/main/java/org/openmrs/module/errorlogging/web/controller/ManageErrorLoggingController.java
@@ -1,97 +1,100 @@
/**
* 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.module.errorlogging.web.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.GlobalProperty;
import org.openmrs.api.context.Context;
import org.openmrs.module.errorlogging.ErrorLoggingConstants;
import org.openmrs.web.WebConstants;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
/**
* The main controller.
*/
@Controller
public class ManageErrorLoggingController {
protected final Log log = LogFactory.getLog(getClass());
/**
* Displays the form to manage the errorlogging module
*
* @param model
*/
@RequestMapping(value = "/module/errorlogging/manage.form", method = RequestMethod.GET)
public void showForm(ModelMap model) {
String ignoredExceptions = getIgnoredExceptions();
if (ignoredExceptions != null) {
model.addAttribute("ignoredExceptions", ignoredExceptions);
} else {
model.addAttribute("ignoredExceptions", "");
}
}
@RequestMapping(value = "module/errorlogging/manage.form", method = RequestMethod.POST)
public ModelAndView processSubmit(@RequestParam(value = "exceptions", required = true) String ignoredExceprions,
ModelMap model, HttpServletRequest request) {
boolean successSave = saveIgnoredExceprions(ignoredExceprions);
HttpSession httpSession = request.getSession();
if (successSave) {
httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "errorlogging.ignredExceptions.successSaveMessage");
} else {
httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "errorlogging.ignredExceptions.errorSaveMessage");
}
return new ModelAndView("redirect:./manage.form");
}
/**
* Save errors that have to be ignored
*
* @param errors that have to be ignored
* @return true in the case of a successful saving, otherwise - false
*/
private boolean saveIgnoredExceprions(String errors) {
+ if (errors == null) {
+ return false;
+ }
GlobalProperty glProp = Context.getAdministrationService().getGlobalPropertyObject(
ErrorLoggingConstants.ERRROR_LOGGING_GP_IGNORED_EXCEPTION);
if (glProp != null) {
glProp.setPropertyValue(errors);
GlobalProperty saved = Context.getAdministrationService().saveGlobalProperty(glProp);
- if (saved != null && saved.getPropertyValue() != null && saved.getPropertyValue().equals(errors)) {
+ if (saved != null) {
return true;
}
- }
+ }
return false;
}
/**
* Get ignored exceptions
*
* @return string which include ignored exceptions
*/
private String getIgnoredExceptions() {
GlobalProperty glProp = Context.getAdministrationService().getGlobalPropertyObject(
ErrorLoggingConstants.ERRROR_LOGGING_GP_IGNORED_EXCEPTION);
if (glProp != null) {
return glProp.getPropertyValue();
}
return null;
}
}
| false | true | private boolean saveIgnoredExceprions(String errors) {
GlobalProperty glProp = Context.getAdministrationService().getGlobalPropertyObject(
ErrorLoggingConstants.ERRROR_LOGGING_GP_IGNORED_EXCEPTION);
if (glProp != null) {
glProp.setPropertyValue(errors);
GlobalProperty saved = Context.getAdministrationService().saveGlobalProperty(glProp);
if (saved != null && saved.getPropertyValue() != null && saved.getPropertyValue().equals(errors)) {
return true;
}
}
return false;
}
| private boolean saveIgnoredExceprions(String errors) {
if (errors == null) {
return false;
}
GlobalProperty glProp = Context.getAdministrationService().getGlobalPropertyObject(
ErrorLoggingConstants.ERRROR_LOGGING_GP_IGNORED_EXCEPTION);
if (glProp != null) {
glProp.setPropertyValue(errors);
GlobalProperty saved = Context.getAdministrationService().saveGlobalProperty(glProp);
if (saved != null) {
return true;
}
}
return false;
}
|
diff --git a/src/battleship/Player.java b/src/battleship/Player.java
index 1c10fd9..e5e6cb6 100644
--- a/src/battleship/Player.java
+++ b/src/battleship/Player.java
@@ -1,33 +1,33 @@
package battleship;
import java.util.ArrayList;
import entities.Aircraft;
import entities.Battleship;
import entities.Cruiser;
import entities.Destroyer;
import entities.Ship;
import entities.Submarine;
public class Player {
private ArrayList<Ship> shipList = new ArrayList<Ship>();
private String name;
public Player(String name) {
this.name = name;
try{
shipList.add(new Aircraft(1,1,Ship.HORIZONTAL));
shipList.add(new Battleship(1,1,Ship.HORIZONTAL));
shipList.add(new Battleship(1,1,Ship.VERTICAL));
shipList.add(new Submarine(1,1,Ship.HORIZONTAL));
shipList.add(new Cruiser(1,1,Ship.VERTICAL));
shipList.add(new Destroyer(1,1,Ship.HORIZONTAL));
shipList.add(new Destroyer(1,1,Ship.VERTICAL));
}
catch(Exception e)
{
- System.err.println("Ship instantiation error: ("+this.name+") : ");
+ System.err.println("Ship instantiation error ("+this.name+") : ");
e.printStackTrace();
}
}
}
| true | true | public Player(String name) {
this.name = name;
try{
shipList.add(new Aircraft(1,1,Ship.HORIZONTAL));
shipList.add(new Battleship(1,1,Ship.HORIZONTAL));
shipList.add(new Battleship(1,1,Ship.VERTICAL));
shipList.add(new Submarine(1,1,Ship.HORIZONTAL));
shipList.add(new Cruiser(1,1,Ship.VERTICAL));
shipList.add(new Destroyer(1,1,Ship.HORIZONTAL));
shipList.add(new Destroyer(1,1,Ship.VERTICAL));
}
catch(Exception e)
{
System.err.println("Ship instantiation error: ("+this.name+") : ");
e.printStackTrace();
}
}
| public Player(String name) {
this.name = name;
try{
shipList.add(new Aircraft(1,1,Ship.HORIZONTAL));
shipList.add(new Battleship(1,1,Ship.HORIZONTAL));
shipList.add(new Battleship(1,1,Ship.VERTICAL));
shipList.add(new Submarine(1,1,Ship.HORIZONTAL));
shipList.add(new Cruiser(1,1,Ship.VERTICAL));
shipList.add(new Destroyer(1,1,Ship.HORIZONTAL));
shipList.add(new Destroyer(1,1,Ship.VERTICAL));
}
catch(Exception e)
{
System.err.println("Ship instantiation error ("+this.name+") : ");
e.printStackTrace();
}
}
|
diff --git a/bundles/org.eclipse.team.cvs.ssh2/src/org/eclipse/team/internal/ccvs/ssh2/PServerSSH2ServerConnection.java b/bundles/org.eclipse.team.cvs.ssh2/src/org/eclipse/team/internal/ccvs/ssh2/PServerSSH2ServerConnection.java
index 86b77c9f2..9dcf54f4b 100644
--- a/bundles/org.eclipse.team.cvs.ssh2/src/org/eclipse/team/internal/ccvs/ssh2/PServerSSH2ServerConnection.java
+++ b/bundles/org.eclipse.team.cvs.ssh2/src/org/eclipse/team/internal/ccvs/ssh2/PServerSSH2ServerConnection.java
@@ -1,143 +1,143 @@
/*******************************************************************************
* Copyright (c) 2000, 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:
* Atsuhiko Yamanaka, JCraft,Inc. - initial API and implementation.
* IBM Corporation - ongoing maintenance
*******************************************************************************/
package org.eclipse.team.internal.ccvs.ssh2;
import java.io.*;
import java.util.Properties;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.team.internal.ccvs.core.*;
import org.eclipse.team.internal.ccvs.core.connection.CVSAuthenticationException;
import org.eclipse.team.internal.ccvs.core.connection.CVSRepositoryLocation;
import com.jcraft.jsch.*;
public class PServerSSH2ServerConnection implements IServerConnection {
private ICVSRepositoryLocation location;
private String password;
private Session session;
private static int localport = 2403;
private IServerConnection psc = null;
protected PServerSSH2ServerConnection(ICVSRepositoryLocation location, String password) {
this.location = location;
this.password = password;
}
public void close() throws IOException {
psc.close();
}
public InputStream getInputStream() {
return psc.getInputStream();
}
public OutputStream getOutputStream() {
return psc.getOutputStream();
}
public void open(IProgressMonitor monitor) throws IOException, CVSAuthenticationException {
monitor.subTask("PServerSSH2ServerConnection.open"); //$NON-NLS-1$
monitor.worked(1);
String cvs_root = location.getRootDirectory();
int cvs_port = location.getPort();
if (cvs_port == 0)
cvs_port = 2401;
String cvs_host = location.getHost();
String ssh_host = cvs_host;
String ssh_user = location.getUsername();
String host = cvs_host;
if (host.indexOf('@') != -1) {
cvs_host = host.substring(host.lastIndexOf('@') + 1);
host = host.substring(0, host.lastIndexOf('@'));
if (host.indexOf('@') != -1) {
ssh_host = host.substring(host.lastIndexOf('@') + 1);
if (ssh_host.length() == 0)
ssh_host = cvs_host;
ssh_user = host.substring(0, host.lastIndexOf('@'));
} else {
ssh_host = host;
}
}
int ssh_port = 0;
if (ssh_host.indexOf('#') != -1) {
try {
ssh_port = Integer.parseInt(ssh_host.substring(ssh_host.lastIndexOf('#') + 1));
ssh_host = ssh_host.substring(0, ssh_host.lastIndexOf('#'));
} catch (Exception e) {
}
}
int lport = cvs_port;
String rhost = (cvs_host.equals(ssh_host) ? "localhost" : cvs_host); //$NON-NLS-1$
int rport = cvs_port;
// ssh -L lport:rhost:rport ssh_user@ssh_host
int retry = 1;
while (true) {
try {
session = JSchSession.getSession(location, ssh_user, "", ssh_host, ssh_port, monitor).getSession(); //$NON-NLS-1$
String[] list = session.getPortForwardingL();
String name = ":" + rhost + ":" + rport; //$NON-NLS-1$ //$NON-NLS-2$
boolean done = false;
for (int i = 0; i < list.length; i++) {
if (list[i].endsWith(name)) {
try {
String foo = list[i].substring(0, list[i].indexOf(':'));
lport = Integer.parseInt(foo);
} catch (Exception ee) {
}
done = true;
break;
}
}
if (!done) {
lport = localport++;
session.setPortForwardingL(lport, rhost, rport);
}
} catch (JSchException ee) {
retry--;
if(retry<0){
throw new CVSAuthenticationException(CVSSSH2Messages.CVSSSH2ServerConnection_3, CVSAuthenticationException.NO_RETRY);
}
- if(session.isConnected()){
+ if(session != null && session.isConnected()){
session.disconnect();
}
continue;
}
break;
}
// password for location will be over-written in JSchSession ;-<
((CVSRepositoryLocation)location).setPassword(password);
// CVSROOT=":pserver:localhost:"+lport+""cvs_root
try {
Properties prop = new Properties();
prop.put("connection", "pserver"); //$NON-NLS-1$ //$NON-NLS-2$
prop.put("user", location.getUsername()); //$NON-NLS-1$
prop.put("password", password); //$NON-NLS-1$
prop.put("host", "localhost"); //$NON-NLS-1$ //$NON-NLS-2$
prop.put("port", Integer.toString(lport)); //$NON-NLS-1$
prop.put("root", cvs_root); //$NON-NLS-1$
CVSRepositoryLocation cvsrl = CVSRepositoryLocation.fromProperties(prop);
IConnectionMethod method = cvsrl.getMethod();
psc = method.createConnection(cvsrl, password);
} catch (Exception e) {
throw new CVSAuthenticationException(e.toString(), CVSAuthenticationException.NO_RETRY);
}
psc.open(monitor);
}
}
| true | true | public void open(IProgressMonitor monitor) throws IOException, CVSAuthenticationException {
monitor.subTask("PServerSSH2ServerConnection.open"); //$NON-NLS-1$
monitor.worked(1);
String cvs_root = location.getRootDirectory();
int cvs_port = location.getPort();
if (cvs_port == 0)
cvs_port = 2401;
String cvs_host = location.getHost();
String ssh_host = cvs_host;
String ssh_user = location.getUsername();
String host = cvs_host;
if (host.indexOf('@') != -1) {
cvs_host = host.substring(host.lastIndexOf('@') + 1);
host = host.substring(0, host.lastIndexOf('@'));
if (host.indexOf('@') != -1) {
ssh_host = host.substring(host.lastIndexOf('@') + 1);
if (ssh_host.length() == 0)
ssh_host = cvs_host;
ssh_user = host.substring(0, host.lastIndexOf('@'));
} else {
ssh_host = host;
}
}
int ssh_port = 0;
if (ssh_host.indexOf('#') != -1) {
try {
ssh_port = Integer.parseInt(ssh_host.substring(ssh_host.lastIndexOf('#') + 1));
ssh_host = ssh_host.substring(0, ssh_host.lastIndexOf('#'));
} catch (Exception e) {
}
}
int lport = cvs_port;
String rhost = (cvs_host.equals(ssh_host) ? "localhost" : cvs_host); //$NON-NLS-1$
int rport = cvs_port;
// ssh -L lport:rhost:rport ssh_user@ssh_host
int retry = 1;
while (true) {
try {
session = JSchSession.getSession(location, ssh_user, "", ssh_host, ssh_port, monitor).getSession(); //$NON-NLS-1$
String[] list = session.getPortForwardingL();
String name = ":" + rhost + ":" + rport; //$NON-NLS-1$ //$NON-NLS-2$
boolean done = false;
for (int i = 0; i < list.length; i++) {
if (list[i].endsWith(name)) {
try {
String foo = list[i].substring(0, list[i].indexOf(':'));
lport = Integer.parseInt(foo);
} catch (Exception ee) {
}
done = true;
break;
}
}
if (!done) {
lport = localport++;
session.setPortForwardingL(lport, rhost, rport);
}
} catch (JSchException ee) {
retry--;
if(retry<0){
throw new CVSAuthenticationException(CVSSSH2Messages.CVSSSH2ServerConnection_3, CVSAuthenticationException.NO_RETRY);
}
if(session.isConnected()){
session.disconnect();
}
continue;
}
break;
}
// password for location will be over-written in JSchSession ;-<
((CVSRepositoryLocation)location).setPassword(password);
// CVSROOT=":pserver:localhost:"+lport+""cvs_root
try {
Properties prop = new Properties();
prop.put("connection", "pserver"); //$NON-NLS-1$ //$NON-NLS-2$
prop.put("user", location.getUsername()); //$NON-NLS-1$
prop.put("password", password); //$NON-NLS-1$
prop.put("host", "localhost"); //$NON-NLS-1$ //$NON-NLS-2$
prop.put("port", Integer.toString(lport)); //$NON-NLS-1$
prop.put("root", cvs_root); //$NON-NLS-1$
CVSRepositoryLocation cvsrl = CVSRepositoryLocation.fromProperties(prop);
IConnectionMethod method = cvsrl.getMethod();
psc = method.createConnection(cvsrl, password);
} catch (Exception e) {
throw new CVSAuthenticationException(e.toString(), CVSAuthenticationException.NO_RETRY);
}
psc.open(monitor);
}
| public void open(IProgressMonitor monitor) throws IOException, CVSAuthenticationException {
monitor.subTask("PServerSSH2ServerConnection.open"); //$NON-NLS-1$
monitor.worked(1);
String cvs_root = location.getRootDirectory();
int cvs_port = location.getPort();
if (cvs_port == 0)
cvs_port = 2401;
String cvs_host = location.getHost();
String ssh_host = cvs_host;
String ssh_user = location.getUsername();
String host = cvs_host;
if (host.indexOf('@') != -1) {
cvs_host = host.substring(host.lastIndexOf('@') + 1);
host = host.substring(0, host.lastIndexOf('@'));
if (host.indexOf('@') != -1) {
ssh_host = host.substring(host.lastIndexOf('@') + 1);
if (ssh_host.length() == 0)
ssh_host = cvs_host;
ssh_user = host.substring(0, host.lastIndexOf('@'));
} else {
ssh_host = host;
}
}
int ssh_port = 0;
if (ssh_host.indexOf('#') != -1) {
try {
ssh_port = Integer.parseInt(ssh_host.substring(ssh_host.lastIndexOf('#') + 1));
ssh_host = ssh_host.substring(0, ssh_host.lastIndexOf('#'));
} catch (Exception e) {
}
}
int lport = cvs_port;
String rhost = (cvs_host.equals(ssh_host) ? "localhost" : cvs_host); //$NON-NLS-1$
int rport = cvs_port;
// ssh -L lport:rhost:rport ssh_user@ssh_host
int retry = 1;
while (true) {
try {
session = JSchSession.getSession(location, ssh_user, "", ssh_host, ssh_port, monitor).getSession(); //$NON-NLS-1$
String[] list = session.getPortForwardingL();
String name = ":" + rhost + ":" + rport; //$NON-NLS-1$ //$NON-NLS-2$
boolean done = false;
for (int i = 0; i < list.length; i++) {
if (list[i].endsWith(name)) {
try {
String foo = list[i].substring(0, list[i].indexOf(':'));
lport = Integer.parseInt(foo);
} catch (Exception ee) {
}
done = true;
break;
}
}
if (!done) {
lport = localport++;
session.setPortForwardingL(lport, rhost, rport);
}
} catch (JSchException ee) {
retry--;
if(retry<0){
throw new CVSAuthenticationException(CVSSSH2Messages.CVSSSH2ServerConnection_3, CVSAuthenticationException.NO_RETRY);
}
if(session != null && session.isConnected()){
session.disconnect();
}
continue;
}
break;
}
// password for location will be over-written in JSchSession ;-<
((CVSRepositoryLocation)location).setPassword(password);
// CVSROOT=":pserver:localhost:"+lport+""cvs_root
try {
Properties prop = new Properties();
prop.put("connection", "pserver"); //$NON-NLS-1$ //$NON-NLS-2$
prop.put("user", location.getUsername()); //$NON-NLS-1$
prop.put("password", password); //$NON-NLS-1$
prop.put("host", "localhost"); //$NON-NLS-1$ //$NON-NLS-2$
prop.put("port", Integer.toString(lport)); //$NON-NLS-1$
prop.put("root", cvs_root); //$NON-NLS-1$
CVSRepositoryLocation cvsrl = CVSRepositoryLocation.fromProperties(prop);
IConnectionMethod method = cvsrl.getMethod();
psc = method.createConnection(cvsrl, password);
} catch (Exception e) {
throw new CVSAuthenticationException(e.toString(), CVSAuthenticationException.NO_RETRY);
}
psc.open(monitor);
}
|
diff --git a/src/org/jwildfire/create/tina/variation/AbstractDisplacementMapWFFunc.java b/src/org/jwildfire/create/tina/variation/AbstractDisplacementMapWFFunc.java
index f9b5205e..8e792c3a 100644
--- a/src/org/jwildfire/create/tina/variation/AbstractDisplacementMapWFFunc.java
+++ b/src/org/jwildfire/create/tina/variation/AbstractDisplacementMapWFFunc.java
@@ -1,303 +1,304 @@
/*
JWildfire - an image and animation processor written in Java
Copyright (C) 1995-2012 Andreas Maschke
This 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 software 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 software;
if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jwildfire.create.tina.variation;
import static org.jwildfire.base.mathlib.MathLib.M_2PI;
import static org.jwildfire.base.mathlib.MathLib.cos;
import static org.jwildfire.base.mathlib.MathLib.fabs;
import static org.jwildfire.base.mathlib.MathLib.sin;
import org.jwildfire.base.Tools;
import org.jwildfire.create.GradientCreator;
import org.jwildfire.create.tina.base.XForm;
import org.jwildfire.create.tina.base.XYZPoint;
import org.jwildfire.create.tina.palette.RenderColor;
import org.jwildfire.image.Pixel;
import org.jwildfire.image.SimpleHDRImage;
import org.jwildfire.image.SimpleImage;
import org.jwildfire.image.WFImage;
public abstract class AbstractDisplacementMapWFFunc extends VariationFunc {
private static final long serialVersionUID = 1L;
private static final String PARAM_MODE = "mode";
private static final String PARAM_COLOR_MODE = "color_mode";
private static final String PARAM_BIAS = "bias";
private static final String PARAM_SCALEX = "scale_x";
private static final String PARAM_SCALEY = "scale_y";
private static final String PARAM_OFFSETX = "offset_x";
private static final String PARAM_OFFSETY = "offset_y";
private static final String PARAM_OFFSETZ = "offset_z";
private static final String PARAM_TILEX = "tile_x";
private static final String PARAM_TILEY = "tile_y";
private static final String RESSOURCE_IMAGE_FILENAME = "image_filename";
private static final String[] paramNames = { PARAM_MODE, PARAM_COLOR_MODE, PARAM_BIAS, PARAM_SCALEX, PARAM_SCALEY, PARAM_OFFSETX, PARAM_OFFSETY, PARAM_OFFSETZ, PARAM_TILEX, PARAM_TILEY };
private static final String[] ressourceNames = { RESSOURCE_IMAGE_FILENAME };
private static final int MODE_ROTATE = 0;
private static final int MODE_TRANSLATE = 1;
private static final int MODE_SCALE = 2;
private static final int MODE_SCISSOR = 3;
private static final int COLOR_MODE_IGNORE = 0;
private static final int COLOR_MODE_INHERIT = 1;
private int mode = MODE_ROTATE;
private int colorMode = COLOR_MODE_IGNORE;
private double bias = 0.0;
private double scaleX = 1.0;
private double scaleY = 1.0;
private double offsetX = 0.0;
private double offsetY = 0.0;
private double offsetZ = 0.0;
private int tileX = 1;
private int tileY = 1;
private String imageFilename = null;
// derived params
private int imgWidth, imgHeight;
private Pixel toolPixel = new Pixel();
private float[] rgbArray = new float[3];
public void transform(FlameTransformationContext pContext, XForm pXForm, XYZPoint pAffineTP, XYZPoint pVarTP, double pAmount, double pInputX, double pInputY) {
double x = (pInputX - (offsetX + 0.5) + 1.0) / scaleX * (double) (imgWidth - 1);
double y = (pInputY - (offsetY + 0.5) + 1.0) / scaleY * (double) (imgHeight - 1);
int ix = Tools.FTOI(x);
int iy = Tools.FTOI(y);
if (this.tileX == 1) {
if (ix < 0) {
int nx = ix / imgWidth - 1;
ix -= nx * imgWidth;
}
else if (ix >= imgWidth) {
int nx = ix / imgWidth;
ix -= nx * imgWidth;
}
}
if (this.tileY == 1) {
if (iy < 0) {
int ny = iy / imgHeight - 1;
iy -= ny * imgHeight;
}
else if (iy >= imgHeight) {
int ny = iy / imgHeight;
iy -= ny * imgHeight;
}
}
double r, g, b;
if (ix >= 0 && ix < imgWidth && iy >= 0 && iy < imgHeight) {
if (colorMap instanceof SimpleImage) {
toolPixel.setARGBValue(((SimpleImage) colorMap).getARGBValue(
ix, iy));
r = (double) toolPixel.r / 255.0;
g = (double) toolPixel.g / 255.0;
b = (double) toolPixel.b / 255.0;
}
else {
((SimpleHDRImage) colorMap).getRGBValues(rgbArray, ix, iy);
r = rgbArray[0];
g = rgbArray[0];
b = rgbArray[0];
}
}
else {
return;
}
switch (mode) {
case MODE_TRANSLATE: {
double amountX = (r - 0.5) * pAmount;
double amountY = (g - 0.5) * pAmount;
pVarTP.x += amountX;
pVarTP.y += amountY;
}
break;
case MODE_SCALE: {
double intensity = calcIntensity(r, g, b) - bias;
if (intensity > 0.0) {
double scl = 1.0 + (intensity - 0.5) * pAmount;
pVarTP.x *= scl;
pVarTP.y *= scl;
}
}
+ break;
case MODE_SCISSOR: {
double amountX = (r - 0.5) * pAmount;
double amountY = (g - 0.5) * pAmount;
double newx = pVarTP.x * amountX * amountY + pVarTP.y * amountY;
double newy = pVarTP.x * amountY - pVarTP.y * amountX * amountY;
pVarTP.x = newx;
pVarTP.y = newy;
}
break;
case MODE_ROTATE:
default: {
double intensity = calcIntensity(r, g, b) - bias;
if (intensity > 0.0) {
double angle = intensity * M_2PI * pAmount;
double sina = sin(angle);
double cosa = cos(angle);
double xnew = pVarTP.x * cosa - pVarTP.y * sina;
double ynew = pVarTP.x * sina + pVarTP.y * cosa;
pVarTP.x = xnew;
pVarTP.y = ynew;
}
}
}
switch (colorMode) {
case COLOR_MODE_INHERIT: {
pVarTP.rgbColor = true;
pVarTP.redColor = r;
pVarTP.greenColor = g;
pVarTP.blueColor = b;
pVarTP.color = getColorIdx(r, g, b);
}
break;
}
}
private double calcIntensity(double red, double green, double blue) {
return (0.299 * red + 0.588 * green + 0.113 * blue);
}
private double getColorIdx(double pR, double pG, double pB) {
int nearestIdx = 0;
RenderColor color = renderColors[0];
double dr, dg, db;
dr = (color.red - pR);
dg = (color.green - pG);
db = (color.blue - pB);
// double nearestDist = sqrt(dr * dr + dg * dg + db * db);
double nearestDist = fabs(dr) + fabs(dg) + fabs(db);
for (int i = 1; i < renderColors.length; i++) {
color = renderColors[i];
dr = (color.red - pR);
dg = (color.green - pG);
db = (color.blue - pB);
// double dist = sqrt(dr * dr + dg * dg + db * db);
double dist = fabs(dr) + fabs(dg) + fabs(db);
if (dist < nearestDist) {
nearestDist = dist;
nearestIdx = i;
}
}
return (double) nearestIdx / (double) (renderColors.length - 1);
}
@Override
public String[] getParameterNames() {
return paramNames;
}
@Override
public Object[] getParameterValues() {
return new Object[] { mode, colorMode, bias, scaleX, scaleY, offsetX, offsetY, offsetZ, tileX, tileY };
}
@Override
public void setParameter(String pName, double pValue) {
if (PARAM_MODE.equalsIgnoreCase(pName))
mode = Tools.FTOI(pValue);
else if (PARAM_COLOR_MODE.equalsIgnoreCase(pName))
colorMode = Tools.FTOI(pValue);
else if (PARAM_BIAS.equalsIgnoreCase(pName))
bias = pValue;
else if (PARAM_SCALEX.equalsIgnoreCase(pName))
scaleX = pValue;
else if (PARAM_SCALEY.equalsIgnoreCase(pName))
scaleY = pValue;
else if (PARAM_OFFSETX.equalsIgnoreCase(pName))
offsetX = pValue;
else if (PARAM_OFFSETY.equalsIgnoreCase(pName))
offsetY = pValue;
else if (PARAM_OFFSETZ.equalsIgnoreCase(pName))
offsetZ = pValue;
else if (PARAM_TILEX.equalsIgnoreCase(pName))
tileX = Tools.FTOI(pValue);
else if (PARAM_TILEY.equalsIgnoreCase(pName))
tileY = Tools.FTOI(pValue);
else
throw new IllegalArgumentException(pName);
}
private WFImage colorMap;
private RenderColor[] renderColors;
@Override
public void init(FlameTransformationContext pContext, XForm pXForm, double pAmount) {
colorMap = null;
renderColors = pContext.getFlameRenderer().getColorMap();
if (imageFilename != null && imageFilename.length() > 0) {
try {
colorMap = RessourceManager.getImage(imageFilename);
}
catch (Exception e) {
e.printStackTrace();
}
}
if (colorMap == null) {
colorMap = getDfltImage();
}
imgWidth = colorMap.getImageWidth();
imgHeight = colorMap.getImageHeight();
}
private static SimpleImage dfltImage = null;
private synchronized SimpleImage getDfltImage() {
if (dfltImage == null) {
GradientCreator creator = new GradientCreator();
dfltImage = creator.createImage(256, 256);
}
return dfltImage;
}
@Override
public String[] getRessourceNames() {
return ressourceNames;
}
@Override
public byte[][] getRessourceValues() {
return new byte[][] { (imageFilename != null ? imageFilename.getBytes() : null) };
}
@Override
public void setRessource(String pName, byte[] pValue) {
if (RESSOURCE_IMAGE_FILENAME.equalsIgnoreCase(pName)) {
imageFilename = pValue != null ? new String(pValue) : "";
colorMap = null;
}
else
throw new IllegalArgumentException(pName);
}
@Override
public RessourceType getRessourceType(String pName) {
if (RESSOURCE_IMAGE_FILENAME.equalsIgnoreCase(pName)) {
return RessourceType.IMAGE_FILENAME;
}
else
throw new IllegalArgumentException(pName);
}
}
| true | true | public void transform(FlameTransformationContext pContext, XForm pXForm, XYZPoint pAffineTP, XYZPoint pVarTP, double pAmount, double pInputX, double pInputY) {
double x = (pInputX - (offsetX + 0.5) + 1.0) / scaleX * (double) (imgWidth - 1);
double y = (pInputY - (offsetY + 0.5) + 1.0) / scaleY * (double) (imgHeight - 1);
int ix = Tools.FTOI(x);
int iy = Tools.FTOI(y);
if (this.tileX == 1) {
if (ix < 0) {
int nx = ix / imgWidth - 1;
ix -= nx * imgWidth;
}
else if (ix >= imgWidth) {
int nx = ix / imgWidth;
ix -= nx * imgWidth;
}
}
if (this.tileY == 1) {
if (iy < 0) {
int ny = iy / imgHeight - 1;
iy -= ny * imgHeight;
}
else if (iy >= imgHeight) {
int ny = iy / imgHeight;
iy -= ny * imgHeight;
}
}
double r, g, b;
if (ix >= 0 && ix < imgWidth && iy >= 0 && iy < imgHeight) {
if (colorMap instanceof SimpleImage) {
toolPixel.setARGBValue(((SimpleImage) colorMap).getARGBValue(
ix, iy));
r = (double) toolPixel.r / 255.0;
g = (double) toolPixel.g / 255.0;
b = (double) toolPixel.b / 255.0;
}
else {
((SimpleHDRImage) colorMap).getRGBValues(rgbArray, ix, iy);
r = rgbArray[0];
g = rgbArray[0];
b = rgbArray[0];
}
}
else {
return;
}
switch (mode) {
case MODE_TRANSLATE: {
double amountX = (r - 0.5) * pAmount;
double amountY = (g - 0.5) * pAmount;
pVarTP.x += amountX;
pVarTP.y += amountY;
}
break;
case MODE_SCALE: {
double intensity = calcIntensity(r, g, b) - bias;
if (intensity > 0.0) {
double scl = 1.0 + (intensity - 0.5) * pAmount;
pVarTP.x *= scl;
pVarTP.y *= scl;
}
}
case MODE_SCISSOR: {
double amountX = (r - 0.5) * pAmount;
double amountY = (g - 0.5) * pAmount;
double newx = pVarTP.x * amountX * amountY + pVarTP.y * amountY;
double newy = pVarTP.x * amountY - pVarTP.y * amountX * amountY;
pVarTP.x = newx;
pVarTP.y = newy;
}
break;
case MODE_ROTATE:
default: {
double intensity = calcIntensity(r, g, b) - bias;
if (intensity > 0.0) {
double angle = intensity * M_2PI * pAmount;
double sina = sin(angle);
double cosa = cos(angle);
double xnew = pVarTP.x * cosa - pVarTP.y * sina;
double ynew = pVarTP.x * sina + pVarTP.y * cosa;
pVarTP.x = xnew;
pVarTP.y = ynew;
}
}
}
switch (colorMode) {
case COLOR_MODE_INHERIT: {
pVarTP.rgbColor = true;
pVarTP.redColor = r;
pVarTP.greenColor = g;
pVarTP.blueColor = b;
pVarTP.color = getColorIdx(r, g, b);
}
break;
}
}
| public void transform(FlameTransformationContext pContext, XForm pXForm, XYZPoint pAffineTP, XYZPoint pVarTP, double pAmount, double pInputX, double pInputY) {
double x = (pInputX - (offsetX + 0.5) + 1.0) / scaleX * (double) (imgWidth - 1);
double y = (pInputY - (offsetY + 0.5) + 1.0) / scaleY * (double) (imgHeight - 1);
int ix = Tools.FTOI(x);
int iy = Tools.FTOI(y);
if (this.tileX == 1) {
if (ix < 0) {
int nx = ix / imgWidth - 1;
ix -= nx * imgWidth;
}
else if (ix >= imgWidth) {
int nx = ix / imgWidth;
ix -= nx * imgWidth;
}
}
if (this.tileY == 1) {
if (iy < 0) {
int ny = iy / imgHeight - 1;
iy -= ny * imgHeight;
}
else if (iy >= imgHeight) {
int ny = iy / imgHeight;
iy -= ny * imgHeight;
}
}
double r, g, b;
if (ix >= 0 && ix < imgWidth && iy >= 0 && iy < imgHeight) {
if (colorMap instanceof SimpleImage) {
toolPixel.setARGBValue(((SimpleImage) colorMap).getARGBValue(
ix, iy));
r = (double) toolPixel.r / 255.0;
g = (double) toolPixel.g / 255.0;
b = (double) toolPixel.b / 255.0;
}
else {
((SimpleHDRImage) colorMap).getRGBValues(rgbArray, ix, iy);
r = rgbArray[0];
g = rgbArray[0];
b = rgbArray[0];
}
}
else {
return;
}
switch (mode) {
case MODE_TRANSLATE: {
double amountX = (r - 0.5) * pAmount;
double amountY = (g - 0.5) * pAmount;
pVarTP.x += amountX;
pVarTP.y += amountY;
}
break;
case MODE_SCALE: {
double intensity = calcIntensity(r, g, b) - bias;
if (intensity > 0.0) {
double scl = 1.0 + (intensity - 0.5) * pAmount;
pVarTP.x *= scl;
pVarTP.y *= scl;
}
}
break;
case MODE_SCISSOR: {
double amountX = (r - 0.5) * pAmount;
double amountY = (g - 0.5) * pAmount;
double newx = pVarTP.x * amountX * amountY + pVarTP.y * amountY;
double newy = pVarTP.x * amountY - pVarTP.y * amountX * amountY;
pVarTP.x = newx;
pVarTP.y = newy;
}
break;
case MODE_ROTATE:
default: {
double intensity = calcIntensity(r, g, b) - bias;
if (intensity > 0.0) {
double angle = intensity * M_2PI * pAmount;
double sina = sin(angle);
double cosa = cos(angle);
double xnew = pVarTP.x * cosa - pVarTP.y * sina;
double ynew = pVarTP.x * sina + pVarTP.y * cosa;
pVarTP.x = xnew;
pVarTP.y = ynew;
}
}
}
switch (colorMode) {
case COLOR_MODE_INHERIT: {
pVarTP.rgbColor = true;
pVarTP.redColor = r;
pVarTP.greenColor = g;
pVarTP.blueColor = b;
pVarTP.color = getColorIdx(r, g, b);
}
break;
}
}
|
diff --git a/unittests/com/jgaap/classifiers/RandomAnalysisTest.java b/unittests/com/jgaap/classifiers/RandomAnalysisTest.java
index aa39a74..1db1294 100644
--- a/unittests/com/jgaap/classifiers/RandomAnalysisTest.java
+++ b/unittests/com/jgaap/classifiers/RandomAnalysisTest.java
@@ -1,147 +1,147 @@
/*
* JGAAP -- a graphical program for stylometric authorship attribution
* Copyright (C) 2009,2011 by Patrick Juola
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
*
*/
package com.jgaap.classifiers;
import static org.junit.Assert.*;
import java.util.List;
import java.util.Vector;
import java.lang.Math;
import org.junit.Test;
import com.jgaap.generics.Event;
import com.jgaap.generics.EventSet;
import com.jgaap.generics.Pair;
/**
* @author darrenvescovi
*
*/
public class RandomAnalysisTest {
/**
* Test method for {@link
* com.jgaap.classifiers.RandomAnalysis#analyze(com.jgaap.generics.EventSet,
* List<EventSet>)}.
*/
@Test
public void testAnalyze() {
EventSet known1 = new EventSet();
EventSet known2 = new EventSet();
EventSet unknownMary = new EventSet();
Vector<Event> test1 = new Vector<Event>();
test1.add(new Event("Mary"));
test1.add(new Event("had"));
test1.add(new Event("a"));
test1.add(new Event("little"));
test1.add(new Event("lamb"));
test1.add(new Event("whose"));
test1.add(new Event("fleece"));
test1.add(new Event("was"));
test1.add(new Event("white"));
test1.add(new Event("as"));
test1.add(new Event("snow."));
known1.addEvents(test1);
known1.setAuthor("Mary");
Vector<Event> test2 = new Vector<Event>();
test2.add(new Event("Peter"));
test2.add(new Event("piper"));
test2.add(new Event("picked"));
test2.add(new Event("a"));
test2.add(new Event("pack"));
test2.add(new Event("of"));
test2.add(new Event("pickled"));
test2.add(new Event("peppers."));
known2.addEvents(test2);
known2.setAuthor("Peter");
Vector<Event> test3 = new Vector<Event>();
test3.add(new Event("Mary"));
test3.add(new Event("had"));
test3.add(new Event("a"));
test3.add(new Event("little"));
test3.add(new Event("lambda"));
test3.add(new Event("whose"));
test3.add(new Event("syntax"));
test3.add(new Event("was"));
test3.add(new Event("white"));
test3.add(new Event("as"));
test3.add(new Event("snow."));
unknownMary.addEvents(test3);
Vector<EventSet> esv = new Vector<EventSet>();
for (int i = 1; i <= 62; i = i + 1) {
esv.add(known1);
}
for (int i = 63; i <= 100; i = i + 1) {
esv.add(known2);
}
RandomAnalysis thing = new RandomAnalysis();
int goodTest = 0; // hold the number of times Confidence interval covers
// Prob of Mary = .62
for (int z = 1; z <= 100; z = z + 1) {
int j = 0; // hold number of marys
for (int i = 1; i <= 1000; i = i + 1) {
List<Pair<String,Double>> t = thing.analyze(unknownMary, esv);
String r = t.get(0).getFirst();
if (r.equals("Mary")) {
j = j + 1;
}
}
double probMary;
double q = (double) j;
probMary = q / 1000.0;
double testStat;
double p;
p = (double) ((q * (1000 - q) / 1000.0) / 1000.0);
testStat = 1.96 * Math.sqrt(p);
if (.62 >= probMary - testStat && .62 <= probMary + testStat) {
goodTest = goodTest + 1;
}
}
double probGood;
- probGood = goodTest / 100; // this prob should be greater than .95
+ probGood = goodTest / 100.0; // this prob should be greater than .95
// because the confidence interval
// may not always cover the .62 mark for
// author Mary
assertTrue(probGood >= .95);
}
}
| true | true | public void testAnalyze() {
EventSet known1 = new EventSet();
EventSet known2 = new EventSet();
EventSet unknownMary = new EventSet();
Vector<Event> test1 = new Vector<Event>();
test1.add(new Event("Mary"));
test1.add(new Event("had"));
test1.add(new Event("a"));
test1.add(new Event("little"));
test1.add(new Event("lamb"));
test1.add(new Event("whose"));
test1.add(new Event("fleece"));
test1.add(new Event("was"));
test1.add(new Event("white"));
test1.add(new Event("as"));
test1.add(new Event("snow."));
known1.addEvents(test1);
known1.setAuthor("Mary");
Vector<Event> test2 = new Vector<Event>();
test2.add(new Event("Peter"));
test2.add(new Event("piper"));
test2.add(new Event("picked"));
test2.add(new Event("a"));
test2.add(new Event("pack"));
test2.add(new Event("of"));
test2.add(new Event("pickled"));
test2.add(new Event("peppers."));
known2.addEvents(test2);
known2.setAuthor("Peter");
Vector<Event> test3 = new Vector<Event>();
test3.add(new Event("Mary"));
test3.add(new Event("had"));
test3.add(new Event("a"));
test3.add(new Event("little"));
test3.add(new Event("lambda"));
test3.add(new Event("whose"));
test3.add(new Event("syntax"));
test3.add(new Event("was"));
test3.add(new Event("white"));
test3.add(new Event("as"));
test3.add(new Event("snow."));
unknownMary.addEvents(test3);
Vector<EventSet> esv = new Vector<EventSet>();
for (int i = 1; i <= 62; i = i + 1) {
esv.add(known1);
}
for (int i = 63; i <= 100; i = i + 1) {
esv.add(known2);
}
RandomAnalysis thing = new RandomAnalysis();
int goodTest = 0; // hold the number of times Confidence interval covers
// Prob of Mary = .62
for (int z = 1; z <= 100; z = z + 1) {
int j = 0; // hold number of marys
for (int i = 1; i <= 1000; i = i + 1) {
List<Pair<String,Double>> t = thing.analyze(unknownMary, esv);
String r = t.get(0).getFirst();
if (r.equals("Mary")) {
j = j + 1;
}
}
double probMary;
double q = (double) j;
probMary = q / 1000.0;
double testStat;
double p;
p = (double) ((q * (1000 - q) / 1000.0) / 1000.0);
testStat = 1.96 * Math.sqrt(p);
if (.62 >= probMary - testStat && .62 <= probMary + testStat) {
goodTest = goodTest + 1;
}
}
double probGood;
probGood = goodTest / 100; // this prob should be greater than .95
// because the confidence interval
// may not always cover the .62 mark for
// author Mary
assertTrue(probGood >= .95);
}
| public void testAnalyze() {
EventSet known1 = new EventSet();
EventSet known2 = new EventSet();
EventSet unknownMary = new EventSet();
Vector<Event> test1 = new Vector<Event>();
test1.add(new Event("Mary"));
test1.add(new Event("had"));
test1.add(new Event("a"));
test1.add(new Event("little"));
test1.add(new Event("lamb"));
test1.add(new Event("whose"));
test1.add(new Event("fleece"));
test1.add(new Event("was"));
test1.add(new Event("white"));
test1.add(new Event("as"));
test1.add(new Event("snow."));
known1.addEvents(test1);
known1.setAuthor("Mary");
Vector<Event> test2 = new Vector<Event>();
test2.add(new Event("Peter"));
test2.add(new Event("piper"));
test2.add(new Event("picked"));
test2.add(new Event("a"));
test2.add(new Event("pack"));
test2.add(new Event("of"));
test2.add(new Event("pickled"));
test2.add(new Event("peppers."));
known2.addEvents(test2);
known2.setAuthor("Peter");
Vector<Event> test3 = new Vector<Event>();
test3.add(new Event("Mary"));
test3.add(new Event("had"));
test3.add(new Event("a"));
test3.add(new Event("little"));
test3.add(new Event("lambda"));
test3.add(new Event("whose"));
test3.add(new Event("syntax"));
test3.add(new Event("was"));
test3.add(new Event("white"));
test3.add(new Event("as"));
test3.add(new Event("snow."));
unknownMary.addEvents(test3);
Vector<EventSet> esv = new Vector<EventSet>();
for (int i = 1; i <= 62; i = i + 1) {
esv.add(known1);
}
for (int i = 63; i <= 100; i = i + 1) {
esv.add(known2);
}
RandomAnalysis thing = new RandomAnalysis();
int goodTest = 0; // hold the number of times Confidence interval covers
// Prob of Mary = .62
for (int z = 1; z <= 100; z = z + 1) {
int j = 0; // hold number of marys
for (int i = 1; i <= 1000; i = i + 1) {
List<Pair<String,Double>> t = thing.analyze(unknownMary, esv);
String r = t.get(0).getFirst();
if (r.equals("Mary")) {
j = j + 1;
}
}
double probMary;
double q = (double) j;
probMary = q / 1000.0;
double testStat;
double p;
p = (double) ((q * (1000 - q) / 1000.0) / 1000.0);
testStat = 1.96 * Math.sqrt(p);
if (.62 >= probMary - testStat && .62 <= probMary + testStat) {
goodTest = goodTest + 1;
}
}
double probGood;
probGood = goodTest / 100.0; // this prob should be greater than .95
// because the confidence interval
// may not always cover the .62 mark for
// author Mary
assertTrue(probGood >= .95);
}
|
diff --git a/src/uk/me/parabola/imgfmt/app/mdr/MDRFile.java b/src/uk/me/parabola/imgfmt/app/mdr/MDRFile.java
index 6447729b..fa622f3c 100644
--- a/src/uk/me/parabola/imgfmt/app/mdr/MDRFile.java
+++ b/src/uk/me/parabola/imgfmt/app/mdr/MDRFile.java
@@ -1,346 +1,346 @@
/*
* Copyright (C) 2009.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 or
* version 2 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.
*/
package uk.me.parabola.imgfmt.app.mdr;
import uk.me.parabola.imgfmt.app.BufferedImgFileReader;
import uk.me.parabola.imgfmt.app.BufferedImgFileWriter;
import uk.me.parabola.imgfmt.app.ImgFile;
import uk.me.parabola.imgfmt.app.ImgFileWriter;
import uk.me.parabola.imgfmt.app.Label;
import uk.me.parabola.imgfmt.app.lbl.Country;
import uk.me.parabola.imgfmt.app.lbl.Region;
import uk.me.parabola.imgfmt.app.lbl.Zip;
import uk.me.parabola.imgfmt.app.net.RoadDef;
import uk.me.parabola.imgfmt.app.srt.Sort;
import uk.me.parabola.imgfmt.app.trergn.Point;
import uk.me.parabola.imgfmt.fs.ImgChannel;
/**
* The MDR file. This is embedded into a .img file, either its own
* separate one, or as one file in the gmapsupp.img.
*
* @author Steve Ratcliffe
*/
public class MDRFile extends ImgFile {
private final MDRHeader mdrHeader;
// The sections
private final Mdr1 mdr1;
private final Mdr4 mdr4;
private final Mdr5 mdr5;
private final Mdr6 mdr6;
private final Mdr7 mdr7;
private final Mdr8 mdr8;
private final Mdr9 mdr9;
private final Mdr10 mdr10;
private final Mdr11 mdr11;
private final Mdr12 mdr12;
private final Mdr13 mdr13;
private final Mdr14 mdr14;
private final Mdr15 mdr15;
private final Mdr20 mdr20;
private final Mdr21 mdr21;
private final Mdr22 mdr22;
private final Mdr23 mdr23;
private final Mdr24 mdr24;
private final Mdr25 mdr25;
private final Mdr26 mdr26;
private final Mdr27 mdr27;
private final Mdr28 mdr28;
private final Mdr29 mdr29;
private int currentMap;
private final MdrSection[] sections;
private MdrSection.PointerSizes sizes;
public MDRFile(ImgChannel chan, MdrConfig config) {
Sort sort = config.getSort();
mdrHeader = new MDRHeader(config.getHeaderLen());
mdrHeader.setSort(sort);
setHeader(mdrHeader);
if (config.isWritable()) {
BufferedImgFileWriter fileWriter = new BufferedImgFileWriter(chan);
fileWriter.setMaxSize(Long.MAX_VALUE);
setWriter(fileWriter);
// Position at the start of the writable area.
position(mdrHeader.getHeaderLength());
} else {
setReader(new BufferedImgFileReader(chan));
mdrHeader.readHeader(getReader());
}
// Initialise the sections
mdr1 = new Mdr1(config);
mdr4 = new Mdr4(config);
mdr5 = new Mdr5(config);
mdr6 = new Mdr6(config);
mdr7 = new Mdr7(config);
mdr8 = new Mdr8(config);
mdr9 = new Mdr9(config);
mdr10 = new Mdr10(config);
mdr11 = new Mdr11(config);
mdr12 = new Mdr12(config);
mdr13 = new Mdr13(config);
mdr14 = new Mdr14(config);
mdr15 = new Mdr15(config);
mdr20 = new Mdr20(config);
mdr21 = new Mdr21(config);
mdr22 = new Mdr22(config);
mdr23 = new Mdr23(config);
mdr24 = new Mdr24(config);
mdr25 = new Mdr25(config);
mdr26 = new Mdr26(config);
mdr27 = new Mdr27(config);
mdr28 = new Mdr28(config);
mdr29 = new Mdr29(config);
this.sections = new MdrSection[]{
null,
mdr1, null, null, mdr4, mdr5, mdr6,
mdr7, mdr8, mdr9, mdr10, mdr11, mdr12,
mdr13, mdr14, mdr15, null, null, null, null,
mdr20, mdr21, mdr22, mdr23, mdr24, mdr25,
mdr26, mdr27, mdr28, mdr29,
};
mdr11.setMdr10(mdr10);
}
/**
* Add a map to the index. You must add the map, then all of the items
* that belong to it, before adding the next map.
* @param mapName The numeric name of the map.
*/
public void addMap(int mapName) {
currentMap++;
mdr1.addMap(mapName);
}
public Mdr14Record addCountry(Country country) {
Mdr14Record record = new Mdr14Record();
String name = country.getLabel().getText();
record.setMapIndex(currentMap);
record.setCountryIndex((int) country.getIndex());
record.setLblOffset(country.getLabel().getOffset());
record.setName(name);
record.setStrOff(createString(name));
mdr14.addCountry(record);
return record;
}
public Mdr13Record addRegion(Region region, Mdr14Record country) {
Mdr13Record record = new Mdr13Record();
String name = region.getLabel().getText();
record.setMapIndex(currentMap);
record.setLblOffset(region.getLabel().getOffset());
record.setCountryIndex(region.getCountry().getIndex());
record.setRegionIndex(region.getIndex());
record.setName(name);
record.setStrOffset(createString(name));
record.setMdr14(country);
mdr13.addRegion(record);
return record;
}
public void addCity(Mdr5Record city) {
int labelOffset = city.getLblOffset();
if (labelOffset != 0) {
String name = city.getName();
assert name != null : "off=" + labelOffset;
city.setMapIndex(currentMap);
city.setStringOffset(createString(name));
mdr5.addCity(city);
}
}
public void addZip(Zip zip) {
int strOff = createString(zip.getLabel().getText());
mdr6.addZip(currentMap, zip, strOff);
}
public void addPoint(Point point, Mdr5Record city, boolean isCity) {
assert currentMap > 0;
int fullType = point.getType();
if (!MdrUtils.canBeIndexed(fullType))
return;
Label label = point.getLabel();
String name = label.getText();
int strOff = createString(name);
Mdr11Record poi = mdr11.addPoi(currentMap, point, name, strOff);
poi.setCity(city);
poi.setIsCity(isCity);
poi.setType(fullType);
mdr4.addType(point.getType());
}
public void addStreet(RoadDef street, Mdr5Record mdrCity) {
// Add a separate record for each name
for (Label lab : street.getLabels()) {
if (lab == null)
break;
String name = lab.getText();
String cleanName = cleanUpName(name);
int strOff = createString(cleanName);
// XXX not sure: we sort on the dirty name (ie with the Garmin shield codes).
mdr7.addStreet(currentMap, name, lab.getOffset(), strOff, mdrCity);
}
}
/**
* Remove shields and other kinds of strange characters. Perform any
* rearrangement of the name to make it searchable.
* @param name The street name as read from the img file.
* @return The name as it will go into the index.
*/
private String cleanUpName(String name) {
return Label.stripGarminCodes(name);
}
public void write() {
for (MdrSection s : sections) {
if (s != null)
s.finish();
}
ImgFileWriter writer = getWriter();
writeSections(writer);
// Now refresh the header
position(0);
getHeader().writeHeader(writer);
}
/**
* Write all the sections out.
*
* The order of all the operations in this method is important. The order
* of the sections in the actual
* @param writer File is written here.
*/
private void writeSections(ImgFileWriter writer) {
sizes = new MdrMapSection.PointerSizes(sections);
// Deal with the dependencies between the sections. The order of the following
// statements is sometimes important.
mdr10.setNumberOfPois(mdr11.getNumberOfPois());
mdr28.buildFromRegions(mdr13.getRegions());
mdr23.sortRegions(mdr13.getRegions());
mdr29.buildFromCountries(mdr14.getCountries());
mdr24.sortCountries(mdr14.getCountries());
mdr20.buildFromStreets(mdr7.getStreets(), mdr5);
mdr21.buildFromStreets(mdr7.getStreets());
mdr22.buildFromStreets(mdr7.getStreets());
mdr8.setIndex(mdr7.getIndex());
mdr9.setGroups(mdr10.getGroupSizes());
mdr12.setIndex(mdr11.getIndex());
mdr25.sortCities(mdr5.getCities());
mdr27.sortCities(mdr5.getCities());
mdr26.sortMdr28(mdr28.getIndex());
writeSection(writer, 4, mdr4);
// We write the following sections that contain per-map data, in the
// order of the subsections of the reverse index that they are associated
// with.
writeSection(writer, 11, mdr11);
writeSection(writer, 10, mdr10);
writeSection(writer, 7, mdr7);
writeSection(writer, 5, mdr5);
writeSection(writer, 6, mdr6);
writeSection(writer, 20, mdr20);
writeSection(writer, 21, mdr21);
writeSection(writer, 22, mdr22);
// There is no ordering constraint on the following
- writeSection(writer, 8, mdr8);
+ //writeSection(writer, 8, mdr8);
writeSection(writer, 9, mdr9);
writeSection(writer, 12, mdr12);
writeSection(writer, 13, mdr13);
writeSection(writer, 14, mdr14);
writeSection(writer, 15, mdr15);
writeSection(writer, 23, mdr23);
writeSection(writer, 24, mdr24);
writeSection(writer, 25, mdr25);
writeSection(writer, 26, mdr26);
writeSection(writer, 27, mdr27);
writeSection(writer, 28, mdr28);
writeSection(writer, 29, mdr29);
// write the reverse index last.
mdr1.writeSubSections(writer);
mdrHeader.setPosition(1, writer.position());
mdr1.writeSectData(writer);
mdrHeader.setItemSize(1, mdr1.getItemSize());
mdrHeader.setEnd(1, writer.position());
mdrHeader.setExtraValue(1, mdr1.getExtraValue());
}
/**
* Write out the given single section.
*/
private void writeSection(ImgFileWriter writer, int sectionNumber, MdrSection section) {
section.setSizes(sizes);
mdrHeader.setPosition(sectionNumber, writer.position());
mdr1.setStartPosition(sectionNumber);
if (section instanceof MdrMapSection) {
MdrMapSection mapSection = (MdrMapSection) section;
mapSection.setMapIndex(mdr1);
mapSection.initIndex(sectionNumber);
}
if (section instanceof HasHeaderFlags)
mdrHeader.setExtraValue(sectionNumber, ((HasHeaderFlags) section).getExtraValue());
section.writeSectData(writer);
int itemSize = section.getItemSize();
if (itemSize > 0)
mdrHeader.setItemSize(sectionNumber, itemSize);
mdrHeader.setEnd(sectionNumber, writer.position());
mdr1.setEndPosition(sectionNumber);
}
/**
* Creates a string in MDR 15 and returns an offset value that can be
* used to refer to it in the other sections.
* @param str The text of the string.
* @return An offset value.
*/
private int createString(String str) {
return mdr15.createString(str.toUpperCase());
}
}
| true | true | private void writeSections(ImgFileWriter writer) {
sizes = new MdrMapSection.PointerSizes(sections);
// Deal with the dependencies between the sections. The order of the following
// statements is sometimes important.
mdr10.setNumberOfPois(mdr11.getNumberOfPois());
mdr28.buildFromRegions(mdr13.getRegions());
mdr23.sortRegions(mdr13.getRegions());
mdr29.buildFromCountries(mdr14.getCountries());
mdr24.sortCountries(mdr14.getCountries());
mdr20.buildFromStreets(mdr7.getStreets(), mdr5);
mdr21.buildFromStreets(mdr7.getStreets());
mdr22.buildFromStreets(mdr7.getStreets());
mdr8.setIndex(mdr7.getIndex());
mdr9.setGroups(mdr10.getGroupSizes());
mdr12.setIndex(mdr11.getIndex());
mdr25.sortCities(mdr5.getCities());
mdr27.sortCities(mdr5.getCities());
mdr26.sortMdr28(mdr28.getIndex());
writeSection(writer, 4, mdr4);
// We write the following sections that contain per-map data, in the
// order of the subsections of the reverse index that they are associated
// with.
writeSection(writer, 11, mdr11);
writeSection(writer, 10, mdr10);
writeSection(writer, 7, mdr7);
writeSection(writer, 5, mdr5);
writeSection(writer, 6, mdr6);
writeSection(writer, 20, mdr20);
writeSection(writer, 21, mdr21);
writeSection(writer, 22, mdr22);
// There is no ordering constraint on the following
writeSection(writer, 8, mdr8);
writeSection(writer, 9, mdr9);
writeSection(writer, 12, mdr12);
writeSection(writer, 13, mdr13);
writeSection(writer, 14, mdr14);
writeSection(writer, 15, mdr15);
writeSection(writer, 23, mdr23);
writeSection(writer, 24, mdr24);
writeSection(writer, 25, mdr25);
writeSection(writer, 26, mdr26);
writeSection(writer, 27, mdr27);
writeSection(writer, 28, mdr28);
writeSection(writer, 29, mdr29);
// write the reverse index last.
mdr1.writeSubSections(writer);
mdrHeader.setPosition(1, writer.position());
mdr1.writeSectData(writer);
mdrHeader.setItemSize(1, mdr1.getItemSize());
mdrHeader.setEnd(1, writer.position());
mdrHeader.setExtraValue(1, mdr1.getExtraValue());
}
| private void writeSections(ImgFileWriter writer) {
sizes = new MdrMapSection.PointerSizes(sections);
// Deal with the dependencies between the sections. The order of the following
// statements is sometimes important.
mdr10.setNumberOfPois(mdr11.getNumberOfPois());
mdr28.buildFromRegions(mdr13.getRegions());
mdr23.sortRegions(mdr13.getRegions());
mdr29.buildFromCountries(mdr14.getCountries());
mdr24.sortCountries(mdr14.getCountries());
mdr20.buildFromStreets(mdr7.getStreets(), mdr5);
mdr21.buildFromStreets(mdr7.getStreets());
mdr22.buildFromStreets(mdr7.getStreets());
mdr8.setIndex(mdr7.getIndex());
mdr9.setGroups(mdr10.getGroupSizes());
mdr12.setIndex(mdr11.getIndex());
mdr25.sortCities(mdr5.getCities());
mdr27.sortCities(mdr5.getCities());
mdr26.sortMdr28(mdr28.getIndex());
writeSection(writer, 4, mdr4);
// We write the following sections that contain per-map data, in the
// order of the subsections of the reverse index that they are associated
// with.
writeSection(writer, 11, mdr11);
writeSection(writer, 10, mdr10);
writeSection(writer, 7, mdr7);
writeSection(writer, 5, mdr5);
writeSection(writer, 6, mdr6);
writeSection(writer, 20, mdr20);
writeSection(writer, 21, mdr21);
writeSection(writer, 22, mdr22);
// There is no ordering constraint on the following
//writeSection(writer, 8, mdr8);
writeSection(writer, 9, mdr9);
writeSection(writer, 12, mdr12);
writeSection(writer, 13, mdr13);
writeSection(writer, 14, mdr14);
writeSection(writer, 15, mdr15);
writeSection(writer, 23, mdr23);
writeSection(writer, 24, mdr24);
writeSection(writer, 25, mdr25);
writeSection(writer, 26, mdr26);
writeSection(writer, 27, mdr27);
writeSection(writer, 28, mdr28);
writeSection(writer, 29, mdr29);
// write the reverse index last.
mdr1.writeSubSections(writer);
mdrHeader.setPosition(1, writer.position());
mdr1.writeSectData(writer);
mdrHeader.setItemSize(1, mdr1.getItemSize());
mdrHeader.setEnd(1, writer.position());
mdrHeader.setExtraValue(1, mdr1.getExtraValue());
}
|
diff --git a/src/com/modcrafting/diablodrops/commands/DiabloDropCommand.java b/src/com/modcrafting/diablodrops/commands/DiabloDropCommand.java
index 2f0d627..426c8f9 100644
--- a/src/com/modcrafting/diablodrops/commands/DiabloDropCommand.java
+++ b/src/com/modcrafting/diablodrops/commands/DiabloDropCommand.java
@@ -1,222 +1,222 @@
package com.modcrafting.diablodrops.commands;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.craftbukkit.inventory.CraftItemStack;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import com.modcrafting.diablodrops.DiabloDrops;
import com.modcrafting.diablodrops.items.Socket;
import com.modcrafting.diablodrops.items.Tome;
import com.modcrafting.diablodrops.tier.Tier;
import com.modcrafting.toolapi.lib.Tool;
public class DiabloDropCommand implements CommandExecutor
{
private DiabloDrops plugin;
public DiabloDropCommand(DiabloDrops plugin)
{
this.plugin = plugin;
}
@Override
public boolean onCommand(CommandSender sender, Command command,
String commandLabel, String[] args)
{
if (!(sender instanceof Player)
|| !sender.hasPermission(command.getPermission()))
{
sender.sendMessage(ChatColor.RED + "You cannot run this command.");
return true;
}
Player player = ((Player) sender);
PlayerInventory pi = player.getInventory();
switch (args.length)
{
case 0:
CraftItemStack ci = plugin.dropsAPI.getItem();
while (ci == null)
ci = plugin.dropsAPI.getItem();
pi.addItem(ci);
player.sendMessage(ChatColor.GREEN
+ "You have been given a DiabloDrops item.");
return true;
default:
if (args[0].equalsIgnoreCase("tome")
|| args[0].equalsIgnoreCase("book"))
{
pi.addItem(new Tome());
player.sendMessage(ChatColor.GREEN
+ "You have been given a tome.");
return true;
}
if (args[0].equalsIgnoreCase("socket")
|| args[0].equalsIgnoreCase("socketitem"))
{
List<String> l = plugin.config.getStringList("SocketItem.Items");
pi.addItem(new Socket(Material.valueOf(l.get(
plugin.gen.nextInt(l.size())).toUpperCase())));
player.sendMessage(ChatColor.GREEN
+ "You have been given a SocketItem.");
return true;
}
if (args[0].equalsIgnoreCase("custom"))
{
pi.addItem(plugin.custom.get(plugin.gen
.nextInt(plugin.custom.size())));
player.sendMessage(ChatColor.GREEN
+ "You have been given a DiabloDrops item.");
return true;
}
if (args[0].equalsIgnoreCase("modify"))
{
- if (args.length < 2)
+ if (args.length < 2||player.getItemInHand()==null||player.getItemInHand().getType().equals(Material.AIR))
return true;
if (args[1].equalsIgnoreCase("lore"))
{
String lore = combineSplit(2, args, " ");
lore = ChatColor.translateAlternateColorCodes(
"&".toCharArray()[0], lore);
new Tool(player.getItemInHand()).setLore(Arrays
.asList(lore.split(",")));
player.sendMessage(ChatColor.GREEN
+ "Set the lore for the item!");
return true;
}
if (args[1].equalsIgnoreCase("name"))
{
String name = combineSplit(2, args, " ");
name = ChatColor.translateAlternateColorCodes(
"&".toCharArray()[0], name);
new Tool(player.getItemInHand()).setName(name);
player.sendMessage(ChatColor.GREEN
+ "Set the name for the item!");
return true;
}
if (args[1].equalsIgnoreCase("enchant"))
{
if (args.length < 4)
return true;
if (args[2].equalsIgnoreCase("add"))
{
if (args.length < 5)
return true;
int i = 1;
try
{
i = Integer.parseInt(args[4]);
}
catch (NumberFormatException nfe)
{
if(plugin.debug) plugin.log.warning(nfe.getMessage());
}
Enchantment ech = Enchantment.getByName(args[3]
.toUpperCase());
if (ech != null)
{
player.getItemInHand().addUnsafeEnchantment(
ech, i);
player.sendMessage(ChatColor.GREEN
+ "Added enchantment.");
}
else
{
player.sendMessage(ChatColor.RED + args[3]
+ " :enchantment does not exist!");
}
return true;
}
if (args[2].equalsIgnoreCase("remove"))
{
ItemStack is = player.getItemInHand();
Map<Enchantment, Integer> hm = new HashMap<Enchantment, Integer>();
for (Enchantment e1 : is.getEnchantments().keySet())
{
if (!e1.getName().equalsIgnoreCase(args[3]))
{
hm.put(e1, is.getEnchantmentLevel(e1));
}
}
is.addUnsafeEnchantments(hm);
player.sendMessage(ChatColor.GREEN
+ "Removed enchantment.");
return true;
}
}
}
if (args[0].equalsIgnoreCase("reload")
&& sender.hasPermission("diablodrops.reload"))
{
plugin.getServer().getPluginManager().disablePlugin(plugin);
plugin.getServer().getPluginManager().enablePlugin(plugin);
plugin.reloadConfig();
plugin.getLogger().info("Reloaded");
sender.sendMessage(ChatColor.GREEN + "DiabloDrops Reloaded");
return true;
}
if (args[0].equalsIgnoreCase("repair"))
{
if (plugin.dropsAPI.canBeItem(player.getItemInHand()
.getType()))
{
player.getItemInHand().setDurability((short) 0);
player.sendMessage(ChatColor.GREEN + "Item repaired.");
return true;
}
player.sendMessage("Unable to repair item.");
return true;
}
if (plugin.dropsAPI.matchesTier(args[0]))
{
Tier tier = plugin.dropsAPI.getTier(args[0]);
CraftItemStack ci2 = plugin.dropsAPI.getItem(tier);
while (ci2 == null)
ci2 = plugin.dropsAPI.getItem(tier);
pi.addItem(ci2);
player.sendMessage(ChatColor.GREEN
+ "You have been given a " + ChatColor.WHITE
+ args[0] + ChatColor.GREEN + " DiabloDrops item.");
return true;
}
CraftItemStack ci2 = plugin.dropsAPI.getItem();
while (ci2 == null)
ci2 = plugin.dropsAPI.getItem();
pi.addItem(ci2);
player.sendMessage(ChatColor.GREEN
+ "You have been given a DiabloDrops item.");
return true;
}
}
public String combineSplit(int startIndex, String[] string, String seperator)
{
StringBuilder builder = new StringBuilder();
if (string.length >= 1)
{
for (int i = startIndex; i < string.length; i++)
{
builder.append(string[i]);
builder.append(seperator);
}
if (builder.length() > seperator.length())
{
builder.deleteCharAt(builder.length() - seperator.length()); // remove
return builder.toString();
}
}
return "";
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command,
String commandLabel, String[] args)
{
if (!(sender instanceof Player)
|| !sender.hasPermission(command.getPermission()))
{
sender.sendMessage(ChatColor.RED + "You cannot run this command.");
return true;
}
Player player = ((Player) sender);
PlayerInventory pi = player.getInventory();
switch (args.length)
{
case 0:
CraftItemStack ci = plugin.dropsAPI.getItem();
while (ci == null)
ci = plugin.dropsAPI.getItem();
pi.addItem(ci);
player.sendMessage(ChatColor.GREEN
+ "You have been given a DiabloDrops item.");
return true;
default:
if (args[0].equalsIgnoreCase("tome")
|| args[0].equalsIgnoreCase("book"))
{
pi.addItem(new Tome());
player.sendMessage(ChatColor.GREEN
+ "You have been given a tome.");
return true;
}
if (args[0].equalsIgnoreCase("socket")
|| args[0].equalsIgnoreCase("socketitem"))
{
List<String> l = plugin.config.getStringList("SocketItem.Items");
pi.addItem(new Socket(Material.valueOf(l.get(
plugin.gen.nextInt(l.size())).toUpperCase())));
player.sendMessage(ChatColor.GREEN
+ "You have been given a SocketItem.");
return true;
}
if (args[0].equalsIgnoreCase("custom"))
{
pi.addItem(plugin.custom.get(plugin.gen
.nextInt(plugin.custom.size())));
player.sendMessage(ChatColor.GREEN
+ "You have been given a DiabloDrops item.");
return true;
}
if (args[0].equalsIgnoreCase("modify"))
{
if (args.length < 2)
return true;
if (args[1].equalsIgnoreCase("lore"))
{
String lore = combineSplit(2, args, " ");
lore = ChatColor.translateAlternateColorCodes(
"&".toCharArray()[0], lore);
new Tool(player.getItemInHand()).setLore(Arrays
.asList(lore.split(",")));
player.sendMessage(ChatColor.GREEN
+ "Set the lore for the item!");
return true;
}
if (args[1].equalsIgnoreCase("name"))
{
String name = combineSplit(2, args, " ");
name = ChatColor.translateAlternateColorCodes(
"&".toCharArray()[0], name);
new Tool(player.getItemInHand()).setName(name);
player.sendMessage(ChatColor.GREEN
+ "Set the name for the item!");
return true;
}
if (args[1].equalsIgnoreCase("enchant"))
{
if (args.length < 4)
return true;
if (args[2].equalsIgnoreCase("add"))
{
if (args.length < 5)
return true;
int i = 1;
try
{
i = Integer.parseInt(args[4]);
}
catch (NumberFormatException nfe)
{
if(plugin.debug) plugin.log.warning(nfe.getMessage());
}
Enchantment ech = Enchantment.getByName(args[3]
.toUpperCase());
if (ech != null)
{
player.getItemInHand().addUnsafeEnchantment(
ech, i);
player.sendMessage(ChatColor.GREEN
+ "Added enchantment.");
}
else
{
player.sendMessage(ChatColor.RED + args[3]
+ " :enchantment does not exist!");
}
return true;
}
if (args[2].equalsIgnoreCase("remove"))
{
ItemStack is = player.getItemInHand();
Map<Enchantment, Integer> hm = new HashMap<Enchantment, Integer>();
for (Enchantment e1 : is.getEnchantments().keySet())
{
if (!e1.getName().equalsIgnoreCase(args[3]))
{
hm.put(e1, is.getEnchantmentLevel(e1));
}
}
is.addUnsafeEnchantments(hm);
player.sendMessage(ChatColor.GREEN
+ "Removed enchantment.");
return true;
}
}
}
if (args[0].equalsIgnoreCase("reload")
&& sender.hasPermission("diablodrops.reload"))
{
plugin.getServer().getPluginManager().disablePlugin(plugin);
plugin.getServer().getPluginManager().enablePlugin(plugin);
plugin.reloadConfig();
plugin.getLogger().info("Reloaded");
sender.sendMessage(ChatColor.GREEN + "DiabloDrops Reloaded");
return true;
}
if (args[0].equalsIgnoreCase("repair"))
{
if (plugin.dropsAPI.canBeItem(player.getItemInHand()
.getType()))
{
player.getItemInHand().setDurability((short) 0);
player.sendMessage(ChatColor.GREEN + "Item repaired.");
return true;
}
player.sendMessage("Unable to repair item.");
return true;
}
if (plugin.dropsAPI.matchesTier(args[0]))
{
Tier tier = plugin.dropsAPI.getTier(args[0]);
CraftItemStack ci2 = plugin.dropsAPI.getItem(tier);
while (ci2 == null)
ci2 = plugin.dropsAPI.getItem(tier);
pi.addItem(ci2);
player.sendMessage(ChatColor.GREEN
+ "You have been given a " + ChatColor.WHITE
+ args[0] + ChatColor.GREEN + " DiabloDrops item.");
return true;
}
CraftItemStack ci2 = plugin.dropsAPI.getItem();
while (ci2 == null)
ci2 = plugin.dropsAPI.getItem();
pi.addItem(ci2);
player.sendMessage(ChatColor.GREEN
+ "You have been given a DiabloDrops item.");
return true;
}
}
| public boolean onCommand(CommandSender sender, Command command,
String commandLabel, String[] args)
{
if (!(sender instanceof Player)
|| !sender.hasPermission(command.getPermission()))
{
sender.sendMessage(ChatColor.RED + "You cannot run this command.");
return true;
}
Player player = ((Player) sender);
PlayerInventory pi = player.getInventory();
switch (args.length)
{
case 0:
CraftItemStack ci = plugin.dropsAPI.getItem();
while (ci == null)
ci = plugin.dropsAPI.getItem();
pi.addItem(ci);
player.sendMessage(ChatColor.GREEN
+ "You have been given a DiabloDrops item.");
return true;
default:
if (args[0].equalsIgnoreCase("tome")
|| args[0].equalsIgnoreCase("book"))
{
pi.addItem(new Tome());
player.sendMessage(ChatColor.GREEN
+ "You have been given a tome.");
return true;
}
if (args[0].equalsIgnoreCase("socket")
|| args[0].equalsIgnoreCase("socketitem"))
{
List<String> l = plugin.config.getStringList("SocketItem.Items");
pi.addItem(new Socket(Material.valueOf(l.get(
plugin.gen.nextInt(l.size())).toUpperCase())));
player.sendMessage(ChatColor.GREEN
+ "You have been given a SocketItem.");
return true;
}
if (args[0].equalsIgnoreCase("custom"))
{
pi.addItem(plugin.custom.get(plugin.gen
.nextInt(plugin.custom.size())));
player.sendMessage(ChatColor.GREEN
+ "You have been given a DiabloDrops item.");
return true;
}
if (args[0].equalsIgnoreCase("modify"))
{
if (args.length < 2||player.getItemInHand()==null||player.getItemInHand().getType().equals(Material.AIR))
return true;
if (args[1].equalsIgnoreCase("lore"))
{
String lore = combineSplit(2, args, " ");
lore = ChatColor.translateAlternateColorCodes(
"&".toCharArray()[0], lore);
new Tool(player.getItemInHand()).setLore(Arrays
.asList(lore.split(",")));
player.sendMessage(ChatColor.GREEN
+ "Set the lore for the item!");
return true;
}
if (args[1].equalsIgnoreCase("name"))
{
String name = combineSplit(2, args, " ");
name = ChatColor.translateAlternateColorCodes(
"&".toCharArray()[0], name);
new Tool(player.getItemInHand()).setName(name);
player.sendMessage(ChatColor.GREEN
+ "Set the name for the item!");
return true;
}
if (args[1].equalsIgnoreCase("enchant"))
{
if (args.length < 4)
return true;
if (args[2].equalsIgnoreCase("add"))
{
if (args.length < 5)
return true;
int i = 1;
try
{
i = Integer.parseInt(args[4]);
}
catch (NumberFormatException nfe)
{
if(plugin.debug) plugin.log.warning(nfe.getMessage());
}
Enchantment ech = Enchantment.getByName(args[3]
.toUpperCase());
if (ech != null)
{
player.getItemInHand().addUnsafeEnchantment(
ech, i);
player.sendMessage(ChatColor.GREEN
+ "Added enchantment.");
}
else
{
player.sendMessage(ChatColor.RED + args[3]
+ " :enchantment does not exist!");
}
return true;
}
if (args[2].equalsIgnoreCase("remove"))
{
ItemStack is = player.getItemInHand();
Map<Enchantment, Integer> hm = new HashMap<Enchantment, Integer>();
for (Enchantment e1 : is.getEnchantments().keySet())
{
if (!e1.getName().equalsIgnoreCase(args[3]))
{
hm.put(e1, is.getEnchantmentLevel(e1));
}
}
is.addUnsafeEnchantments(hm);
player.sendMessage(ChatColor.GREEN
+ "Removed enchantment.");
return true;
}
}
}
if (args[0].equalsIgnoreCase("reload")
&& sender.hasPermission("diablodrops.reload"))
{
plugin.getServer().getPluginManager().disablePlugin(plugin);
plugin.getServer().getPluginManager().enablePlugin(plugin);
plugin.reloadConfig();
plugin.getLogger().info("Reloaded");
sender.sendMessage(ChatColor.GREEN + "DiabloDrops Reloaded");
return true;
}
if (args[0].equalsIgnoreCase("repair"))
{
if (plugin.dropsAPI.canBeItem(player.getItemInHand()
.getType()))
{
player.getItemInHand().setDurability((short) 0);
player.sendMessage(ChatColor.GREEN + "Item repaired.");
return true;
}
player.sendMessage("Unable to repair item.");
return true;
}
if (plugin.dropsAPI.matchesTier(args[0]))
{
Tier tier = plugin.dropsAPI.getTier(args[0]);
CraftItemStack ci2 = plugin.dropsAPI.getItem(tier);
while (ci2 == null)
ci2 = plugin.dropsAPI.getItem(tier);
pi.addItem(ci2);
player.sendMessage(ChatColor.GREEN
+ "You have been given a " + ChatColor.WHITE
+ args[0] + ChatColor.GREEN + " DiabloDrops item.");
return true;
}
CraftItemStack ci2 = plugin.dropsAPI.getItem();
while (ci2 == null)
ci2 = plugin.dropsAPI.getItem();
pi.addItem(ci2);
player.sendMessage(ChatColor.GREEN
+ "You have been given a DiabloDrops item.");
return true;
}
}
|
diff --git a/examples/src/main/java/com/xebialabs/overthere/WriteFile.java b/examples/src/main/java/com/xebialabs/overthere/WriteFile.java
index bc56c57..9d8266d 100644
--- a/examples/src/main/java/com/xebialabs/overthere/WriteFile.java
+++ b/examples/src/main/java/com/xebialabs/overthere/WriteFile.java
@@ -1,47 +1,47 @@
package com.xebialabs.overthere;
import static com.xebialabs.overthere.ConnectionOptions.ADDRESS;
import static com.xebialabs.overthere.ConnectionOptions.OPERATING_SYSTEM;
import static com.xebialabs.overthere.ConnectionOptions.PASSWORD;
import static com.xebialabs.overthere.ConnectionOptions.USERNAME;
import static com.xebialabs.overthere.OperatingSystemFamily.UNIX;
import static com.xebialabs.overthere.ssh.SshConnectionBuilder.CONNECTION_TYPE;
import static com.xebialabs.overthere.ssh.SshConnectionType.SCP;
import static com.xebialabs.overthere.util.ConsoleOverthereProcessOutputHandler.consoleHandler;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import com.xebialabs.overthere.CmdLine;
import com.xebialabs.overthere.ConnectionOptions;
import com.xebialabs.overthere.Overthere;
import com.xebialabs.overthere.OverthereConnection;
import com.xebialabs.overthere.OverthereFile;
public class WriteFile {
public static void main(String[] args) throws IOException {
ConnectionOptions options = new ConnectionOptions();
options.set(ADDRESS, "unix-box");
options.set(USERNAME, "demo");
options.set(PASSWORD, "secret");
options.set(OPERATING_SYSTEM, UNIX);
options.set(CONNECTION_TYPE, SCP);
OverthereConnection connection = Overthere.getConnection("ssh", options);
try {
- OverthereFile motd = connection.getFile("/tmp/tmp2/new-motd");
+ OverthereFile motd = connection.getFile("/tmp/new-motd");
PrintWriter w = new PrintWriter(motd.getOutputStream());
try {
w.println("An Overthere a day keeps the doctor away");
w.println("Written on " + new java.util.Date() + " from " + InetAddress.getLocalHost() + " running " + System.getProperty("os.name") + " " + System.getProperty("os.version"));
} finally {
w.close();
}
connection.execute(consoleHandler(), CmdLine.build("cat", "/tmp/new-motd"));
} finally {
connection.close();
}
}
}
| true | true | public static void main(String[] args) throws IOException {
ConnectionOptions options = new ConnectionOptions();
options.set(ADDRESS, "unix-box");
options.set(USERNAME, "demo");
options.set(PASSWORD, "secret");
options.set(OPERATING_SYSTEM, UNIX);
options.set(CONNECTION_TYPE, SCP);
OverthereConnection connection = Overthere.getConnection("ssh", options);
try {
OverthereFile motd = connection.getFile("/tmp/tmp2/new-motd");
PrintWriter w = new PrintWriter(motd.getOutputStream());
try {
w.println("An Overthere a day keeps the doctor away");
w.println("Written on " + new java.util.Date() + " from " + InetAddress.getLocalHost() + " running " + System.getProperty("os.name") + " " + System.getProperty("os.version"));
} finally {
w.close();
}
connection.execute(consoleHandler(), CmdLine.build("cat", "/tmp/new-motd"));
} finally {
connection.close();
}
}
| public static void main(String[] args) throws IOException {
ConnectionOptions options = new ConnectionOptions();
options.set(ADDRESS, "unix-box");
options.set(USERNAME, "demo");
options.set(PASSWORD, "secret");
options.set(OPERATING_SYSTEM, UNIX);
options.set(CONNECTION_TYPE, SCP);
OverthereConnection connection = Overthere.getConnection("ssh", options);
try {
OverthereFile motd = connection.getFile("/tmp/new-motd");
PrintWriter w = new PrintWriter(motd.getOutputStream());
try {
w.println("An Overthere a day keeps the doctor away");
w.println("Written on " + new java.util.Date() + " from " + InetAddress.getLocalHost() + " running " + System.getProperty("os.name") + " " + System.getProperty("os.version"));
} finally {
w.close();
}
connection.execute(consoleHandler(), CmdLine.build("cat", "/tmp/new-motd"));
} finally {
connection.close();
}
}
|
diff --git a/src/com/github/noxan/aves/server/SocketServer.java b/src/com/github/noxan/aves/server/SocketServer.java
index 3822e64..ac606b0 100644
--- a/src/com/github/noxan/aves/server/SocketServer.java
+++ b/src/com/github/noxan/aves/server/SocketServer.java
@@ -1,142 +1,144 @@
/*
* Copyright (c) 2012, noxan
* See LICENSE for details.
*/
package com.github.noxan.aves.server;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import com.github.noxan.aves.net.Connection;
import com.github.noxan.aves.net.SocketConnection;
import com.github.noxan.aves.util.Tuple;
public class SocketServer implements Server, Runnable {
private String host;
private int port;
private BlockingQueue<Tuple<ServerEvent, Object>> serverEvents;
private ServerHandler handler;
private Set<Connection> connections;
private ServerSocket server;
private Thread serverThread;
private EventManager manager;
private Thread managerThread;
public SocketServer(ServerHandler handler) {
this("0.0.0.0", 1666, handler);
}
public SocketServer(String host, int port, ServerHandler handler) {
this.host = host;
this.port = port;
this.handler = handler;
serverEvents = new LinkedBlockingQueue<Tuple<ServerEvent, Object>>();
connections = new HashSet<Connection>();
}
@Override
public void start() {
try {
server = new ServerSocket();
server.setSoTimeout(1000);
server.bind(new InetSocketAddress(host, port));
manager = new EventManager();
serverThread = new Thread(this);
serverThread.start();
managerThread = new Thread(manager);
managerThread.start();
} catch(IOException e) {
e.printStackTrace();
}
}
@Override
public void run() {
while(true) {
try {
Socket socket = server.accept();
Connection connection = new SocketConnection(this, socket);
connection.start();
} catch(SocketTimeoutException e) {
} catch(IOException e) {
e.printStackTrace();
}
}
}
@Override
public Set<Connection> getConnections() {
return Collections.unmodifiableSet(connections);
}
public void broadcast(Object data) throws IOException {
for(Connection connection:connections) {
connection.write(data);
}
}
public void broadcast(Connection self, Object data) throws IOException {
for(Connection connection:connections) {
if(connection != self) {
connection.write(data);
}
}
}
@Override
public String getHost() {
return host;
}
@Override
public int getPort() {
return port;
}
public void offerEvent(ServerEvent type, Object data) {
serverEvents.add(new Tuple<ServerEvent, Object>(type, data));
}
private class EventManager implements Runnable {
@Override
public void run() {
while(true) {
Tuple<ServerEvent, Object> event = serverEvents.poll();
if(event != null) {
switch(event.getFirst()) {
- case DATA_READ:
- Tuple<?, ?> read = (Tuple<?, ?>)event.getSecond();
- handler.readData((Connection)read.getFirst(), read.getSecond());
- break;
- case CLIENT_CONNECT:
- connections.add((Connection)event.getSecond());
- handler.clientConnect((Connection)event.getSecond());
- break;
- case CLIENT_DISCONNECT:
- handler.clientDisconnect((Connection)event.getSecond());
- connections.remove((Connection)event.getSecond());
- break;
- case CLIENT_LOST:
- handler.clientLost((Connection)event.getSecond());
- connections.remove((Connection)event.getSecond());
- break;
+ case DATA_READ:
+ Tuple<?, ?> read = (Tuple<?, ?>) event.getSecond();
+ handler.readData((Connection) read.getFirst(), read.getSecond());
+ break;
+ case CLIENT_CONNECT:
+ connections.add((Connection) event.getSecond());
+ handler.clientConnect((Connection) event.getSecond());
+ break;
+ case CLIENT_DISCONNECT:
+ handler.clientDisconnect((Connection) event.getSecond());
+ connections.remove((Connection) event.getSecond());
+ break;
+ case CLIENT_LOST:
+ handler.clientLost((Connection) event.getSecond());
+ connections.remove((Connection) event.getSecond());
+ break;
+ case DATA_WRITE:
+ break;
}
}
}
}
}
}
| true | true | public void run() {
while(true) {
Tuple<ServerEvent, Object> event = serverEvents.poll();
if(event != null) {
switch(event.getFirst()) {
case DATA_READ:
Tuple<?, ?> read = (Tuple<?, ?>)event.getSecond();
handler.readData((Connection)read.getFirst(), read.getSecond());
break;
case CLIENT_CONNECT:
connections.add((Connection)event.getSecond());
handler.clientConnect((Connection)event.getSecond());
break;
case CLIENT_DISCONNECT:
handler.clientDisconnect((Connection)event.getSecond());
connections.remove((Connection)event.getSecond());
break;
case CLIENT_LOST:
handler.clientLost((Connection)event.getSecond());
connections.remove((Connection)event.getSecond());
break;
}
}
}
}
| public void run() {
while(true) {
Tuple<ServerEvent, Object> event = serverEvents.poll();
if(event != null) {
switch(event.getFirst()) {
case DATA_READ:
Tuple<?, ?> read = (Tuple<?, ?>) event.getSecond();
handler.readData((Connection) read.getFirst(), read.getSecond());
break;
case CLIENT_CONNECT:
connections.add((Connection) event.getSecond());
handler.clientConnect((Connection) event.getSecond());
break;
case CLIENT_DISCONNECT:
handler.clientDisconnect((Connection) event.getSecond());
connections.remove((Connection) event.getSecond());
break;
case CLIENT_LOST:
handler.clientLost((Connection) event.getSecond());
connections.remove((Connection) event.getSecond());
break;
case DATA_WRITE:
break;
}
}
}
}
|
diff --git a/main/src/cgeo/geocaching/cgeocaches.java b/main/src/cgeo/geocaching/cgeocaches.java
index 23eeec4b4..032438531 100644
--- a/main/src/cgeo/geocaching/cgeocaches.java
+++ b/main/src/cgeo/geocaching/cgeocaches.java
@@ -1,2237 +1,2242 @@
package cgeo.geocaching;
import cgeo.geocaching.activity.AbstractActivity;
import cgeo.geocaching.activity.AbstractListActivity;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.activity.Progress;
import cgeo.geocaching.apps.cache.navi.NavigationAppFactory;
import cgeo.geocaching.apps.cachelist.CacheListAppFactory;
import cgeo.geocaching.enumerations.CacheListType;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.enumerations.LogType;
import cgeo.geocaching.enumerations.StatusCode;
import cgeo.geocaching.export.ExportFactory;
import cgeo.geocaching.files.GPXImporter;
import cgeo.geocaching.filter.FilterUserInterface;
import cgeo.geocaching.filter.IFilter;
import cgeo.geocaching.geopoint.Geopoint;
import cgeo.geocaching.maps.CGeoMap;
import cgeo.geocaching.network.Network;
import cgeo.geocaching.network.Parameters;
import cgeo.geocaching.sorting.CacheComparator;
import cgeo.geocaching.sorting.DateComparator;
import cgeo.geocaching.sorting.DifficultyComparator;
import cgeo.geocaching.sorting.EventDateComparator;
import cgeo.geocaching.sorting.FindsComparator;
import cgeo.geocaching.sorting.GeocodeComparator;
import cgeo.geocaching.sorting.InventoryComparator;
import cgeo.geocaching.sorting.NameComparator;
import cgeo.geocaching.sorting.PopularityComparator;
import cgeo.geocaching.sorting.RatingComparator;
import cgeo.geocaching.sorting.SizeComparator;
import cgeo.geocaching.sorting.StateComparator;
import cgeo.geocaching.sorting.TerrainComparator;
import cgeo.geocaching.sorting.VisitComparator;
import cgeo.geocaching.sorting.VoteComparator;
import cgeo.geocaching.ui.CacheListAdapter;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.RunnableWithArgument;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SubMenu;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class cgeocaches extends AbstractListActivity {
private static final int MAX_LIST_ITEMS = 1000;
private static final String EXTRAS_LIST_TYPE = "type";
private static final String EXTRAS_COORDS = "coords";
private static final int MENU_REFRESH_STORED = 2;
private static final int MENU_CACHE_DETAILS = 4;
private static final int MENU_DROP_CACHES = 5;
private static final int MENU_IMPORT_GPX = 6;
private static final int MENU_CREATE_LIST = 7;
private static final int MENU_DROP_LIST = 8;
private static final int MENU_INVERT_SELECTION = 9;
private static final int MENU_SORT_DISTANCE = 10;
private static final int MENU_SORT_DIFFICULTY = 11;
private static final int MENU_SORT_TERRAIN = 12;
private static final int MENU_SORT_SIZE = 13;
private static final int MENU_SORT_FAVORITES = 14;
private static final int MENU_SORT_NAME = 15;
private static final int MENU_SORT_GEOCODE = 16;
private static final int MENU_SWITCH_LIST = 17;
private static final int MENU_SORT_RATING = 18;
private static final int MENU_SORT_VOTE = 19;
private static final int MENU_SORT_INVENTORY = 20;
private static final int MENU_IMPORT_WEB = 21;
private static final int MENU_EXPORT = 22;
private static final int MENU_REMOVE_FROM_HISTORY = 23;
private static final int MENU_DROP_CACHE = 24;
private static final int MENU_MOVE_TO_LIST = 25;
private static final int MENU_SWITCH_SELECT_MODE = 52;
private static final int SUBMENU_SHOW_MAP = 54;
private static final int SUBMENU_MANAGE_LISTS = 55;
private static final int SUBMENU_MANAGE_OFFLINE = 56;
private static final int SUBMENU_SORT = 57;
private static final int SUBMENU_IMPORT = 59;
private static final int SUBMENU_MANAGE_HISTORY = 60;
private static final int MENU_SORT_DATE = 61;
private static final int MENU_SORT_FINDS = 62;
private static final int MENU_SORT_STATE = 63;
private static final int MENU_RENAME_LIST = 64;
private static final int MENU_DROP_CACHES_AND_LIST = 65;
private static final int MENU_DEFAULT_NAVIGATION = 66;
private static final int MENU_NAVIGATION = 69;
private static final int MENU_STORE_CACHE = 73;
private static final int MENU_FILTER = 74;
private static final int MSG_DONE = -1;
private static final int MSG_CANCEL = -99;
private String action = null;
private CacheListType type = null;
private Geopoint coords = null;
private CacheType cacheType = Settings.getCacheType();
private String keyword = null;
private String address = null;
private String username = null;
private SearchResult search = null;
private List<cgCache> cacheList = new ArrayList<cgCache>();
private CacheListAdapter adapter = null;
private LayoutInflater inflater = null;
private View listFooter = null;
private TextView listFooterText = null;
private Progress progress = new Progress();
private Float northHeading = 0f;
private cgGeo geo = null;
private cgDirection dir = null;
private UpdateLocationCallback geoUpdate = new UpdateLocation();
private UpdateDirectionCallback dirUpdate = new UpdateDirection();
private String title = "";
private int detailTotal = 0;
private int detailProgress = 0;
private long detailProgressTime = 0L;
private LoadDetailsThread threadDetails = null;
private LoadFromWebThread threadWeb = null;
private DropDetailsThread threadR = null;
private RemoveFromHistoryThread threadH = null;
private int listId = StoredList.TEMPORARY_LIST_ID;
private GeocodeComparator gcComparator = new GeocodeComparator();
private Handler loadCachesHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
try {
if (search != null) {
setTitle(title + " [" + search.getCount() + "]");
cacheList.clear();
final Set<cgCache> caches = search.getCachesFromSearchResult(LoadFlags.LOAD_CACHE_OR_DB);
if (CollectionUtils.isNotEmpty(caches)) {
cacheList.addAll(caches);
Collections.sort(cacheList, gcComparator);
}
} else {
setTitle(title);
}
setAdapter();
setDateComparatorForEventList();
if (cacheList == null) {
showToast(res.getString(R.string.err_list_load_fail));
}
setMoreCaches();
if (cacheList != null && search != null && search.getError() == StatusCode.UNAPPROVED_LICENSE) {
AlertDialog.Builder dialog = new AlertDialog.Builder(cgeocaches.this);
dialog.setTitle(res.getString(R.string.license));
dialog.setMessage(res.getString(R.string.err_license));
dialog.setCancelable(true);
dialog.setNegativeButton(res.getString(R.string.license_dismiss), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Network.clearCookies();
dialog.cancel();
}
});
dialog.setPositiveButton(res.getString(R.string.license_show), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Network.clearCookies();
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.geocaching.com/software/agreement.aspx?ID=0")));
}
});
AlertDialog alert = dialog.create();
alert.show();
} else if (app != null && search != null && search.getError() != null) {
showToast(res.getString(R.string.err_download_fail) + " " + search.getError().getErrorString(res) + ".");
hideLoading();
showProgress(false);
finish();
return;
}
if (geo != null && geo.coordsNow != null) {
adapter.setActualCoordinates(geo.coordsNow);
adapter.setActualHeading(northHeading);
}
} catch (Exception e) {
showToast(res.getString(R.string.err_detail_cache_find_any));
Log.e("cgeocaches.loadCachesHandler: " + e.toString());
hideLoading();
showProgress(false);
finish();
return;
}
try {
hideLoading();
showProgress(false);
} catch (Exception e2) {
Log.e("cgeocaches.loadCachesHandler.2: " + e2.toString());
}
if (adapter != null) {
adapter.setSelectMode(false, true);
}
}
};
private Handler loadNextPageHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
try {
if (search != null) {
setTitle(title + " [" + search.getCount() + "]");
cacheList.clear();
final Set<cgCache> caches = search.getCachesFromSearchResult(LoadFlags.LOAD_CACHE_OR_DB);
if (CollectionUtils.isNotEmpty(caches)) {
cacheList.addAll(caches);
caches.clear();
Collections.sort(cacheList, gcComparator);
}
if (adapter != null) {
adapter.reFilter();
}
} else {
setTitle(title);
}
setAdapter();
if (cacheList == null) {
showToast(res.getString(R.string.err_list_load_fail));
}
setMoreCaches();
if (search != null && search.getError() != null) {
showToast(res.getString(R.string.err_download_fail) + " " + search.getError().getErrorString(res) + ".");
listFooter.setOnClickListener(new MoreCachesListener());
hideLoading();
showProgress(false);
finish();
return;
}
if (geo != null && geo.coordsNow != null) {
adapter.setActualCoordinates(geo.coordsNow);
adapter.setActualHeading(northHeading);
}
} catch (Exception e) {
showToast(res.getString(R.string.err_detail_cache_find_next));
Log.e("cgeocaches.loadNextPageHandler: " + e.toString());
}
hideLoading();
showProgress(false);
if (adapter != null) {
adapter.setSelectMode(false, true);
}
}
};
private Handler loadDetailsHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
setAdapter();
if (msg.what > -1) {
cacheList.get(msg.what).setStatusChecked(false);
if (adapter != null) {
adapter.notifyDataSetChanged();
}
int secondsElapsed = (int) ((System.currentTimeMillis() - detailProgressTime) / 1000);
int minutesRemaining = ((detailTotal - detailProgress) * secondsElapsed / ((detailProgress > 0) ? detailProgress : 1) / 60);
progress.setProgress(detailProgress);
if (minutesRemaining < 1) {
progress.setMessage(res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm));
} else if (minutesRemaining == 1) {
progress.setMessage(res.getString(R.string.caches_downloading) + " " + minutesRemaining + " " + res.getString(R.string.caches_eta_min));
} else {
progress.setMessage(res.getString(R.string.caches_downloading) + " " + minutesRemaining + " " + res.getString(R.string.caches_eta_mins));
}
} else if (msg.what == MSG_CANCEL) {
if (threadDetails != null) {
threadDetails.kill();
}
} else {
if (cacheList != null && search != null) {
final Set<cgCache> cacheListTmp = search.getCachesFromSearchResult(LoadFlags.LOAD_CACHE_OR_DB);
if (CollectionUtils.isNotEmpty(cacheListTmp)) {
cacheList.clear();
cacheList.addAll(cacheListTmp);
cacheListTmp.clear();
Collections.sort(cacheList, gcComparator);
}
}
if (geo != null && geo.coordsNow != null) {
adapter.setActualCoordinates(geo.coordsNow);
adapter.setActualHeading(northHeading);
}
showProgress(false);
progress.dismiss();
startGeoAndDir();
}
}
};
private Handler downloadFromWebHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
setAdapter();
if (adapter != null) {
adapter.notifyDataSetChanged();
}
if (msg.what == 0) { //no caches
progress.setMessage(res.getString(R.string.web_import_waiting));
} else if (msg.what == 1) { //cache downloading
progress.setMessage(res.getString(R.string.web_downloading) + " " + (String) msg.obj + "...");
} else if (msg.what == 2) { //Cache downloaded
progress.setMessage(res.getString(R.string.web_downloaded) + " " + (String) msg.obj + ".");
refreshCurrentList();
} else if (msg.what == -2) {
progress.dismiss();
startGeoAndDir();
showToast(res.getString(R.string.sendToCgeo_download_fail));
finish();
} else if (msg.what == -3) {
progress.dismiss();
startGeoAndDir();
showToast(res.getString(R.string.sendToCgeo_no_registration));
finish();
} else if (msg.what == MSG_CANCEL) {
if (threadWeb != null) {
threadWeb.kill();
}
} else {
if (adapter != null) {
adapter.setSelectMode(false, true);
}
cacheList.clear();
final Set<cgCache> cacheListTmp = search.getCachesFromSearchResult(LoadFlags.LOAD_CACHE_OR_DB);
if (CollectionUtils.isNotEmpty(cacheListTmp)) {
cacheList.addAll(cacheListTmp);
cacheListTmp.clear();
Collections.sort(cacheList, gcComparator);
}
startGeoAndDir();
progress.dismiss();
}
}
};
private Handler dropDetailsHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
if (msg.what == MSG_CANCEL) {
if (threadR != null) {
threadR.kill();
}
} else {
if (adapter != null) {
adapter.setSelectMode(false, true);
}
refreshCurrentList();
cacheList.clear();
final Set<cgCache> cacheListTmp = search.getCachesFromSearchResult(LoadFlags.LOAD_CACHE_OR_DB);
if (CollectionUtils.isNotEmpty(cacheListTmp)) {
cacheList.addAll(cacheListTmp);
cacheListTmp.clear();
Collections.sort(cacheList, gcComparator);
}
progress.dismiss();
}
}
};
private Handler removeFromHistoryHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
setAdapter();
if (msg.what > -1) {
cacheList.get(msg.what).setStatusChecked(false);
progress.setProgress(detailProgress);
} else if (msg.what == MSG_CANCEL) {
if (threadH != null) {
threadH.kill();
}
} else {
if (adapter != null) {
adapter.setSelectMode(false, true);
}
// reload history list
(new LoadByHistoryThread(loadCachesHandler)).start();
progress.dismiss();
}
}
};
private Handler importGpxAttachementFinishedHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
refreshCurrentList();
}
};
private ContextMenuInfo lastMenuInfo;
private String contextMenuGeocode = "";
/**
* the navigation menu item for the cache list (not the context menu!), or <code>null</code>
*/
private MenuItem navigationMenu;
public cgeocaches() {
super(true);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// init
app.setAction(action);
setTheme();
setContentView(R.layout.caches);
setTitle("caches");
// get parameters
final Bundle extras = getIntent().getExtras();
if (extras != null) {
Object typeObject = extras.get(EXTRAS_LIST_TYPE);
type = (typeObject instanceof CacheListType) ? (CacheListType) typeObject : CacheListType.OFFLINE;
coords = (Geopoint) extras.getParcelable(EXTRAS_COORDS);
+ // FIXME: this code seems dubious, as adding a fake Geopoint with valid
+ // coordinates should not be required.
+ if (coords == null) {
+ coords = new Geopoint(0.0, 0.0);
+ }
cacheType = Settings.getCacheType();
keyword = extras.getString("keyword");
address = extras.getString("address");
username = extras.getString("username");
}
if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
type = CacheListType.OFFLINE;
if (coords == null) {
coords = new Geopoint(0.0, 0.0);
}
}
init();
Thread threadPure;
cgSearchThread thread;
switch (type) {
case OFFLINE:
listId = Settings.getLastList();
if (listId <= StoredList.TEMPORARY_LIST_ID) {
listId = StoredList.STANDARD_LIST_ID;
title = res.getString(R.string.stored_caches_button);
} else {
final StoredList list = app.getList(listId);
// list.id may be different if listId was not valid
listId = list.id;
title = list.title;
}
setTitle(title);
showProgress(true);
setLoadingCaches();
threadPure = new LoadByOfflineThread(loadCachesHandler, coords, listId);
threadPure.start();
break;
case HISTORY:
title = res.getString(R.string.caches_history);
setTitle(title);
showProgress(true);
setLoadingCaches();
threadPure = new LoadByHistoryThread(loadCachesHandler);
threadPure.start();
break;
case NEAREST:
action = "pending";
title = res.getString(R.string.caches_nearby);
setTitle(title);
showProgress(true);
setLoadingCaches();
thread = new LoadByCoordsThread(loadCachesHandler, coords);
thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread));
thread.start();
break;
case COORDINATE:
action = "planning";
title = coords.toString();
setTitle(title);
showProgress(true);
setLoadingCaches();
thread = new LoadByCoordsThread(loadCachesHandler, coords);
thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread));
thread.start();
break;
case KEYWORD:
title = keyword;
setTitle(title);
showProgress(true);
setLoadingCaches();
thread = new LoadByKeywordThread(loadCachesHandler, keyword);
thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread));
thread.start();
break;
case ADDRESS:
action = "planning";
if (StringUtils.isNotBlank(address)) {
title = address;
setTitle(title);
showProgress(true);
setLoadingCaches();
} else {
title = coords.toString();
setTitle(title);
showProgress(true);
setLoadingCaches();
}
thread = new LoadByCoordsThread(loadCachesHandler, coords);
thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread));
thread.start();
break;
case USERNAME:
title = username;
setTitle(title);
showProgress(true);
setLoadingCaches();
thread = new LoadByUserNameThread(loadCachesHandler, username);
thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread));
thread.start();
break;
case OWNER:
title = username;
setTitle(title);
showProgress(true);
setLoadingCaches();
thread = new LoadByOwnerThread(loadCachesHandler, username);
thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread));
thread.start();
break;
case MAP:
title = res.getString(R.string.map_map);
setTitle(title);
showProgress(true);
SearchResult result = extras != null ? (SearchResult) extras.get("search") : null;
search = new SearchResult(result);
loadCachesHandler.sendMessage(Message.obtain());
break;
default:
title = "caches";
setTitle(title);
Log.e("cgeocaches.onCreate: No action or unknown action specified");
break;
}
prepareFilterBar();
if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
importGpxAttachement();
}
}
private void importGpxAttachement() {
new AlertDialog.Builder(this)
.setTitle(res.getString(R.string.gpx_import_title))
.setMessage(res.getString(R.string.gpx_import_confirm))
.setCancelable(false)
.setPositiveButton(getString(android.R.string.yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
new GPXImporter(cgeocaches.this, listId, importGpxAttachementFinishedHandler).importGPX();
}
})
.setNegativeButton(getString(android.R.string.no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.create()
.show();
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
init();
}
@Override
public void onResume() {
super.onResume();
init();
if (adapter != null && geo != null && geo.coordsNow != null) {
adapter.setActualCoordinates(geo.coordsNow);
adapter.setActualHeading(northHeading);
}
if (adapter != null) {
adapter.setSelectMode(false, true);
if (geo != null && geo.coordsNow != null) {
adapter.forceSort(geo.coordsNow);
}
}
if (loadCachesHandler != null && search != null) {
loadCachesHandler.sendEmptyMessage(0);
}
// refresh standard list if it has changed (new caches downloaded)
if (type == CacheListType.OFFLINE && listId >= StoredList.STANDARD_LIST_ID && search != null) {
SearchResult newSearch = cgBase.searchByStored(coords, cacheType, listId);
if (newSearch != null && newSearch.getTotal() != search.getTotal()) {
refreshCurrentList();
}
}
}
@Override
public void onDestroy() {
if (adapter != null) {
adapter = null;
}
removeGeoAndDir();
super.onDestroy();
}
@Override
public void onStop() {
removeGeoAndDir();
super.onStop();
}
@Override
public void onPause() {
removeGeoAndDir();
super.onPause();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_FILTER, 0, res.getString(R.string.caches_filter)).setIcon(R.drawable.ic_menu_filter);
SubMenu subMenuSort = menu.addSubMenu(0, SUBMENU_SORT, 0, res.getString(R.string.caches_sort)).setIcon(android.R.drawable.ic_menu_sort_alphabetically);
subMenuSort.setHeaderTitle(res.getString(R.string.caches_sort_title));
// sort the context menu labels alphabetically for easier reading
Map<String, Integer> comparators = new HashMap<String, Integer>();
comparators.put(res.getString(R.string.caches_sort_distance), MENU_SORT_DISTANCE);
comparators.put(res.getString(R.string.caches_sort_difficulty), MENU_SORT_DIFFICULTY);
comparators.put(res.getString(R.string.caches_sort_terrain), MENU_SORT_TERRAIN);
comparators.put(res.getString(R.string.caches_sort_size), MENU_SORT_SIZE);
comparators.put(res.getString(R.string.caches_sort_favorites), MENU_SORT_FAVORITES);
comparators.put(res.getString(R.string.caches_sort_name), MENU_SORT_NAME);
comparators.put(res.getString(R.string.caches_sort_gccode), MENU_SORT_GEOCODE);
comparators.put(res.getString(R.string.caches_sort_rating), MENU_SORT_RATING);
comparators.put(res.getString(R.string.caches_sort_vote), MENU_SORT_VOTE);
comparators.put(res.getString(R.string.caches_sort_inventory), MENU_SORT_INVENTORY);
comparators.put(res.getString(R.string.caches_sort_date), MENU_SORT_DATE);
comparators.put(res.getString(R.string.caches_sort_finds), MENU_SORT_FINDS);
comparators.put(res.getString(R.string.caches_sort_state), MENU_SORT_STATE);
List<String> sortedLabels = new ArrayList<String>(comparators.keySet());
Collections.sort(sortedLabels);
for (String label : sortedLabels) {
Integer id = comparators.get(label);
subMenuSort.add(1, id.intValue(), 0, label).setCheckable(true).setChecked(id.intValue() == MENU_SORT_DISTANCE);
}
subMenuSort.setGroupCheckable(1, true, true);
menu.add(0, MENU_SWITCH_SELECT_MODE, 0, res.getString(R.string.caches_select_mode)).setIcon(android.R.drawable.ic_menu_agenda);
menu.add(0, MENU_INVERT_SELECTION, 0, res.getString(R.string.caches_select_invert)).setIcon(R.drawable.ic_menu_mark);
if (type == CacheListType.OFFLINE) {
SubMenu subMenu = menu.addSubMenu(0, SUBMENU_MANAGE_OFFLINE, 0, res.getString(R.string.caches_manage)).setIcon(android.R.drawable.ic_menu_save);
subMenu.add(0, MENU_DROP_CACHES, 0, res.getString(R.string.caches_drop_all)); // delete saved caches
subMenu.add(0, MENU_DROP_CACHES_AND_LIST, 0, res.getString(R.string.caches_drop_all_and_list));
subMenu.add(0, MENU_REFRESH_STORED, 0, res.getString(R.string.cache_offline_refresh)); // download details for all caches
subMenu.add(0, MENU_MOVE_TO_LIST, 0, res.getString(R.string.cache_menu_move_list));
subMenu.add(0, MENU_EXPORT, 0, res.getString(R.string.export)); // export caches
if (Settings.getWebDeviceCode() == null) {
menu.add(0, MENU_IMPORT_GPX, 0, res.getString(R.string.gpx_import_title)).setIcon(android.R.drawable.ic_menu_upload); // import gpx file
} else {
SubMenu subMenuImport = menu.addSubMenu(0, SUBMENU_IMPORT, 0, res.getString(R.string.import_title)).setIcon(android.R.drawable.ic_menu_upload); // import
subMenuImport.add(1, MENU_IMPORT_GPX, 0, res.getString(R.string.gpx_import_title)).setCheckable(false).setChecked(false);
subMenuImport.add(1, MENU_IMPORT_WEB, 0, res.getString(R.string.web_import_title)).setCheckable(false).setChecked(false);
}
} else {
if (type == CacheListType.HISTORY) {
SubMenu subMenu = menu.addSubMenu(0, SUBMENU_MANAGE_HISTORY, 0, res.getString(R.string.caches_manage)).setIcon(android.R.drawable.ic_menu_save);
subMenu.add(0, MENU_REMOVE_FROM_HISTORY, 0, res.getString(R.string.cache_clear_history)); // remove from history
subMenu.add(0, MENU_EXPORT, 0, res.getString(R.string.export)); // export caches
}
menu.add(0, MENU_REFRESH_STORED, 0, res.getString(R.string.caches_store_offline)).setIcon(android.R.drawable.ic_menu_set_as); // download details for all caches
}
navigationMenu = CacheListAppFactory.addMenuItems(menu, this, res);
if (type == CacheListType.OFFLINE) {
SubMenu subMenu = menu.addSubMenu(0, SUBMENU_MANAGE_LISTS, 0, res.getString(R.string.list_menu)).setIcon(android.R.drawable.ic_menu_more);
subMenu.add(0, MENU_CREATE_LIST, 0, res.getString(R.string.list_menu_create));
subMenu.add(0, MENU_DROP_LIST, 0, res.getString(R.string.list_menu_drop));
subMenu.add(0, MENU_RENAME_LIST, 0, res.getString(R.string.list_menu_rename));
subMenu.add(0, MENU_SWITCH_LIST, 0, res.getString(R.string.list_menu_change));
}
return true;
}
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
super.onPrepareOptionsMenu(menu);
try {
if (adapter != null && adapter.getSelectMode()) {
menu.findItem(MENU_SWITCH_SELECT_MODE).setTitle(res.getString(R.string.caches_select_mode_exit))
.setIcon(R.drawable.ic_menu_clear_playlist);
menu.findItem(MENU_INVERT_SELECTION).setVisible(true);
} else {
menu.findItem(MENU_SWITCH_SELECT_MODE).setTitle(res.getString(R.string.caches_select_mode))
.setIcon(android.R.drawable.ic_menu_agenda);
menu.findItem(MENU_INVERT_SELECTION).setVisible(false);
}
boolean hasSelection = adapter != null && adapter.getChecked() > 0;
boolean isNonDefaultList = listId != StoredList.STANDARD_LIST_ID;
if (type == CacheListType.OFFLINE) { // only offline list
setMenuItemLabel(menu, MENU_DROP_CACHES, R.string.caches_drop_selected, R.string.caches_drop_all);
menu.findItem(MENU_DROP_CACHES_AND_LIST).setVisible(!hasSelection && isNonDefaultList);
setMenuItemLabel(menu, MENU_REFRESH_STORED, R.string.caches_refresh_selected, R.string.caches_refresh_all);
setMenuItemLabel(menu, MENU_MOVE_TO_LIST, R.string.caches_move_selected, R.string.caches_move_all);
} else { // search and history list (all other than offline)
setMenuItemLabel(menu, MENU_REFRESH_STORED, R.string.caches_store_selected, R.string.caches_store_offline);
}
// Hide menus if cache-list is empty
int[] hideIfEmptyList = new int[] {
MENU_SWITCH_SELECT_MODE,
SUBMENU_MANAGE_OFFLINE,
SUBMENU_MANAGE_HISTORY,
SUBMENU_SHOW_MAP,
SUBMENU_SORT,
MENU_REFRESH_STORED };
boolean menuVisible = cacheList.size() > 0;
for (int itemId : hideIfEmptyList) {
MenuItem item = menu.findItem(itemId);
if (null != item) {
item.setVisible(menuVisible);
}
}
if (navigationMenu != null) {
navigationMenu.setVisible(menuVisible);
}
MenuItem item = menu.findItem(MENU_DROP_LIST);
if (item != null) {
item.setVisible(isNonDefaultList);
}
item = menu.findItem(MENU_RENAME_LIST);
if (item != null) {
item.setVisible(isNonDefaultList);
}
boolean multipleLists = app.getLists().size() >= 2;
item = menu.findItem(MENU_SWITCH_LIST);
if (item != null) {
item.setVisible(multipleLists);
}
item = menu.findItem(MENU_MOVE_TO_LIST);
if (item != null) {
item.setVisible(multipleLists);
}
setMenuItemLabel(menu, MENU_REMOVE_FROM_HISTORY, R.string.cache_remove_from_history, R.string.cache_clear_history);
setMenuItemLabel(menu, MENU_EXPORT, R.string.export, R.string.export);
} catch (Exception e) {
Log.e("cgeocaches.onPrepareOptionsMenu", e);
}
return true;
}
private void setMenuItemLabel(final Menu menu, final int menuId, final int resIdSelection, final int resId) {
final MenuItem menuItem = menu.findItem(menuId);
if (menuItem == null) {
return;
}
boolean hasSelection = adapter != null && adapter.getChecked() > 0;
if (hasSelection) {
menuItem.setTitle(res.getString(resIdSelection) + " (" + adapter.getChecked() + ")");
} else {
menuItem.setTitle(res.getString(resId));
}
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case MENU_SWITCH_SELECT_MODE:
if (adapter != null) {
adapter.switchSelectMode();
}
invalidateOptionsMenuCompatible();
return true;
case MENU_REFRESH_STORED:
refreshStored();
invalidateOptionsMenuCompatible();
return true;
case MENU_DROP_CACHES:
dropStored(false);
invalidateOptionsMenuCompatible();
return false;
case MENU_DROP_CACHES_AND_LIST:
dropStored(true);
invalidateOptionsMenuCompatible();
return true;
case MENU_IMPORT_GPX:
importGpx();
invalidateOptionsMenuCompatible();
return false;
case MENU_CREATE_LIST:
new StoredList.UserInterface(this).promptForListCreation(null);
invalidateOptionsMenuCompatible();
return false;
case MENU_DROP_LIST:
removeList(true);
invalidateOptionsMenuCompatible();
return false;
case MENU_RENAME_LIST:
renameList();
return false;
case MENU_INVERT_SELECTION:
if (adapter != null) {
adapter.invertSelection();
}
invalidateOptionsMenuCompatible();
return false;
case MENU_SORT_DISTANCE:
setComparator(item, null);
return false;
case MENU_SORT_DIFFICULTY:
setComparator(item, new DifficultyComparator());
return false;
case MENU_SORT_TERRAIN:
setComparator(item, new TerrainComparator());
return false;
case MENU_SORT_SIZE:
setComparator(item, new SizeComparator());
return false;
case MENU_SORT_FAVORITES:
setComparator(item, new PopularityComparator());
return false;
case MENU_SORT_NAME:
setComparator(item, new NameComparator());
return false;
case MENU_SORT_GEOCODE:
setComparator(item, new GeocodeComparator());
return false;
case MENU_SWITCH_LIST:
selectList(null);
invalidateOptionsMenuCompatible();
return false;
case MENU_SORT_RATING:
setComparator(item, new RatingComparator());
return false;
case MENU_SORT_VOTE:
setComparator(item, new VoteComparator());
return false;
case MENU_SORT_INVENTORY:
setComparator(item, new InventoryComparator());
return false;
case MENU_SORT_DATE:
setComparator(item, new DateComparator());
return true;
case MENU_SORT_FINDS:
setComparator(item, new FindsComparator(app));
return true;
case MENU_SORT_STATE:
setComparator(item, new StateComparator());
return true;
case MENU_FILTER:
new FilterUserInterface(this).selectFilter(new RunnableWithArgument<IFilter>() {
@Override
public void run(IFilter selectedFilter) {
if (selectedFilter != null) {
setFilter(selectedFilter);
}
else {
// clear filter
if (adapter != null) {
setFilter(null);
}
}
}
});
return true;
case MENU_IMPORT_WEB:
importWeb();
return false;
case MENU_EXPORT:
exportCaches();
return false;
case MENU_REMOVE_FROM_HISTORY:
removeFromHistoryCheck();
invalidateOptionsMenuCompatible();
return false;
case MENU_MOVE_TO_LIST:
moveCachesToOtherList();
invalidateOptionsMenuCompatible();
return true;
}
return CacheListAppFactory.onMenuItemSelected(item, geo, cacheList, this, search);
}
private void setComparator(MenuItem item,
CacheComparator comparator) {
if (adapter != null) {
adapter.setComparator(comparator);
}
item.setChecked(true);
}
@Override
public void onCreateContextMenu(final ContextMenu menu, final View view, final ContextMenu.ContextMenuInfo info) {
super.onCreateContextMenu(menu, view, info);
if (adapter == null) {
return;
}
AdapterContextMenuInfo adapterInfo = null;
try {
adapterInfo = (AdapterContextMenuInfo) info;
} catch (Exception e) {
Log.w("cgeocaches.onCreateContextMenu: " + e.toString());
}
if (adapterInfo == null || adapterInfo.position >= adapter.getCount()) {
return;
}
final cgCache cache = adapter.getItem(adapterInfo.position);
if (StringUtils.isNotBlank(cache.getName())) {
menu.setHeaderTitle(cache.getName());
} else {
menu.setHeaderTitle(cache.getGeocode());
}
contextMenuGeocode = cache.getGeocode();
if (cache.getCoords() != null) {
menu.add(0, MENU_DEFAULT_NAVIGATION, 0, NavigationAppFactory.getDefaultNavigationApplication(this).getName());
menu.add(1, MENU_NAVIGATION, 0, res.getString(R.string.cache_menu_navigate)).setIcon(android.R.drawable.ic_menu_mapmode);
addVisitMenu(menu, cache);
menu.add(0, MENU_CACHE_DETAILS, 0, res.getString(R.string.cache_menu_details));
}
if (cache.getListId() >= 1) {
menu.add(0, MENU_DROP_CACHE, 0, res.getString(R.string.cache_offline_drop));
final List<StoredList> cacheLists = app.getLists();
final int listCount = cacheLists.size();
if (listCount > 1) {
menu.add(0, MENU_MOVE_TO_LIST, 0, res.getString(R.string.cache_menu_move_list));
}
}
else {
menu.add(0, MENU_STORE_CACHE, 0, res.getString(R.string.cache_offline_store));
}
}
private void moveCachesToOtherList() {
new StoredList.UserInterface(this).promptForListSelection(R.string.cache_menu_move_list, new RunnableWithArgument<Integer>() {
@Override
public void run(Integer newListId) {
final boolean moveAll = adapter.getChecked() == 0;
for (final cgCache c : Collections.unmodifiableList(cacheList)) {
if (moveAll || c.isStatusChecked()) {
app.moveToList(c.getGeocode(), newListId);
}
}
adapter.resetChecks();
refreshCurrentList();
}
});
}
@Override
public boolean onContextItemSelected(MenuItem item) {
final int id = item.getItemId();
ContextMenu.ContextMenuInfo info = item.getMenuInfo();
// restore menu info for sub menu items, see
// https://code.google.com/p/android/issues/detail?id=7139
if (info == null) {
info = lastMenuInfo;
lastMenuInfo = null;
}
AdapterContextMenuInfo adapterInfo = null;
try {
adapterInfo = (AdapterContextMenuInfo) info;
} catch (Exception e) {
Log.w("cgeocaches.onContextItemSelected: " + e.toString());
}
if (id == MENU_DEFAULT_NAVIGATION) {
final cgCache cache = getCacheFromAdapter(adapterInfo);
NavigationAppFactory.startDefaultNavigationApplication(geo, this, cache, null, null);
return true;
} else if (id == MENU_NAVIGATION) {
final cgCache cache = getCacheFromAdapter(adapterInfo);
NavigationAppFactory.showNavigationMenu(geo, this, cache, null, null);
return true;
} else if (id == MENU_LOG_VISIT) {
return getCacheFromAdapter(adapterInfo).logVisit(this);
} else if (id == MENU_CACHE_DETAILS) {
final Intent cachesIntent = new Intent(this, CacheDetailActivity.class);
final cgCache cache = getCacheFromAdapter(adapterInfo);
cachesIntent.putExtra("geocode", cache.getGeocode().toUpperCase());
cachesIntent.putExtra("name", cache.getName());
startActivity(cachesIntent);
return true;
} else if (id == MENU_DROP_CACHE) {
cgBase.dropCache(getCacheFromAdapter(adapterInfo), new Handler() {
@Override
public void handleMessage(Message msg) {
refreshCurrentList();
}
});
return true;
} else if (id == MENU_MOVE_TO_LIST) {
final String geocode = getCacheFromAdapter(adapterInfo).getGeocode();
new StoredList.UserInterface(this).promptForListSelection(R.string.cache_menu_move_list, new RunnableWithArgument<Integer>() {
@Override
public void run(Integer newListId) {
app.moveToList(geocode, newListId);
adapter.resetChecks();
refreshCurrentList();
}
});
return true;
} else if (id == MENU_STORE_CACHE) {
final cgCache cache = getCacheFromAdapter(adapterInfo);
//FIXME: this must use the same handler like in the CacheDetailActivity. Will be done by moving the handler into the store method.
cache.store(this, null);
return true;
}
// we must remember the menu info for the sub menu, there is a bug
// in Android:
// https://code.google.com/p/android/issues/detail?id=7139
lastMenuInfo = info;
if (adapterInfo != null) {
// create a search for a single cache (as if in details view)
final cgCache cache = getCacheFromAdapter(adapterInfo);
int logType = id - MENU_LOG_VISIT_OFFLINE;
cache.logOffline(this, LogType.getById(logType));
}
return true;
}
/**
* Extract a cache from adapter data.
*
* @param adapterInfo
* an adapterInfo
* @return the pointed cache
*/
private cgCache getCacheFromAdapter(final AdapterContextMenuInfo adapterInfo) {
final cgCache cache = adapter.getItem(adapterInfo.position);
if (cache.getGeocode().equalsIgnoreCase(contextMenuGeocode)) {
return cache;
}
return adapter.findCacheByGeocode(contextMenuGeocode);
}
private boolean setFilter(IFilter filter) {
if (adapter != null) {
adapter.setFilter(filter);
prepareFilterBar();
invalidateOptionsMenuCompatible();
return true;
}
return false;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (adapter != null) {
if (adapter.resetChecks()) {
return true;
} else if (adapter.getSelectMode()) {
adapter.setSelectMode(false, true);
return true;
}
}
}
return super.onKeyDown(keyCode, event);
}
private void setAdapter() {
if (listFooter == null) {
if (inflater == null) {
inflater = getLayoutInflater();
}
listFooter = inflater.inflate(R.layout.caches_footer, null);
listFooter.setClickable(true);
listFooter.setOnClickListener(new MoreCachesListener());
}
if (listFooterText == null) {
listFooterText = (TextView) listFooter.findViewById(R.id.more_caches);
}
if (adapter == null) {
final ListView list = getListView();
registerForContextMenu(list);
list.setLongClickable(true);
list.addFooterView(listFooter);
adapter = new CacheListAdapter(this, cacheList, type);
setListAdapter(adapter);
} else {
adapter.notifyDataSetChanged();
}
adapter.reFilter();
if (geo != null) {
adapter.setActualCoordinates(geo.coordsNow);
}
if (dir != null) {
adapter.setActualHeading(dir.directionNow);
}
}
private void setLoadingCaches() {
if (listFooter == null) {
return;
}
if (listFooterText == null) {
return;
}
listFooterText.setText(res.getString(R.string.caches_more_caches_loading));
listFooter.setClickable(false);
listFooter.setOnClickListener(null);
}
private void setMoreCaches() {
if (listFooter == null) {
return;
}
if (listFooterText == null) {
return;
}
boolean enableMore = type != CacheListType.OFFLINE && cacheList != null && cacheList.size() < MAX_LIST_ITEMS;
if (enableMore && search != null) {
final int count = search.getTotal();
enableMore = enableMore && count > 0 && cacheList.size() < count;
}
if (enableMore) {
listFooterText.setText(res.getString(R.string.caches_more_caches) + " (" + res.getString(R.string.caches_more_caches_currently) + ": " + cacheList.size() + ")");
listFooter.setOnClickListener(new MoreCachesListener());
} else {
if (CollectionUtils.isEmpty(cacheList)) {
listFooterText.setText(res.getString(R.string.caches_no_cache));
} else {
listFooterText.setText(res.getString(R.string.caches_more_caches_no));
}
listFooter.setOnClickListener(null);
}
listFooter.setClickable(enableMore);
}
private void init() {
startGeoAndDir();
if (CollectionUtils.isNotEmpty(cacheList)) {
setMoreCaches();
}
setTitle(title);
setAdapter();
if (geo != null) {
geoUpdate.updateLocation(geo);
}
if (dir != null) {
dirUpdate.updateDirection(dir);
}
}
// sensor & geolocation manager
private void startGeoAndDir() {
if (geo == null) {
geo = app.startGeo(geoUpdate);
}
if (Settings.isLiveList() && Settings.isUseCompass() && dir == null) {
dir = app.startDir(this, dirUpdate);
}
}
private void removeGeoAndDir() {
if (dir != null) {
dir = app.removeDir();
}
if (geo != null) {
geo = app.removeGeo();
}
}
private void importGpx() {
cgeogpxes.startSubActivity(this, listId);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
refreshCurrentList();
}
public void refreshStored() {
if (adapter != null && adapter.getChecked() > 0) {
// there are some checked caches
detailTotal = adapter.getChecked();
} else {
// no checked caches, download everything (when already stored - refresh them)
detailTotal = cacheList.size();
}
detailProgress = 0;
showProgress(false);
int etaTime = ((detailTotal * 25) / 60);
String message;
if (etaTime < 1) {
message = res.getString(R.string.caches_downloading) + " " + res.getString(R.string.caches_eta_ltm);
} else if (etaTime == 1) {
message = res.getString(R.string.caches_downloading) + " " + etaTime + " " + res.getString(R.string.caches_eta_min);
} else {
message = res.getString(R.string.caches_downloading) + " " + etaTime + " " + res.getString(R.string.caches_eta_mins);
}
progress.show(this, null, message, ProgressDialog.STYLE_HORIZONTAL, loadDetailsHandler.obtainMessage(MSG_CANCEL));
progress.setMaxProgressAndReset(detailTotal);
detailProgressTime = System.currentTimeMillis();
threadDetails = new LoadDetailsThread(loadDetailsHandler, listId);
threadDetails.start();
}
public void removeFromHistoryCheck() {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setCancelable(true);
dialog.setTitle(res.getString(R.string.caches_removing_from_history));
dialog.setMessage((adapter != null && adapter.getChecked() > 0) ? res.getString(R.string.cache_remove_from_history)
: res.getString(R.string.cache_clear_history));
dialog.setPositiveButton(getString(android.R.string.yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
removeFromHistory();
dialog.cancel();
}
});
dialog.setNegativeButton(getString(android.R.string.no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = dialog.create();
alert.show();
}
public void removeFromHistory() {
if (adapter != null && adapter.getChecked() > 0)
{
// there are some checked caches
detailTotal = adapter.getChecked();
}
else
{
// no checked caches, remove all
detailTotal = cacheList.size();
}
detailProgress = 0;
showProgress(false);
progress.show(this, null, res.getString(R.string.caches_removing_from_history), ProgressDialog.STYLE_HORIZONTAL, removeFromHistoryHandler.obtainMessage(MSG_CANCEL));
progress.setMaxProgressAndReset(detailTotal);
threadH = new RemoveFromHistoryThread(removeFromHistoryHandler);
threadH.start();
}
public void exportCaches() {
List<cgCache> caches;
if (adapter != null && adapter.getChecked() > 0) {
// there are some caches checked
caches = new LinkedList<cgCache>();
for (cgCache cache : cacheList) {
if (cache.isStatusChecked()) {
caches.add(cache);
}
}
} else {
// no caches checked, export all
caches = cacheList;
}
ExportFactory.showExportMenu(caches, this);
}
public void importWeb() {
detailProgress = 0;
showProgress(false);
progress.show(this, null, res.getString(R.string.web_import_waiting), true, downloadFromWebHandler.obtainMessage(MSG_CANCEL));
threadWeb = new LoadFromWebThread(downloadFromWebHandler, listId);
threadWeb.start();
}
public void dropStored(final boolean removeListAfterwards) {
AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setCancelable(true);
dialog.setTitle(res.getString(R.string.caches_drop_stored));
if (adapter != null && adapter.getChecked() > 0) {
dialog.setMessage(res.getString(R.string.caches_drop_selected_ask));
} else {
dialog.setMessage(res.getString(R.string.caches_drop_all_ask));
}
dialog.setPositiveButton(getString(android.R.string.yes), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dropSelected();
if (removeListAfterwards) {
removeList(false);
}
dialog.cancel();
}
});
dialog.setNegativeButton(getString(android.R.string.no), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = dialog.create();
alert.show();
}
public void dropSelected() {
progress.show(this, null, res.getString(R.string.caches_drop_progress), true, dropDetailsHandler.obtainMessage(MSG_CANCEL));
threadR = new DropDetailsThread(dropDetailsHandler);
threadR.start();
}
private class UpdateLocation implements UpdateLocationCallback {
@Override
public void updateLocation(cgGeo geo) {
if (geo == null) {
return;
}
if (adapter == null) {
return;
}
try {
if (cacheList != null && geo.coordsNow != null) {
adapter.setActualCoordinates(geo.coordsNow);
}
if (!Settings.isUseCompass() || geo.speedNow > 5) { // use GPS when speed is higher than 18 km/h
if (!Settings.isUseCompass()) {
adapter.setActualHeading(geo.bearingNow);
}
if (northHeading != null) {
adapter.setActualHeading(northHeading);
}
}
} catch (Exception e) {
Log.w("Failed to UpdateLocation location.");
}
}
}
private class UpdateDirection implements UpdateDirectionCallback {
@Override
public void updateDirection(cgDirection dir) {
if (!Settings.isLiveList()) {
return;
}
if (dir == null || dir.directionNow == null) {
return;
}
northHeading = dir.directionNow;
if (northHeading != null && adapter != null && (geo == null || geo.speedNow <= 5)) { // use compass when speed is lower than 18 km/h) {
adapter.setActualHeading(northHeading);
}
}
}
private class LoadByOfflineThread extends Thread {
final private Handler handler;
final private Geopoint coords;
final private int listId;
public LoadByOfflineThread(final Handler handlerIn, final Geopoint coordsIn, int listIdIn) {
handler = handlerIn;
coords = coordsIn;
listId = listIdIn;
}
@Override
public void run() {
search = cgBase.searchByStored(coords, Settings.getCacheType(), listId);
handler.sendMessage(Message.obtain());
}
}
private class LoadByHistoryThread extends Thread {
final private Handler handler;
public LoadByHistoryThread(Handler handlerIn) {
handler = handlerIn;
}
@Override
public void run() {
search = cgeoapplication.getInstance().getHistoryOfCaches(true, coords != null ? Settings.getCacheType() : CacheType.ALL);
handler.sendMessage(Message.obtain());
}
}
private class LoadNextPageThread extends cgSearchThread {
private final Handler handler;
public LoadNextPageThread(Handler handlerIn) {
handler = handlerIn;
}
@Override
public void run() {
search = cgBase.searchByNextPage(this, search, Settings.isShowCaptcha());
handler.sendMessage(Message.obtain());
}
}
private class LoadByCoordsThread extends cgSearchThread {
final private Handler handler;
final private Geopoint coords;
public LoadByCoordsThread(final Handler handler, final Geopoint coords) {
setPriority(Thread.MIN_PRIORITY);
this.handler = handler;
this.coords = coords;
if (coords == null) {
showToast(res.getString(R.string.warn_no_coordinates));
finish();
return;
}
}
@Override
public void run() {
search = cgBase.searchByCoords(this, coords, cacheType, Settings.isShowCaptcha());
handler.sendMessage(Message.obtain());
}
}
private class LoadByKeywordThread extends cgSearchThread {
final private Handler handler;
final private String keyword;
public LoadByKeywordThread(final Handler handler, final String keyword) {
setPriority(Thread.MIN_PRIORITY);
this.handler = handler;
this.keyword = keyword;
if (keyword == null) {
showToast(res.getString(R.string.warn_no_keyword));
finish();
return;
}
}
@Override
public void run() {
search = cgBase.searchByKeyword(this, keyword, cacheType, Settings.isShowCaptcha());
handler.sendMessage(Message.obtain());
}
}
private class LoadByUserNameThread extends cgSearchThread {
final private Handler handler;
final private String username;
public LoadByUserNameThread(final Handler handler, final String username) {
setPriority(Thread.MIN_PRIORITY);
this.handler = handler;
this.username = username;
if (StringUtils.isBlank(username)) {
showToast(res.getString(R.string.warn_no_username));
finish();
return;
}
}
@Override
public void run() {
search = cgBase.searchByUsername(this, username, cacheType, Settings.isShowCaptcha());
handler.sendMessage(Message.obtain());
}
}
private class LoadByOwnerThread extends cgSearchThread {
final private Handler handler;
final private String username;
public LoadByOwnerThread(final Handler handler, final String username) {
setPriority(Thread.MIN_PRIORITY);
this.handler = handler;
this.username = username;
if (StringUtils.isBlank(username)) {
showToast(res.getString(R.string.warn_no_username));
finish();
return;
}
}
@Override
public void run() {
Map<String, String> params = new HashMap<String, String>();
params.put("username", username);
if (cacheType != null) {
params.put("cacheType", cacheType.id);
}
search = cgBase.searchByOwner(this, username, cacheType, Settings.isShowCaptcha());
handler.sendMessage(Message.obtain());
}
}
private class LoadDetailsThread extends Thread {
final private Handler handler;
final private int listIdLD;
private volatile boolean needToStop = false;
private int checked = 0;
private long last = 0L;
public LoadDetailsThread(Handler handlerIn, int listId) {
setPriority(Thread.MIN_PRIORITY);
handler = handlerIn;
// in case of online lists, set the list id to the standard list
this.listIdLD = Math.max(listId, StoredList.STANDARD_LIST_ID);
if (adapter != null) {
checked = adapter.getChecked();
}
}
public void kill() {
needToStop = true;
}
@Override
public void run() {
removeGeoAndDir();
final List<cgCache> cacheListTemp = new ArrayList<cgCache>(cacheList);
for (cgCache cache : cacheListTemp) {
if (checked > 0 && !cache.isStatusChecked()) {
handler.sendEmptyMessage(0);
yield();
continue;
}
try {
if (needToStop) {
Log.i("Stopped storing process.");
break;
}
if ((System.currentTimeMillis() - last) < 1500) {
try {
int delay = 1000 + ((Double) (Math.random() * 1000)).intValue() - (int) (System.currentTimeMillis() - last);
if (delay < 0) {
delay = 500;
}
Log.i("Waiting for next cache " + delay + " ms");
sleep(delay);
} catch (Exception e) {
Log.e("cgeocaches.LoadDetailsThread.sleep: " + e.toString());
}
}
if (needToStop) {
Log.i("Stopped storing process.");
break;
}
detailProgress++;
cgBase.refreshCache(cgeocaches.this, cache.getGeocode(), listIdLD, null);
handler.sendEmptyMessage(cacheList.indexOf(cache));
yield();
} catch (Exception e) {
Log.e("cgeocaches.LoadDetailsThread: " + e.toString());
}
last = System.currentTimeMillis();
}
cacheListTemp.clear();
handler.sendEmptyMessage(MSG_DONE);
}
}
private class LoadFromWebThread extends Thread {
final private Handler handler;
final private int listIdLFW;
private volatile boolean needToStop = false;
public LoadFromWebThread(Handler handlerIn, int listId) {
setPriority(Thread.MIN_PRIORITY);
handler = handlerIn;
listIdLFW = listId;
}
public void kill() {
needToStop = true;
}
@Override
public void run() {
int ret = MSG_DONE;
removeGeoAndDir();
int delay = -1;
int times = 0;
while (!needToStop && times < 3 * 60 / 5) // maximum: 3 minutes, every 5 seconds
{
//download new code
String deviceCode = Settings.getWebDeviceCode();
if (deviceCode == null) {
deviceCode = "";
}
final Parameters params = new Parameters("code", deviceCode);
HttpResponse responseFromWeb = Network.request("http://send2.cgeo.org/read.html", params);
if (responseFromWeb != null && responseFromWeb.getStatusLine().getStatusCode() == 200) {
final String response = Network.getResponseData(responseFromWeb);
if (response.length() > 2) {
String GCcode = response;
delay = 1;
handler.sendMessage(handler.obtainMessage(1, GCcode));
yield();
cgBase.storeCache(cgeocaches.this, null, GCcode, listIdLFW, false, null);
handler.sendMessage(handler.obtainMessage(2, GCcode));
yield();
} else if ("RG".equals(response)) {
//Server returned RG (registration) and this device no longer registered.
Settings.setWebNameCode(null, null);
ret = -3;
needToStop = true;
break;
} else {
delay = 0;
handler.sendEmptyMessage(0);
yield();
}
}
if (responseFromWeb == null || responseFromWeb.getStatusLine().getStatusCode() != 200) {
ret = -2;
needToStop = true;
break;
}
try {
yield();
if (delay == 0)
{
sleep(5000); //No caches 5s
times++;
} else {
sleep(500); //Cache was loaded 0.5s
times = 0;
}
} catch (InterruptedException e) {
Log.e("cgeocaches.LoadFromWebThread.sleep: " + e.toString());
}
}
handler.sendEmptyMessage(ret);
}
}
private class DropDetailsThread extends Thread {
final private Handler handler;
private volatile boolean needToStop = false;
private int checked = 0;
public DropDetailsThread(Handler handlerIn) {
setPriority(Thread.MIN_PRIORITY);
handler = handlerIn;
if (adapter != null) {
checked = adapter.getChecked();
}
}
public void kill() {
needToStop = true;
}
@Override
public void run() {
removeGeoAndDir();
final List<cgCache> cacheListTemp = new ArrayList<cgCache>(cacheList);
for (cgCache cache : cacheListTemp) {
if (checked > 0 && !cache.isStatusChecked()) {
continue;
}
try {
if (needToStop) {
Log.i("Stopped dropping process.");
break;
}
app.markDropped(cache.getGeocode());
} catch (Exception e) {
Log.e("cgeocaches.DropDetailsThread: " + e.toString());
}
}
cacheListTemp.clear();
handler.sendEmptyMessage(MSG_DONE);
}
}
private class RemoveFromHistoryThread extends Thread {
final private Handler handler;
private volatile boolean needToStop = false;
private int checked = 0;
public RemoveFromHistoryThread(Handler handlerIn) {
setPriority(Thread.MIN_PRIORITY);
handler = handlerIn;
if (adapter != null) {
checked = adapter.getChecked();
}
}
public void kill() {
needToStop = true;
}
@Override
public void run() {
for (cgCache cache : cacheList) {
if (checked > 0 && !cache.isStatusChecked()) {
handler.sendEmptyMessage(0);
yield();
continue;
}
try {
if (needToStop) {
Log.i("Stopped removing process.");
break;
}
app.clearVisitDate(cache.getGeocode());
detailProgress++;
handler.sendEmptyMessage(cacheList.indexOf(cache));
yield();
} catch (Exception e) {
Log.e("cgeocaches.RemoveFromHistoryThread: " + e.toString());
}
}
handler.sendEmptyMessage(MSG_DONE);
}
}
private class MoreCachesListener implements View.OnClickListener {
@Override
public void onClick(View arg0) {
showProgress(true);
setLoadingCaches();
listFooter.setOnClickListener(null);
LoadNextPageThread thread;
thread = new LoadNextPageThread(loadNextPageHandler);
thread.setRecaptchaHandler(new cgSearchHandler(cgeocaches.this, res, thread));
thread.start();
}
}
private void hideLoading() {
final ListView list = getListView();
final RelativeLayout loading = (RelativeLayout) findViewById(R.id.loading);
if (list.getVisibility() == View.GONE) {
list.setVisibility(View.VISIBLE);
loading.setVisibility(View.GONE);
}
}
/**
* @param view
* unused here but needed since this method is referenced from XML layout
*/
public void selectList(View view) {
if (type != CacheListType.OFFLINE) {
return;
}
new StoredList.UserInterface(this).promptForListSelection(R.string.list_title, new RunnableWithArgument<Integer>() {
@Override
public void run(final Integer selectedListId) {
switchListById(selectedListId.intValue());
}
});
}
public void switchListById(int id) {
if (id < 0) {
return;
}
StoredList list = app.getList(id);
if (list == null) {
return;
}
listId = list.id;
title = list.title;
Settings.saveLastList(listId);
showProgress(true);
setLoadingCaches();
(new MoveCachesToListThread(listId, new MoveHandler())).start();
invalidateOptionsMenuCompatible();
}
private class MoveHandler extends Handler {
@Override
public void handleMessage(Message msg) {
Thread threadPure = new LoadByOfflineThread(loadCachesHandler, coords, msg.what);
threadPure.start();
}
}
private class MoveCachesToListThread extends Thread {
final private int listId;
final private Handler handler;
public MoveCachesToListThread(int listIdIn, Handler handlerIn) {
listId = listIdIn;
handler = handlerIn;
}
@Override
public void run() {
int checked = adapter.getChecked();
if (checked > 0) {
final List<cgCache> cacheListTemp = new ArrayList<cgCache>(cacheList);
for (cgCache cache : cacheListTemp) {
if (cache.isStatusChecked()) {
app.moveToList(cache.getGeocode(), listId);
}
}
}
handler.sendEmptyMessage(listId);
}
}
private void renameList() {
new StoredList.UserInterface(this).promptForListRename(listId, new Runnable() {
@Override
public void run() {
refreshCurrentList();
}
});
}
private void removeListInternal() {
boolean status = app.removeList(listId);
if (status) {
showToast(res.getString(R.string.list_dialog_remove_ok));
switchListById(StoredList.STANDARD_LIST_ID);
} else {
showToast(res.getString(R.string.list_dialog_remove_err));
}
}
private void removeList(final boolean askForConfirmation) {
// if there are no caches on this list, don't bother the user with questions.
// there is no harm in deleting the list, he could recreate it easily
if (CollectionUtils.isEmpty(cacheList)) {
removeListInternal();
return;
}
if (!askForConfirmation) {
removeListInternal();
return;
}
// ask him, if there are caches on the list
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle(R.string.list_dialog_remove_title);
alert.setMessage(R.string.list_dialog_remove_description);
alert.setPositiveButton(R.string.list_dialog_remove, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
removeListInternal();
}
});
alert.setNegativeButton(res.getString(R.string.list_dialog_cancel), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
}
});
alert.show();
}
/**
* @param view
* unused here but needed since this method is referenced from XML layout
*/
public void goMap(View view) {
if (search == null || CollectionUtils.isEmpty(cacheList)) {
showToast(res.getString(R.string.warn_no_cache_coord));
return;
}
SearchResult searchToUse = search;
// apply filter settings (if there's a filter)
if (adapter != null) {
Set<String> geocodes = new HashSet<String>();
for (cgCache cache : adapter.getFilteredList()) {
geocodes.add(cache.getGeocode());
}
searchToUse = new SearchResult(geocodes);
}
int count = searchToUse.getCount();
String mapTitle = title;
if (count > 0) {
mapTitle = title + " [" + count + "]";
}
CGeoMap.startActivitySearch(this, searchToUse, mapTitle);
}
@Override
public void goManual(View view) {
switch (type) {
case OFFLINE:
ActivityMixin.goManual(this, "c:geo-stored");
break;
case HISTORY:
ActivityMixin.goManual(this, "c:geo-history");
break;
default:
ActivityMixin.goManual(this, "c:geo-nearby");
break;
}
}
private void refreshCurrentList() {
switchListById(listId);
}
public static void startActivityOffline(final Context context) {
final Intent cachesIntent = new Intent(context, cgeocaches.class);
cachesIntent.putExtra(EXTRAS_LIST_TYPE, CacheListType.OFFLINE);
context.startActivity(cachesIntent);
}
public static void startActivityCachesAround(final AbstractActivity context, final Geopoint coords) {
cgeocaches cachesActivity = new cgeocaches();
Intent cachesIntent = new Intent(context, cachesActivity.getClass());
cachesIntent.putExtra(EXTRAS_LIST_TYPE, CacheListType.COORDINATE);
cachesIntent.putExtra(EXTRAS_COORDS, coords);
context.startActivity(cachesIntent);
}
public static void startActivityOwner(final AbstractActivity context, final String userName) {
final Intent cachesIntent = new Intent(context, cgeocaches.class);
cachesIntent.putExtra(EXTRAS_LIST_TYPE, CacheListType.OWNER);
cachesIntent.putExtra("username", userName);
context.startActivity(cachesIntent);
}
public static void startActivityUserName(final AbstractActivity context, final String userName) {
final Intent cachesIntent = new Intent(context, cgeocaches.class);
cachesIntent.putExtra(EXTRAS_LIST_TYPE, CacheListType.USERNAME);
cachesIntent.putExtra("username", userName);
context.startActivity(cachesIntent);
}
private void prepareFilterBar() {
if (Settings.getCacheType() != CacheType.ALL || adapter.isFilter()) {
String filter = "";
String cacheType = Settings.getCacheType().getL10n();
if (adapter.isFilter()) {
filter = ", " + adapter.getFilterName();
}
((TextView) findViewById(R.id.filter_text)).setText(cacheType + filter);
findViewById(R.id.filter_bar).setVisibility(View.VISIBLE);
}
else {
findViewById(R.id.filter_bar).setVisibility(View.GONE);
}
}
/**
* set date comparator for pure event lists
*/
private void setDateComparatorForEventList() {
if (CollectionUtils.isNotEmpty(cacheList)) {
boolean eventsOnly = true;
for (cgCache cache : cacheList) {
if (!cache.isEventCache()) {
eventsOnly = false;
break;
}
}
if (eventsOnly) {
adapter.setComparator(new EventDateComparator());
}
else if (type == CacheListType.HISTORY) {
adapter.setComparator(new VisitComparator());
}
else if (adapter.getCacheComparator() != null && adapter.getCacheComparator() instanceof EventDateComparator) {
adapter.setComparator(null);
}
}
}
public static void startActivityNearest(final Context context, final Geopoint coordsNow) {
final Intent cachesIntent = new Intent(context, cgeocaches.class);
cachesIntent.putExtra(EXTRAS_LIST_TYPE, CacheListType.NEAREST);
cachesIntent.putExtra(EXTRAS_COORDS, coordsNow);
context.startActivity(cachesIntent);
}
public static void startActivityHistory(Context context) {
final Intent cachesIntent = new Intent(context, cgeocaches.class);
cachesIntent.putExtra(EXTRAS_LIST_TYPE, CacheListType.HISTORY);
context.startActivity(cachesIntent);
}
public static void startActivityAddress(final Context context, final Geopoint coords, final String address) {
Intent addressIntent = new Intent(context, cgeocaches.class);
addressIntent.putExtra(EXTRAS_LIST_TYPE, CacheListType.ADDRESS);
addressIntent.putExtra(EXTRAS_COORDS, coords);
addressIntent.putExtra("address", address);
context.startActivity(addressIntent);
}
public static void startActivityCoordinates(final Context context, final Geopoint coords) {
final Intent cachesIntent = new Intent(context, cgeocaches.class);
cachesIntent.putExtra(EXTRAS_LIST_TYPE, CacheListType.COORDINATE);
cachesIntent.putExtra(EXTRAS_COORDS, coords);
context.startActivity(cachesIntent);
}
public static void startActivityKeyword(final Context context, final String keyword) {
final Intent cachesIntent = new Intent(context, cgeocaches.class);
cachesIntent.putExtra(EXTRAS_LIST_TYPE, CacheListType.KEYWORD);
cachesIntent.putExtra("keyword", keyword);
context.startActivity(cachesIntent);
}
public static void startActivityMap(final Context context, final SearchResult search) {
final Intent cachesIntent = new Intent(context, cgeocaches.class);
cachesIntent.putExtra(EXTRAS_LIST_TYPE, CacheListType.MAP);
cachesIntent.putExtra("search", search);
context.startActivity(cachesIntent);
}
}
| true | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// init
app.setAction(action);
setTheme();
setContentView(R.layout.caches);
setTitle("caches");
// get parameters
final Bundle extras = getIntent().getExtras();
if (extras != null) {
Object typeObject = extras.get(EXTRAS_LIST_TYPE);
type = (typeObject instanceof CacheListType) ? (CacheListType) typeObject : CacheListType.OFFLINE;
coords = (Geopoint) extras.getParcelable(EXTRAS_COORDS);
cacheType = Settings.getCacheType();
keyword = extras.getString("keyword");
address = extras.getString("address");
username = extras.getString("username");
}
if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
type = CacheListType.OFFLINE;
if (coords == null) {
coords = new Geopoint(0.0, 0.0);
}
}
init();
Thread threadPure;
cgSearchThread thread;
switch (type) {
case OFFLINE:
listId = Settings.getLastList();
if (listId <= StoredList.TEMPORARY_LIST_ID) {
listId = StoredList.STANDARD_LIST_ID;
title = res.getString(R.string.stored_caches_button);
} else {
final StoredList list = app.getList(listId);
// list.id may be different if listId was not valid
listId = list.id;
title = list.title;
}
setTitle(title);
showProgress(true);
setLoadingCaches();
threadPure = new LoadByOfflineThread(loadCachesHandler, coords, listId);
threadPure.start();
break;
case HISTORY:
title = res.getString(R.string.caches_history);
setTitle(title);
showProgress(true);
setLoadingCaches();
threadPure = new LoadByHistoryThread(loadCachesHandler);
threadPure.start();
break;
case NEAREST:
action = "pending";
title = res.getString(R.string.caches_nearby);
setTitle(title);
showProgress(true);
setLoadingCaches();
thread = new LoadByCoordsThread(loadCachesHandler, coords);
thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread));
thread.start();
break;
case COORDINATE:
action = "planning";
title = coords.toString();
setTitle(title);
showProgress(true);
setLoadingCaches();
thread = new LoadByCoordsThread(loadCachesHandler, coords);
thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread));
thread.start();
break;
case KEYWORD:
title = keyword;
setTitle(title);
showProgress(true);
setLoadingCaches();
thread = new LoadByKeywordThread(loadCachesHandler, keyword);
thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread));
thread.start();
break;
case ADDRESS:
action = "planning";
if (StringUtils.isNotBlank(address)) {
title = address;
setTitle(title);
showProgress(true);
setLoadingCaches();
} else {
title = coords.toString();
setTitle(title);
showProgress(true);
setLoadingCaches();
}
thread = new LoadByCoordsThread(loadCachesHandler, coords);
thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread));
thread.start();
break;
case USERNAME:
title = username;
setTitle(title);
showProgress(true);
setLoadingCaches();
thread = new LoadByUserNameThread(loadCachesHandler, username);
thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread));
thread.start();
break;
case OWNER:
title = username;
setTitle(title);
showProgress(true);
setLoadingCaches();
thread = new LoadByOwnerThread(loadCachesHandler, username);
thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread));
thread.start();
break;
case MAP:
title = res.getString(R.string.map_map);
setTitle(title);
showProgress(true);
SearchResult result = extras != null ? (SearchResult) extras.get("search") : null;
search = new SearchResult(result);
loadCachesHandler.sendMessage(Message.obtain());
break;
default:
title = "caches";
setTitle(title);
Log.e("cgeocaches.onCreate: No action or unknown action specified");
break;
}
prepareFilterBar();
if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
importGpxAttachement();
}
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// init
app.setAction(action);
setTheme();
setContentView(R.layout.caches);
setTitle("caches");
// get parameters
final Bundle extras = getIntent().getExtras();
if (extras != null) {
Object typeObject = extras.get(EXTRAS_LIST_TYPE);
type = (typeObject instanceof CacheListType) ? (CacheListType) typeObject : CacheListType.OFFLINE;
coords = (Geopoint) extras.getParcelable(EXTRAS_COORDS);
// FIXME: this code seems dubious, as adding a fake Geopoint with valid
// coordinates should not be required.
if (coords == null) {
coords = new Geopoint(0.0, 0.0);
}
cacheType = Settings.getCacheType();
keyword = extras.getString("keyword");
address = extras.getString("address");
username = extras.getString("username");
}
if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
type = CacheListType.OFFLINE;
if (coords == null) {
coords = new Geopoint(0.0, 0.0);
}
}
init();
Thread threadPure;
cgSearchThread thread;
switch (type) {
case OFFLINE:
listId = Settings.getLastList();
if (listId <= StoredList.TEMPORARY_LIST_ID) {
listId = StoredList.STANDARD_LIST_ID;
title = res.getString(R.string.stored_caches_button);
} else {
final StoredList list = app.getList(listId);
// list.id may be different if listId was not valid
listId = list.id;
title = list.title;
}
setTitle(title);
showProgress(true);
setLoadingCaches();
threadPure = new LoadByOfflineThread(loadCachesHandler, coords, listId);
threadPure.start();
break;
case HISTORY:
title = res.getString(R.string.caches_history);
setTitle(title);
showProgress(true);
setLoadingCaches();
threadPure = new LoadByHistoryThread(loadCachesHandler);
threadPure.start();
break;
case NEAREST:
action = "pending";
title = res.getString(R.string.caches_nearby);
setTitle(title);
showProgress(true);
setLoadingCaches();
thread = new LoadByCoordsThread(loadCachesHandler, coords);
thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread));
thread.start();
break;
case COORDINATE:
action = "planning";
title = coords.toString();
setTitle(title);
showProgress(true);
setLoadingCaches();
thread = new LoadByCoordsThread(loadCachesHandler, coords);
thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread));
thread.start();
break;
case KEYWORD:
title = keyword;
setTitle(title);
showProgress(true);
setLoadingCaches();
thread = new LoadByKeywordThread(loadCachesHandler, keyword);
thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread));
thread.start();
break;
case ADDRESS:
action = "planning";
if (StringUtils.isNotBlank(address)) {
title = address;
setTitle(title);
showProgress(true);
setLoadingCaches();
} else {
title = coords.toString();
setTitle(title);
showProgress(true);
setLoadingCaches();
}
thread = new LoadByCoordsThread(loadCachesHandler, coords);
thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread));
thread.start();
break;
case USERNAME:
title = username;
setTitle(title);
showProgress(true);
setLoadingCaches();
thread = new LoadByUserNameThread(loadCachesHandler, username);
thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread));
thread.start();
break;
case OWNER:
title = username;
setTitle(title);
showProgress(true);
setLoadingCaches();
thread = new LoadByOwnerThread(loadCachesHandler, username);
thread.setRecaptchaHandler(new cgSearchHandler(this, res, thread));
thread.start();
break;
case MAP:
title = res.getString(R.string.map_map);
setTitle(title);
showProgress(true);
SearchResult result = extras != null ? (SearchResult) extras.get("search") : null;
search = new SearchResult(result);
loadCachesHandler.sendMessage(Message.obtain());
break;
default:
title = "caches";
setTitle(title);
Log.e("cgeocaches.onCreate: No action or unknown action specified");
break;
}
prepareFilterBar();
if (Intent.ACTION_VIEW.equals(getIntent().getAction())) {
importGpxAttachement();
}
}
|
diff --git a/src/graindcafe/tribu/Executors/CmdTribu.java b/src/graindcafe/tribu/Executors/CmdTribu.java
index 2c9850f..1a2ade0 100644
--- a/src/graindcafe/tribu/Executors/CmdTribu.java
+++ b/src/graindcafe/tribu/Executors/CmdTribu.java
@@ -1,482 +1,482 @@
/*******************************************************************************
* Copyright or � or Copr. Quentin Godron (2011)
*
* [email protected]
*
* This software is a computer program whose purpose is to create zombie
* survival games on Bukkit's server.
*
* This software is governed by the CeCILL-C license under French law and
* abiding by the rules of distribution of free software. You can use,
* modify and/ or redistribute the software under the terms of the CeCILL-C
* license as circulated by CEA, CNRS and INRIA at the following URL
* "http://www.cecill.info".
*
* As a counterpart to the access to the source code and rights to copy,
* modify and redistribute granted by the license, users are provided only
* with a limited warranty and the software's author, the holder of the
* economic rights, and the successive licensors have only limited
* liability.
*
* In this respect, the user's attention is drawn to the risks associated
* with loading, using, modifying and/or developing or reproducing the
* software by the user in light of its specific status of free software,
* that may mean that it is complicated to manipulate, and that also
* therefore means that it is reserved for developers and experienced
* professionals having in-depth computer knowledge. Users are therefore
* encouraged to load and test the software's suitability as regards their
* requirements in conditions enabling the security of their systems and/or
* data to be ensured and, more generally, to use and operate it in the
* same conditions as regards security.
*
* The fact that you are presently reading this means that you have had
* knowledge of the CeCILL-C license and that you accept its terms.
******************************************************************************/
package graindcafe.tribu.Executors;
import graindcafe.tribu.Package;
import graindcafe.tribu.PlayerStats;
import graindcafe.tribu.Tribu;
import graindcafe.tribu.Signs.TribuSign;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Set;
import org.bukkit.ChatColor;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class CmdTribu implements CommandExecutor {
// use to confirm deletion of a level
private String deletedLevel = "";
private Package pck = null;
private Tribu plugin;
public CmdTribu(Tribu instance) {
plugin = instance;
}
// usage: /tribu ((create | load | delete) <name>) | enter | leave | package
// (create |delete | list)
// list | start [<name>] | stop | save | stats
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length == 0) {
return usage(sender);
}
args[0] = args[0].toLowerCase();
/*
* Players commands
*/
if (args[0].equalsIgnoreCase("enter") || args[0].equalsIgnoreCase("join")) {
if (!plugin.config().PluginModeServerExclusive || sender.isOp())
{
if (!sender.hasPermission("tribu.use.enter"))
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
} else
if (!(sender instanceof Player))
{
plugin.LogWarning(plugin.getLocale("Warning.ThisCommandCannotBeUsedFromTheConsole"));
} else
{
if(!plugin.isPlaying((Player) sender))
{
plugin.addPlayer((Player) sender);
} else
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.AlreadyIn"));
}
}
}
return true;
} else if (args[0].equals("leave"))
{
if (!plugin.config().PluginModeServerExclusive || sender.isOp())
{
if (!sender.hasPermission("tribu.use.leave"))
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
} else
if (!(sender instanceof Player))
{
plugin.LogWarning(plugin.getLocale("Warning.ThisCommandCannotBeUsedFromTheConsole"));
} else
{
plugin.removePlayer((Player) sender);
}
}
//add in them to change to main world (world when they leave the game);
return true;
} else if (args[0].equals("stats")) {
if (!sender.hasPermission("tribu.use.stats"))
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
else {
LinkedList<PlayerStats> stats = plugin.getSortedStats();
Tribu.messagePlayer(sender, plugin.getLocale("Message.Stats"));
Iterator<PlayerStats> i = stats.iterator();
String s;
PlayerStats cur;
while (i.hasNext()) {
s = "";
for (byte j = 0; i.hasNext() && j < 3; j++) {
cur = i.next();
s += ", " + cur.getPlayer().getDisplayName() + " (" + String.valueOf(cur.getPoints()) + ")";
}
Tribu.messagePlayer(sender, s.substring(2));
}
}
return true;
} else if (args[0].equals("vote")) {
if (!sender.hasPermission("tribu.use.vote"))
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
else {
if (!(sender instanceof Player)) {
plugin.LogWarning(plugin.getLocale("Warning.ThisCommandCannotBeUsedFromTheConsole"));
return true;
}
if (args.length == 2) {
try {
plugin.getLevelSelector().castVote((Player) sender, Integer.parseInt(args[1]));
} catch (NumberFormatException e) {
Tribu.messagePlayer(sender,plugin.getLocale("Message.InvalidVote"));
}
return true;
}
}
} else if (args[0].equals("vote1")) {
if(!sender.hasPermission("tribu.use.vote"))
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
else
{
if (!(sender instanceof Player)) {
plugin.LogWarning(plugin.getLocale("Warning.ThisCommandCannotBeUsedFromTheConsole"));
return true;
}
plugin.getLevelSelector().castVote((Player) sender, 1);
}
return true;
} else if (args[0].equals("vote2")) {
if(!sender.hasPermission("tribu.use.vote"))
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
else
{
if (!(sender instanceof Player)) {
plugin.LogWarning(plugin.getLocale("Warning.ThisCommandCannotBeUsedFromTheConsole"));
return true;
}
plugin.getLevelSelector().castVote((Player) sender, 2);
}
return true;
}
/*
* Ops commands
*/
/* Package management */
else if (args[0].equals("package") || args[0].equals("pck")) {
if(!sender.hasPermission("tribu.level.package"))
{
sender.sendMessage(plugin.getLocale("Message.Deny"));
return true;
}
else
if (args.length == 1) {
return usage(sender);
}
if (plugin.getLevel() == null) {
Tribu.messagePlayer(sender, plugin.getLocale("Message.NoLevelLoaded"));
Tribu.messagePlayer(sender, plugin.getLocale("Message.NoLevelLoaded2"));
return true;
}
args[1] = args[1].toLowerCase();
if (args[1].equals("new") || args[1].equals("create")) {
if (args.length == 2) {
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckNeedName"));
} else {
pck = new Package(args[2]);
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.PckCreated"), args[2]));
}
} else if (args[1].equals("open")) {
if (args.length == 2) {
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckNeedName"));
} else {
pck = plugin.getLevel().getPackage(args[2]);
if (pck != null)
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.PckOpened"), args[2]));
else
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.PckNotFound"), args[2]));
}
} else if (args[1].equals("close") || args[1].equals("save")) {
if (pck == null) {
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckNeedOpen"));
} else {
plugin.getLevel().addPackage(pck);
plugin.getLevel().setChanged();
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.PckSaved"), pck.getName()));
pck = null;
}
} else if (args[1].equals("add")) {
boolean success = false;
if (pck == null)
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckNeedOpen"));
else if (args.length == 2)
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckNeedId"));
else {
if (args.length == 3)
if (args[2].equalsIgnoreCase("this"))
if (!(sender instanceof Player)) {
plugin.LogWarning(plugin.getLocale("Warning.ThisCommandCannotBeUsedFromTheConsole"));
return true;
} else
success = pck.addItem(((Player) sender).getItemInHand().clone());
else
success = pck.addItem(args[2]);
else if (args.length == 4)
if (args[2].equalsIgnoreCase("this"))
if (!(sender instanceof Player)) {
plugin.LogWarning(plugin.getLocale("Warning.ThisCommandCannotBeUsedFromTheConsole"));
return true;
} else
success = pck.addItem(((Player) sender).getItemInHand().clone(), (short) TribuSign.parseInt(args[3]));
else
success = pck.addItem(args[2], (short) TribuSign.parseInt(args[3]));
else
success = pck.addItem(args[2], (short) TribuSign.parseInt(args[3]), (short) TribuSign.parseInt(args[4]));
if (success)
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.PckItemAdded"), pck.getLastItemName()));
else
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.PckItemAddFailed"), args[2]));
}
} else if (args[1].equals("del") || args[1].equals("delete")) {
if (pck == null)
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckNeedOpen"));
else if (args.length == 4) {
pck.deleteItem(TribuSign.parseInt(args[2]), (short) TribuSign.parseInt(args[3]));
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckItemDeleted"));
- } else if (pck.deleteItem(TribuSign.parseInt(args[2]), (short) TribuSign.parseInt(args[3])))
+ } else if (args.length==3 && pck.deleteItem(TribuSign.parseInt(args[2])))
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckItemDeleted"));
else
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckNeedSubId"));
} else if (args[1].equals("remove")) {
if (args.length == 3)
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckNeedName"));
else {
plugin.getLevel().removePackage(args[2]);
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckRemoved"));
pck=null;
}
} else if (args[1].equals("list")) {
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.PckList"), plugin.getLevel().listPackages()));
} else if (args[1].equals("show") || args[1].equals("describe")) {
if (plugin.getLevel() == null) {
Tribu.messagePlayer(sender, plugin.getLocale("Message.NoLevelLoaded"));
Tribu.messagePlayer(sender, plugin.getLocale("Message.NoLevelLoaded2"));
return true;
}
Package p = pck;
if (args.length > 2)
p = plugin.getLevel().getPackage(args[2]);
if (p != null)
Tribu.messagePlayer(sender, p.toString());
else
Tribu.messagePlayer(
sender,
String.format(plugin.getLocale("Message.PckNotFound"),
args.length > 2 ? args[2] : plugin.getLocale("Message.PckNoneOpened")));
} else {
return usage(sender);
}
return true;
}
/*
* Level management
*/
else if (args[0].equals("new") || args[0].equals("create")) {
if(!sender.hasPermission("tribu.level.create"))
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
return true;
}
if (args.length == 1) {
return usage(sender);
}
if (!(sender instanceof Player)) {
plugin.LogWarning(plugin.getLocale("Warning.ThisCommandCannotBeUsedFromTheConsole"));
return true;
}
Player player = (Player) sender;
if (!plugin.getLevelLoader().saveLevel(plugin.getLevel())) {
Tribu.messagePlayer(sender,plugin.getLocale("Message.UnableToSaveCurrentLevely"));
return true;
}
plugin.setLevel(plugin.getLevelLoader().newLevel(args[1], player.getLocation()));
player.sendMessage(String.format(plugin.getLocale("Message.LevelCreated"), args[1]));
return true;
} else if (args[0].equals("delete") || args[0].equals("remove")) {
if(!sender.hasPermission("tribu.level.delete"))
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
return true;
}
if (args.length == 1) {
return usage(sender);
} else if (!plugin.getLevelLoader().exists(args[1])) {
Tribu.messagePlayer(sender,String.format(plugin.getLocale("Message.UnknownLevel"), args[1]));
Tribu.messagePlayer(sender,plugin.getLocale("Message.MaybeNotSaved"));
return true;
} else if (!deletedLevel.equals(args[1])) {
deletedLevel = args[1];
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.ConfirmDeletion"), args[1]));
Tribu.messagePlayer(sender, plugin.getLocale("Message.ThisOperationIsNotCancellable"));
return true;
} else {
if (!plugin.getLevelLoader().deleteLevel(args[1])) {
Tribu.messagePlayer(sender, plugin.getLocale("Message.UnableToDeleteLevel"));
} else {
Tribu.messagePlayer(sender, plugin.getLocale("Message.LevelDeleted"));
}
return true;
}
} else if (args[0].equals("save") || args[0].equals("close")) {
if(!sender.hasPermission("tribu.level.save"))
{
sender.sendMessage(plugin.getLocale("Message.Deny"));
return true;
}
if (plugin.getLevel() != null)
plugin.getLevel().addPackage(pck);
if (!plugin.getLevelLoader().saveLevel(plugin.getLevel())) {
Tribu.messagePlayer(sender, plugin.getLocale("Message.UnableToSaveCurrentLevel"));
} else {
Tribu.messagePlayer(sender, plugin.getLocale("Message.LevelSaveSuccessful"));
}
return true;
} else if (args[0].equals("load") || args[0].equals("open")) {
if(!sender.hasPermission("tribu.level.load"))
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
return true;
}
if (args.length == 1) {
return usage(sender);
} else {
plugin.getLevelSelector().ChangeLevel(args[1], sender instanceof Player ? (Player) sender : null);
return true;
}
} else if (args[0].equals("unload")) {
if(!sender.hasPermission("tribu.level.unload"))
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
return true;
}
plugin.setLevel(null);
Tribu.messagePlayer(sender, plugin.getLocale("Message.LevelUnloaded"));
return true;
} else if (args[0].equals("list")) {
Set<String> levels = plugin.getLevelLoader().getLevelList();
String msg = "";
for (String level : levels) {
msg += ", " + level;
}
if (msg != "")
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.Levels"), msg.substring(2)));
return true;
}
/*
* Game management
*/
else if (args[0].equals("start")) {
if(!sender.hasPermission("tribu.game.start"))
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
return true;
}
// if a level is given, load it before start
if (args.length > 1 && plugin.getLevelLoader().exists(args[1])) {
plugin.getLevelSelector().ChangeLevel(args[1], sender instanceof Player ? (Player) sender : null);
} else if (plugin.getLevel() == null) {
Tribu.messagePlayer(sender, plugin.getLocale("Message.NoLevelLoaded"));
Tribu.messagePlayer(sender, plugin.getLocale("Message.NoLevelLoaded2"));
return true;
}
plugin.getLevelSelector().cancelVote();
if (plugin.startRunning())
Tribu.messagePlayer(sender, plugin.getLocale("Message.ZombieModeEnabled"));
else
Tribu.messagePlayer(sender, plugin.getLocale("Message.LevelNotReady"));
return true;
} else if (args[0].equals("stop")) {
if(!sender.hasPermission("tribu.game.stop"))
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
return true;
}
plugin.stopRunning();
Tribu.messagePlayer(sender, plugin.getLocale("Message.ZombieModeDisabled"));
return true;
} else if (args[0].equals("tpfz")) {
Location loc = plugin.getSpawner().getFirstZombieLocation();
if (loc != null)
if (sender instanceof Player)
((Player) sender).teleport(loc);
else if (args.length > 1)
plugin.getServer().getPlayer(args[1]).teleport(loc);
return true;
}else if (args[0].equals("reload")) {
if(sender.hasPermission("tribu.plugin.reload"))
{
plugin.reloadConf();
Tribu.messagePlayer(sender,plugin.getLocale("Message.ConfigFileReloaded"));
}
return true;
} else if (args[0].equals("help") || args[0].equals("?") || args[0].equals("aide")) {
if (sender.isOp()) {
Tribu.messagePlayer(sender,"There are 4 commands : /zspawn (setting zombie spawns) /ispawn (setting initial spawn) /dspawn (setting death spawn) /tribu.");
Tribu.messagePlayer(sender,"This is the /tribu command detail :");
}
return usage(sender);
}
return usage(sender);
}
private boolean usage(CommandSender sender) {
if (sender.isOp()) {
Tribu.messagePlayer(sender,ChatColor.LIGHT_PURPLE + "Ops commands :");
Tribu.messagePlayer(sender,ChatColor.YELLOW + "/tribu ((create | load | delete) <name>) | save | list | start [<name>] | stop");
Tribu.messagePlayer(sender,ChatColor.YELLOW + "/tribu package ((add | del) <id> [<subid>] [<number>]) | ((new | open | remove) <name> | close) | list");
Tribu.messagePlayer(sender,ChatColor.YELLOW + "See also /ispawn /dspawn /zspawn");
Tribu.messagePlayer(sender,ChatColor.YELLOW + "Players commands :");
}
return false;
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length == 0) {
return usage(sender);
}
args[0] = args[0].toLowerCase();
/*
* Players commands
*/
if (args[0].equalsIgnoreCase("enter") || args[0].equalsIgnoreCase("join")) {
if (!plugin.config().PluginModeServerExclusive || sender.isOp())
{
if (!sender.hasPermission("tribu.use.enter"))
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
} else
if (!(sender instanceof Player))
{
plugin.LogWarning(plugin.getLocale("Warning.ThisCommandCannotBeUsedFromTheConsole"));
} else
{
if(!plugin.isPlaying((Player) sender))
{
plugin.addPlayer((Player) sender);
} else
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.AlreadyIn"));
}
}
}
return true;
} else if (args[0].equals("leave"))
{
if (!plugin.config().PluginModeServerExclusive || sender.isOp())
{
if (!sender.hasPermission("tribu.use.leave"))
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
} else
if (!(sender instanceof Player))
{
plugin.LogWarning(plugin.getLocale("Warning.ThisCommandCannotBeUsedFromTheConsole"));
} else
{
plugin.removePlayer((Player) sender);
}
}
//add in them to change to main world (world when they leave the game);
return true;
} else if (args[0].equals("stats")) {
if (!sender.hasPermission("tribu.use.stats"))
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
else {
LinkedList<PlayerStats> stats = plugin.getSortedStats();
Tribu.messagePlayer(sender, plugin.getLocale("Message.Stats"));
Iterator<PlayerStats> i = stats.iterator();
String s;
PlayerStats cur;
while (i.hasNext()) {
s = "";
for (byte j = 0; i.hasNext() && j < 3; j++) {
cur = i.next();
s += ", " + cur.getPlayer().getDisplayName() + " (" + String.valueOf(cur.getPoints()) + ")";
}
Tribu.messagePlayer(sender, s.substring(2));
}
}
return true;
} else if (args[0].equals("vote")) {
if (!sender.hasPermission("tribu.use.vote"))
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
else {
if (!(sender instanceof Player)) {
plugin.LogWarning(plugin.getLocale("Warning.ThisCommandCannotBeUsedFromTheConsole"));
return true;
}
if (args.length == 2) {
try {
plugin.getLevelSelector().castVote((Player) sender, Integer.parseInt(args[1]));
} catch (NumberFormatException e) {
Tribu.messagePlayer(sender,plugin.getLocale("Message.InvalidVote"));
}
return true;
}
}
} else if (args[0].equals("vote1")) {
if(!sender.hasPermission("tribu.use.vote"))
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
else
{
if (!(sender instanceof Player)) {
plugin.LogWarning(plugin.getLocale("Warning.ThisCommandCannotBeUsedFromTheConsole"));
return true;
}
plugin.getLevelSelector().castVote((Player) sender, 1);
}
return true;
} else if (args[0].equals("vote2")) {
if(!sender.hasPermission("tribu.use.vote"))
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
else
{
if (!(sender instanceof Player)) {
plugin.LogWarning(plugin.getLocale("Warning.ThisCommandCannotBeUsedFromTheConsole"));
return true;
}
plugin.getLevelSelector().castVote((Player) sender, 2);
}
return true;
}
/*
* Ops commands
*/
/* Package management */
else if (args[0].equals("package") || args[0].equals("pck")) {
if(!sender.hasPermission("tribu.level.package"))
{
sender.sendMessage(plugin.getLocale("Message.Deny"));
return true;
}
else
if (args.length == 1) {
return usage(sender);
}
if (plugin.getLevel() == null) {
Tribu.messagePlayer(sender, plugin.getLocale("Message.NoLevelLoaded"));
Tribu.messagePlayer(sender, plugin.getLocale("Message.NoLevelLoaded2"));
return true;
}
args[1] = args[1].toLowerCase();
if (args[1].equals("new") || args[1].equals("create")) {
if (args.length == 2) {
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckNeedName"));
} else {
pck = new Package(args[2]);
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.PckCreated"), args[2]));
}
} else if (args[1].equals("open")) {
if (args.length == 2) {
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckNeedName"));
} else {
pck = plugin.getLevel().getPackage(args[2]);
if (pck != null)
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.PckOpened"), args[2]));
else
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.PckNotFound"), args[2]));
}
} else if (args[1].equals("close") || args[1].equals("save")) {
if (pck == null) {
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckNeedOpen"));
} else {
plugin.getLevel().addPackage(pck);
plugin.getLevel().setChanged();
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.PckSaved"), pck.getName()));
pck = null;
}
} else if (args[1].equals("add")) {
boolean success = false;
if (pck == null)
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckNeedOpen"));
else if (args.length == 2)
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckNeedId"));
else {
if (args.length == 3)
if (args[2].equalsIgnoreCase("this"))
if (!(sender instanceof Player)) {
plugin.LogWarning(plugin.getLocale("Warning.ThisCommandCannotBeUsedFromTheConsole"));
return true;
} else
success = pck.addItem(((Player) sender).getItemInHand().clone());
else
success = pck.addItem(args[2]);
else if (args.length == 4)
if (args[2].equalsIgnoreCase("this"))
if (!(sender instanceof Player)) {
plugin.LogWarning(plugin.getLocale("Warning.ThisCommandCannotBeUsedFromTheConsole"));
return true;
} else
success = pck.addItem(((Player) sender).getItemInHand().clone(), (short) TribuSign.parseInt(args[3]));
else
success = pck.addItem(args[2], (short) TribuSign.parseInt(args[3]));
else
success = pck.addItem(args[2], (short) TribuSign.parseInt(args[3]), (short) TribuSign.parseInt(args[4]));
if (success)
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.PckItemAdded"), pck.getLastItemName()));
else
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.PckItemAddFailed"), args[2]));
}
} else if (args[1].equals("del") || args[1].equals("delete")) {
if (pck == null)
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckNeedOpen"));
else if (args.length == 4) {
pck.deleteItem(TribuSign.parseInt(args[2]), (short) TribuSign.parseInt(args[3]));
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckItemDeleted"));
} else if (pck.deleteItem(TribuSign.parseInt(args[2]), (short) TribuSign.parseInt(args[3])))
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckItemDeleted"));
else
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckNeedSubId"));
} else if (args[1].equals("remove")) {
if (args.length == 3)
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckNeedName"));
else {
plugin.getLevel().removePackage(args[2]);
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckRemoved"));
pck=null;
}
} else if (args[1].equals("list")) {
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.PckList"), plugin.getLevel().listPackages()));
} else if (args[1].equals("show") || args[1].equals("describe")) {
if (plugin.getLevel() == null) {
Tribu.messagePlayer(sender, plugin.getLocale("Message.NoLevelLoaded"));
Tribu.messagePlayer(sender, plugin.getLocale("Message.NoLevelLoaded2"));
return true;
}
Package p = pck;
if (args.length > 2)
p = plugin.getLevel().getPackage(args[2]);
if (p != null)
Tribu.messagePlayer(sender, p.toString());
else
Tribu.messagePlayer(
sender,
String.format(plugin.getLocale("Message.PckNotFound"),
args.length > 2 ? args[2] : plugin.getLocale("Message.PckNoneOpened")));
} else {
return usage(sender);
}
return true;
}
/*
* Level management
*/
else if (args[0].equals("new") || args[0].equals("create")) {
if(!sender.hasPermission("tribu.level.create"))
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
return true;
}
if (args.length == 1) {
return usage(sender);
}
if (!(sender instanceof Player)) {
plugin.LogWarning(plugin.getLocale("Warning.ThisCommandCannotBeUsedFromTheConsole"));
return true;
}
Player player = (Player) sender;
if (!plugin.getLevelLoader().saveLevel(plugin.getLevel())) {
Tribu.messagePlayer(sender,plugin.getLocale("Message.UnableToSaveCurrentLevely"));
return true;
}
plugin.setLevel(plugin.getLevelLoader().newLevel(args[1], player.getLocation()));
player.sendMessage(String.format(plugin.getLocale("Message.LevelCreated"), args[1]));
return true;
} else if (args[0].equals("delete") || args[0].equals("remove")) {
if(!sender.hasPermission("tribu.level.delete"))
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
return true;
}
if (args.length == 1) {
return usage(sender);
} else if (!plugin.getLevelLoader().exists(args[1])) {
Tribu.messagePlayer(sender,String.format(plugin.getLocale("Message.UnknownLevel"), args[1]));
Tribu.messagePlayer(sender,plugin.getLocale("Message.MaybeNotSaved"));
return true;
} else if (!deletedLevel.equals(args[1])) {
deletedLevel = args[1];
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.ConfirmDeletion"), args[1]));
Tribu.messagePlayer(sender, plugin.getLocale("Message.ThisOperationIsNotCancellable"));
return true;
} else {
if (!plugin.getLevelLoader().deleteLevel(args[1])) {
Tribu.messagePlayer(sender, plugin.getLocale("Message.UnableToDeleteLevel"));
} else {
Tribu.messagePlayer(sender, plugin.getLocale("Message.LevelDeleted"));
}
return true;
}
} else if (args[0].equals("save") || args[0].equals("close")) {
if(!sender.hasPermission("tribu.level.save"))
{
sender.sendMessage(plugin.getLocale("Message.Deny"));
return true;
}
if (plugin.getLevel() != null)
plugin.getLevel().addPackage(pck);
if (!plugin.getLevelLoader().saveLevel(plugin.getLevel())) {
Tribu.messagePlayer(sender, plugin.getLocale("Message.UnableToSaveCurrentLevel"));
} else {
Tribu.messagePlayer(sender, plugin.getLocale("Message.LevelSaveSuccessful"));
}
return true;
} else if (args[0].equals("load") || args[0].equals("open")) {
if(!sender.hasPermission("tribu.level.load"))
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
return true;
}
if (args.length == 1) {
return usage(sender);
} else {
plugin.getLevelSelector().ChangeLevel(args[1], sender instanceof Player ? (Player) sender : null);
return true;
}
} else if (args[0].equals("unload")) {
if(!sender.hasPermission("tribu.level.unload"))
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
return true;
}
plugin.setLevel(null);
Tribu.messagePlayer(sender, plugin.getLocale("Message.LevelUnloaded"));
return true;
} else if (args[0].equals("list")) {
Set<String> levels = plugin.getLevelLoader().getLevelList();
String msg = "";
for (String level : levels) {
msg += ", " + level;
}
if (msg != "")
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.Levels"), msg.substring(2)));
return true;
}
/*
* Game management
*/
else if (args[0].equals("start")) {
if(!sender.hasPermission("tribu.game.start"))
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
return true;
}
// if a level is given, load it before start
if (args.length > 1 && plugin.getLevelLoader().exists(args[1])) {
plugin.getLevelSelector().ChangeLevel(args[1], sender instanceof Player ? (Player) sender : null);
} else if (plugin.getLevel() == null) {
Tribu.messagePlayer(sender, plugin.getLocale("Message.NoLevelLoaded"));
Tribu.messagePlayer(sender, plugin.getLocale("Message.NoLevelLoaded2"));
return true;
}
plugin.getLevelSelector().cancelVote();
if (plugin.startRunning())
Tribu.messagePlayer(sender, plugin.getLocale("Message.ZombieModeEnabled"));
else
Tribu.messagePlayer(sender, plugin.getLocale("Message.LevelNotReady"));
return true;
} else if (args[0].equals("stop")) {
if(!sender.hasPermission("tribu.game.stop"))
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
return true;
}
plugin.stopRunning();
Tribu.messagePlayer(sender, plugin.getLocale("Message.ZombieModeDisabled"));
return true;
} else if (args[0].equals("tpfz")) {
Location loc = plugin.getSpawner().getFirstZombieLocation();
if (loc != null)
if (sender instanceof Player)
((Player) sender).teleport(loc);
else if (args.length > 1)
plugin.getServer().getPlayer(args[1]).teleport(loc);
return true;
}else if (args[0].equals("reload")) {
if(sender.hasPermission("tribu.plugin.reload"))
{
plugin.reloadConf();
Tribu.messagePlayer(sender,plugin.getLocale("Message.ConfigFileReloaded"));
}
return true;
} else if (args[0].equals("help") || args[0].equals("?") || args[0].equals("aide")) {
if (sender.isOp()) {
Tribu.messagePlayer(sender,"There are 4 commands : /zspawn (setting zombie spawns) /ispawn (setting initial spawn) /dspawn (setting death spawn) /tribu.");
Tribu.messagePlayer(sender,"This is the /tribu command detail :");
}
return usage(sender);
}
return usage(sender);
}
| public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (args.length == 0) {
return usage(sender);
}
args[0] = args[0].toLowerCase();
/*
* Players commands
*/
if (args[0].equalsIgnoreCase("enter") || args[0].equalsIgnoreCase("join")) {
if (!plugin.config().PluginModeServerExclusive || sender.isOp())
{
if (!sender.hasPermission("tribu.use.enter"))
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
} else
if (!(sender instanceof Player))
{
plugin.LogWarning(plugin.getLocale("Warning.ThisCommandCannotBeUsedFromTheConsole"));
} else
{
if(!plugin.isPlaying((Player) sender))
{
plugin.addPlayer((Player) sender);
} else
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.AlreadyIn"));
}
}
}
return true;
} else if (args[0].equals("leave"))
{
if (!plugin.config().PluginModeServerExclusive || sender.isOp())
{
if (!sender.hasPermission("tribu.use.leave"))
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
} else
if (!(sender instanceof Player))
{
plugin.LogWarning(plugin.getLocale("Warning.ThisCommandCannotBeUsedFromTheConsole"));
} else
{
plugin.removePlayer((Player) sender);
}
}
//add in them to change to main world (world when they leave the game);
return true;
} else if (args[0].equals("stats")) {
if (!sender.hasPermission("tribu.use.stats"))
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
else {
LinkedList<PlayerStats> stats = plugin.getSortedStats();
Tribu.messagePlayer(sender, plugin.getLocale("Message.Stats"));
Iterator<PlayerStats> i = stats.iterator();
String s;
PlayerStats cur;
while (i.hasNext()) {
s = "";
for (byte j = 0; i.hasNext() && j < 3; j++) {
cur = i.next();
s += ", " + cur.getPlayer().getDisplayName() + " (" + String.valueOf(cur.getPoints()) + ")";
}
Tribu.messagePlayer(sender, s.substring(2));
}
}
return true;
} else if (args[0].equals("vote")) {
if (!sender.hasPermission("tribu.use.vote"))
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
else {
if (!(sender instanceof Player)) {
plugin.LogWarning(plugin.getLocale("Warning.ThisCommandCannotBeUsedFromTheConsole"));
return true;
}
if (args.length == 2) {
try {
plugin.getLevelSelector().castVote((Player) sender, Integer.parseInt(args[1]));
} catch (NumberFormatException e) {
Tribu.messagePlayer(sender,plugin.getLocale("Message.InvalidVote"));
}
return true;
}
}
} else if (args[0].equals("vote1")) {
if(!sender.hasPermission("tribu.use.vote"))
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
else
{
if (!(sender instanceof Player)) {
plugin.LogWarning(plugin.getLocale("Warning.ThisCommandCannotBeUsedFromTheConsole"));
return true;
}
plugin.getLevelSelector().castVote((Player) sender, 1);
}
return true;
} else if (args[0].equals("vote2")) {
if(!sender.hasPermission("tribu.use.vote"))
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
else
{
if (!(sender instanceof Player)) {
plugin.LogWarning(plugin.getLocale("Warning.ThisCommandCannotBeUsedFromTheConsole"));
return true;
}
plugin.getLevelSelector().castVote((Player) sender, 2);
}
return true;
}
/*
* Ops commands
*/
/* Package management */
else if (args[0].equals("package") || args[0].equals("pck")) {
if(!sender.hasPermission("tribu.level.package"))
{
sender.sendMessage(plugin.getLocale("Message.Deny"));
return true;
}
else
if (args.length == 1) {
return usage(sender);
}
if (plugin.getLevel() == null) {
Tribu.messagePlayer(sender, plugin.getLocale("Message.NoLevelLoaded"));
Tribu.messagePlayer(sender, plugin.getLocale("Message.NoLevelLoaded2"));
return true;
}
args[1] = args[1].toLowerCase();
if (args[1].equals("new") || args[1].equals("create")) {
if (args.length == 2) {
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckNeedName"));
} else {
pck = new Package(args[2]);
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.PckCreated"), args[2]));
}
} else if (args[1].equals("open")) {
if (args.length == 2) {
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckNeedName"));
} else {
pck = plugin.getLevel().getPackage(args[2]);
if (pck != null)
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.PckOpened"), args[2]));
else
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.PckNotFound"), args[2]));
}
} else if (args[1].equals("close") || args[1].equals("save")) {
if (pck == null) {
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckNeedOpen"));
} else {
plugin.getLevel().addPackage(pck);
plugin.getLevel().setChanged();
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.PckSaved"), pck.getName()));
pck = null;
}
} else if (args[1].equals("add")) {
boolean success = false;
if (pck == null)
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckNeedOpen"));
else if (args.length == 2)
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckNeedId"));
else {
if (args.length == 3)
if (args[2].equalsIgnoreCase("this"))
if (!(sender instanceof Player)) {
plugin.LogWarning(plugin.getLocale("Warning.ThisCommandCannotBeUsedFromTheConsole"));
return true;
} else
success = pck.addItem(((Player) sender).getItemInHand().clone());
else
success = pck.addItem(args[2]);
else if (args.length == 4)
if (args[2].equalsIgnoreCase("this"))
if (!(sender instanceof Player)) {
plugin.LogWarning(plugin.getLocale("Warning.ThisCommandCannotBeUsedFromTheConsole"));
return true;
} else
success = pck.addItem(((Player) sender).getItemInHand().clone(), (short) TribuSign.parseInt(args[3]));
else
success = pck.addItem(args[2], (short) TribuSign.parseInt(args[3]));
else
success = pck.addItem(args[2], (short) TribuSign.parseInt(args[3]), (short) TribuSign.parseInt(args[4]));
if (success)
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.PckItemAdded"), pck.getLastItemName()));
else
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.PckItemAddFailed"), args[2]));
}
} else if (args[1].equals("del") || args[1].equals("delete")) {
if (pck == null)
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckNeedOpen"));
else if (args.length == 4) {
pck.deleteItem(TribuSign.parseInt(args[2]), (short) TribuSign.parseInt(args[3]));
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckItemDeleted"));
} else if (args.length==3 && pck.deleteItem(TribuSign.parseInt(args[2])))
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckItemDeleted"));
else
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckNeedSubId"));
} else if (args[1].equals("remove")) {
if (args.length == 3)
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckNeedName"));
else {
plugin.getLevel().removePackage(args[2]);
Tribu.messagePlayer(sender, plugin.getLocale("Message.PckRemoved"));
pck=null;
}
} else if (args[1].equals("list")) {
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.PckList"), plugin.getLevel().listPackages()));
} else if (args[1].equals("show") || args[1].equals("describe")) {
if (plugin.getLevel() == null) {
Tribu.messagePlayer(sender, plugin.getLocale("Message.NoLevelLoaded"));
Tribu.messagePlayer(sender, plugin.getLocale("Message.NoLevelLoaded2"));
return true;
}
Package p = pck;
if (args.length > 2)
p = plugin.getLevel().getPackage(args[2]);
if (p != null)
Tribu.messagePlayer(sender, p.toString());
else
Tribu.messagePlayer(
sender,
String.format(plugin.getLocale("Message.PckNotFound"),
args.length > 2 ? args[2] : plugin.getLocale("Message.PckNoneOpened")));
} else {
return usage(sender);
}
return true;
}
/*
* Level management
*/
else if (args[0].equals("new") || args[0].equals("create")) {
if(!sender.hasPermission("tribu.level.create"))
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
return true;
}
if (args.length == 1) {
return usage(sender);
}
if (!(sender instanceof Player)) {
plugin.LogWarning(plugin.getLocale("Warning.ThisCommandCannotBeUsedFromTheConsole"));
return true;
}
Player player = (Player) sender;
if (!plugin.getLevelLoader().saveLevel(plugin.getLevel())) {
Tribu.messagePlayer(sender,plugin.getLocale("Message.UnableToSaveCurrentLevely"));
return true;
}
plugin.setLevel(plugin.getLevelLoader().newLevel(args[1], player.getLocation()));
player.sendMessage(String.format(plugin.getLocale("Message.LevelCreated"), args[1]));
return true;
} else if (args[0].equals("delete") || args[0].equals("remove")) {
if(!sender.hasPermission("tribu.level.delete"))
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
return true;
}
if (args.length == 1) {
return usage(sender);
} else if (!plugin.getLevelLoader().exists(args[1])) {
Tribu.messagePlayer(sender,String.format(plugin.getLocale("Message.UnknownLevel"), args[1]));
Tribu.messagePlayer(sender,plugin.getLocale("Message.MaybeNotSaved"));
return true;
} else if (!deletedLevel.equals(args[1])) {
deletedLevel = args[1];
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.ConfirmDeletion"), args[1]));
Tribu.messagePlayer(sender, plugin.getLocale("Message.ThisOperationIsNotCancellable"));
return true;
} else {
if (!plugin.getLevelLoader().deleteLevel(args[1])) {
Tribu.messagePlayer(sender, plugin.getLocale("Message.UnableToDeleteLevel"));
} else {
Tribu.messagePlayer(sender, plugin.getLocale("Message.LevelDeleted"));
}
return true;
}
} else if (args[0].equals("save") || args[0].equals("close")) {
if(!sender.hasPermission("tribu.level.save"))
{
sender.sendMessage(plugin.getLocale("Message.Deny"));
return true;
}
if (plugin.getLevel() != null)
plugin.getLevel().addPackage(pck);
if (!plugin.getLevelLoader().saveLevel(plugin.getLevel())) {
Tribu.messagePlayer(sender, plugin.getLocale("Message.UnableToSaveCurrentLevel"));
} else {
Tribu.messagePlayer(sender, plugin.getLocale("Message.LevelSaveSuccessful"));
}
return true;
} else if (args[0].equals("load") || args[0].equals("open")) {
if(!sender.hasPermission("tribu.level.load"))
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
return true;
}
if (args.length == 1) {
return usage(sender);
} else {
plugin.getLevelSelector().ChangeLevel(args[1], sender instanceof Player ? (Player) sender : null);
return true;
}
} else if (args[0].equals("unload")) {
if(!sender.hasPermission("tribu.level.unload"))
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
return true;
}
plugin.setLevel(null);
Tribu.messagePlayer(sender, plugin.getLocale("Message.LevelUnloaded"));
return true;
} else if (args[0].equals("list")) {
Set<String> levels = plugin.getLevelLoader().getLevelList();
String msg = "";
for (String level : levels) {
msg += ", " + level;
}
if (msg != "")
Tribu.messagePlayer(sender, String.format(plugin.getLocale("Message.Levels"), msg.substring(2)));
return true;
}
/*
* Game management
*/
else if (args[0].equals("start")) {
if(!sender.hasPermission("tribu.game.start"))
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
return true;
}
// if a level is given, load it before start
if (args.length > 1 && plugin.getLevelLoader().exists(args[1])) {
plugin.getLevelSelector().ChangeLevel(args[1], sender instanceof Player ? (Player) sender : null);
} else if (plugin.getLevel() == null) {
Tribu.messagePlayer(sender, plugin.getLocale("Message.NoLevelLoaded"));
Tribu.messagePlayer(sender, plugin.getLocale("Message.NoLevelLoaded2"));
return true;
}
plugin.getLevelSelector().cancelVote();
if (plugin.startRunning())
Tribu.messagePlayer(sender, plugin.getLocale("Message.ZombieModeEnabled"));
else
Tribu.messagePlayer(sender, plugin.getLocale("Message.LevelNotReady"));
return true;
} else if (args[0].equals("stop")) {
if(!sender.hasPermission("tribu.game.stop"))
{
Tribu.messagePlayer(sender,plugin.getLocale("Message.Deny"));
return true;
}
plugin.stopRunning();
Tribu.messagePlayer(sender, plugin.getLocale("Message.ZombieModeDisabled"));
return true;
} else if (args[0].equals("tpfz")) {
Location loc = plugin.getSpawner().getFirstZombieLocation();
if (loc != null)
if (sender instanceof Player)
((Player) sender).teleport(loc);
else if (args.length > 1)
plugin.getServer().getPlayer(args[1]).teleport(loc);
return true;
}else if (args[0].equals("reload")) {
if(sender.hasPermission("tribu.plugin.reload"))
{
plugin.reloadConf();
Tribu.messagePlayer(sender,plugin.getLocale("Message.ConfigFileReloaded"));
}
return true;
} else if (args[0].equals("help") || args[0].equals("?") || args[0].equals("aide")) {
if (sender.isOp()) {
Tribu.messagePlayer(sender,"There are 4 commands : /zspawn (setting zombie spawns) /ispawn (setting initial spawn) /dspawn (setting death spawn) /tribu.");
Tribu.messagePlayer(sender,"This is the /tribu command detail :");
}
return usage(sender);
}
return usage(sender);
}
|
diff --git a/modules/cpr/src/main/java/org/atmosphere/container/Jetty9AsyncSupportWithWebSocket.java b/modules/cpr/src/main/java/org/atmosphere/container/Jetty9AsyncSupportWithWebSocket.java
index 522bab5d3..ea65135d0 100644
--- a/modules/cpr/src/main/java/org/atmosphere/container/Jetty9AsyncSupportWithWebSocket.java
+++ b/modules/cpr/src/main/java/org/atmosphere/container/Jetty9AsyncSupportWithWebSocket.java
@@ -1,200 +1,200 @@
/*
* Copyright 2013 Jeanfrancois Arcand
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package org.atmosphere.container;
import org.atmosphere.cpr.Action;
import org.atmosphere.cpr.ApplicationConfig;
import org.atmosphere.cpr.AtmosphereConfig;
import org.atmosphere.cpr.AtmosphereRequest;
import org.atmosphere.cpr.AtmosphereResource;
import org.atmosphere.cpr.AtmosphereResponse;
import org.atmosphere.cpr.WebSocketProcessorFactory;
import org.atmosphere.util.Utils;
import org.atmosphere.websocket.WebSocket;
import org.atmosphere.websocket.WebSocketProcessor;
import org.eclipse.jetty.websocket.api.UpgradeRequest;
import org.eclipse.jetty.websocket.api.UpgradeResponse;
import org.eclipse.jetty.websocket.api.WebSocketBehavior;
import org.eclipse.jetty.websocket.api.WebSocketPolicy;
import org.eclipse.jetty.websocket.server.ServletWebSocketRequest;
import org.eclipse.jetty.websocket.server.WebSocketServerFactory;
import org.eclipse.jetty.websocket.servlet.ServletUpgradeRequest;
import org.eclipse.jetty.websocket.servlet.ServletUpgradeResponse;
import org.eclipse.jetty.websocket.servlet.WebSocketCreator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
/**
* Jetty 9 WebSocket support.
*
* @author Jeanfrancois Arcand
*/
public class Jetty9AsyncSupportWithWebSocket extends Servlet30CometSupport {
private static final Logger logger = LoggerFactory.getLogger(Jetty9AsyncSupportWithWebSocket.class);
private final WebSocketServerFactory webSocketFactory;
public Jetty9AsyncSupportWithWebSocket(final AtmosphereConfig config) {
super(config);
String bs = config.getInitParameter(ApplicationConfig.WEBSOCKET_BUFFER_SIZE);
WebSocketPolicy policy = new WebSocketPolicy(WebSocketBehavior.SERVER);
if (bs != null) {
policy.setInputBufferSize(Integer.parseInt(bs));
}
String max = config.getInitParameter(ApplicationConfig.WEBSOCKET_IDLETIME);
if (max != null) {
policy.setIdleTimeout(Integer.parseInt(max));
}
// Crazy Jetty API Incompatibility
String serverInfo = config.getServletConfig().getServletContext().getServerInfo();
boolean isJetty91 = false;
if (serverInfo != null && serverInfo.indexOf("9.1") != -1) {
isJetty91 = true;
}
max = config.getInitParameter(ApplicationConfig.WEBSOCKET_MAXTEXTSIZE);;
try {
if (max != null) {
//policy.setMaxMessageSize(Integer.parseInt(max));
Method m;
if (isJetty91) {
m = policy.getClass().getMethod("setMaxTextMessageSize", new Class[]{int.class});
} else {
- m = policy.getClass().getMethod("setMaxMessageSize", new Class[]{int.class});
+ m = policy.getClass().getMethod("setMaxMessageSize", new Class[]{long.class});
}
m.invoke(policy, Integer.parseInt(max));
}
max = config.getInitParameter(ApplicationConfig.WEBSOCKET_MAXBINARYSIZE);
if (max != null) {
//policy.setMaxMessageSize(Integer.parseInt(max));
Method m;
if (isJetty91) {
m = policy.getClass().getMethod("setMaxBinaryMessageSize", new Class[]{int.class});
} else {
- m = policy.getClass().getMethod("setMaxMessageSize", new Class[]{int.class});
+ m = policy.getClass().getMethod("setMaxMessageSize", new Class[]{long.class});
}
m.invoke(policy, Integer.parseInt(max));
}
} catch (Exception ex) {
logger.warn("", ex);
}
final WebSocketProcessor webSocketProcessor = WebSocketProcessorFactory.getDefault().getWebSocketProcessor(config.framework());
webSocketFactory = new WebSocketServerFactory(policy) {
@Override
public boolean acceptWebSocket(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
setCreator(new WebSocketCreator() {
// @Override 9.0.x
public Object createWebSocket(UpgradeRequest upgradeRequest, UpgradeResponse upgradeResponse) {
ServletWebSocketRequest r = ServletWebSocketRequest.class.cast(upgradeRequest);
r.getExtensions().clear();
if (!webSocketProcessor.handshake(request)) {
try {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "WebSocket requests rejected.");
} catch (IOException e) {
logger.trace("", e);
}
return null;
}
return new Jetty9WebSocketHandler(request, config.framework(), webSocketProcessor);
}
// @Override 9.1.x
public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) {
req.getExtensions().clear();
if (!webSocketProcessor.handshake(request)) {
try {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "WebSocket requests rejected.");
} catch (IOException e) {
logger.trace("", e);
}
return null;
}
return new Jetty9WebSocketHandler(request, config.framework(), webSocketProcessor);
}
});
return super.acceptWebSocket(request, response);
}
};
try {
webSocketFactory.start();
} catch (Exception e) {
logger.error("", e);
}
}
@Override
public Action service(AtmosphereRequest req, AtmosphereResponse res)
throws IOException, ServletException {
Action action = null;
Boolean b = (Boolean) req.getAttribute(WebSocket.WEBSOCKET_INITIATED);
if (b == null) b = Boolean.FALSE;
if (!Utils.webSocketEnabled(req) && req.getAttribute(WebSocket.WEBSOCKET_ACCEPT_DONE) == null) {
if (req.resource() != null && req.resource().transport() == AtmosphereResource.TRANSPORT.WEBSOCKET) {
WebSocket.notSupported(req, res);
return Action.CANCELLED;
} else {
return super.service(req, res);
}
} else {
if (webSocketFactory != null && !b) {
req.setAttribute(WebSocket.WEBSOCKET_INITIATED, true);
webSocketFactory.acceptWebSocket(req, res);
req.setAttribute(WebSocket.WEBSOCKET_ACCEPT_DONE, true);
return new Action();
}
action = suspended(req, res);
if (action.type() == Action.TYPE.SUSPEND) {
} else if (action.type() == Action.TYPE.RESUME) {
req.setAttribute(WebSocket.WEBSOCKET_RESUME, true);
}
}
return action == null ? super.service(req, res) : action;
}
/**
* Return the container's name.
*/
public String getContainerName() {
return config.getServletConfig().getServletContext().getServerInfo() + " with WebSocket enabled.";
}
@Override
public boolean supportWebSocket() {
return true;
}
}
| false | true | public Jetty9AsyncSupportWithWebSocket(final AtmosphereConfig config) {
super(config);
String bs = config.getInitParameter(ApplicationConfig.WEBSOCKET_BUFFER_SIZE);
WebSocketPolicy policy = new WebSocketPolicy(WebSocketBehavior.SERVER);
if (bs != null) {
policy.setInputBufferSize(Integer.parseInt(bs));
}
String max = config.getInitParameter(ApplicationConfig.WEBSOCKET_IDLETIME);
if (max != null) {
policy.setIdleTimeout(Integer.parseInt(max));
}
// Crazy Jetty API Incompatibility
String serverInfo = config.getServletConfig().getServletContext().getServerInfo();
boolean isJetty91 = false;
if (serverInfo != null && serverInfo.indexOf("9.1") != -1) {
isJetty91 = true;
}
max = config.getInitParameter(ApplicationConfig.WEBSOCKET_MAXTEXTSIZE);;
try {
if (max != null) {
//policy.setMaxMessageSize(Integer.parseInt(max));
Method m;
if (isJetty91) {
m = policy.getClass().getMethod("setMaxTextMessageSize", new Class[]{int.class});
} else {
m = policy.getClass().getMethod("setMaxMessageSize", new Class[]{int.class});
}
m.invoke(policy, Integer.parseInt(max));
}
max = config.getInitParameter(ApplicationConfig.WEBSOCKET_MAXBINARYSIZE);
if (max != null) {
//policy.setMaxMessageSize(Integer.parseInt(max));
Method m;
if (isJetty91) {
m = policy.getClass().getMethod("setMaxBinaryMessageSize", new Class[]{int.class});
} else {
m = policy.getClass().getMethod("setMaxMessageSize", new Class[]{int.class});
}
m.invoke(policy, Integer.parseInt(max));
}
} catch (Exception ex) {
logger.warn("", ex);
}
final WebSocketProcessor webSocketProcessor = WebSocketProcessorFactory.getDefault().getWebSocketProcessor(config.framework());
webSocketFactory = new WebSocketServerFactory(policy) {
@Override
public boolean acceptWebSocket(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
setCreator(new WebSocketCreator() {
// @Override 9.0.x
public Object createWebSocket(UpgradeRequest upgradeRequest, UpgradeResponse upgradeResponse) {
ServletWebSocketRequest r = ServletWebSocketRequest.class.cast(upgradeRequest);
r.getExtensions().clear();
if (!webSocketProcessor.handshake(request)) {
try {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "WebSocket requests rejected.");
} catch (IOException e) {
logger.trace("", e);
}
return null;
}
return new Jetty9WebSocketHandler(request, config.framework(), webSocketProcessor);
}
// @Override 9.1.x
public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) {
req.getExtensions().clear();
if (!webSocketProcessor.handshake(request)) {
try {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "WebSocket requests rejected.");
} catch (IOException e) {
logger.trace("", e);
}
return null;
}
return new Jetty9WebSocketHandler(request, config.framework(), webSocketProcessor);
}
});
return super.acceptWebSocket(request, response);
}
};
try {
webSocketFactory.start();
} catch (Exception e) {
logger.error("", e);
}
}
| public Jetty9AsyncSupportWithWebSocket(final AtmosphereConfig config) {
super(config);
String bs = config.getInitParameter(ApplicationConfig.WEBSOCKET_BUFFER_SIZE);
WebSocketPolicy policy = new WebSocketPolicy(WebSocketBehavior.SERVER);
if (bs != null) {
policy.setInputBufferSize(Integer.parseInt(bs));
}
String max = config.getInitParameter(ApplicationConfig.WEBSOCKET_IDLETIME);
if (max != null) {
policy.setIdleTimeout(Integer.parseInt(max));
}
// Crazy Jetty API Incompatibility
String serverInfo = config.getServletConfig().getServletContext().getServerInfo();
boolean isJetty91 = false;
if (serverInfo != null && serverInfo.indexOf("9.1") != -1) {
isJetty91 = true;
}
max = config.getInitParameter(ApplicationConfig.WEBSOCKET_MAXTEXTSIZE);;
try {
if (max != null) {
//policy.setMaxMessageSize(Integer.parseInt(max));
Method m;
if (isJetty91) {
m = policy.getClass().getMethod("setMaxTextMessageSize", new Class[]{int.class});
} else {
m = policy.getClass().getMethod("setMaxMessageSize", new Class[]{long.class});
}
m.invoke(policy, Integer.parseInt(max));
}
max = config.getInitParameter(ApplicationConfig.WEBSOCKET_MAXBINARYSIZE);
if (max != null) {
//policy.setMaxMessageSize(Integer.parseInt(max));
Method m;
if (isJetty91) {
m = policy.getClass().getMethod("setMaxBinaryMessageSize", new Class[]{int.class});
} else {
m = policy.getClass().getMethod("setMaxMessageSize", new Class[]{long.class});
}
m.invoke(policy, Integer.parseInt(max));
}
} catch (Exception ex) {
logger.warn("", ex);
}
final WebSocketProcessor webSocketProcessor = WebSocketProcessorFactory.getDefault().getWebSocketProcessor(config.framework());
webSocketFactory = new WebSocketServerFactory(policy) {
@Override
public boolean acceptWebSocket(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
setCreator(new WebSocketCreator() {
// @Override 9.0.x
public Object createWebSocket(UpgradeRequest upgradeRequest, UpgradeResponse upgradeResponse) {
ServletWebSocketRequest r = ServletWebSocketRequest.class.cast(upgradeRequest);
r.getExtensions().clear();
if (!webSocketProcessor.handshake(request)) {
try {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "WebSocket requests rejected.");
} catch (IOException e) {
logger.trace("", e);
}
return null;
}
return new Jetty9WebSocketHandler(request, config.framework(), webSocketProcessor);
}
// @Override 9.1.x
public Object createWebSocket(ServletUpgradeRequest req, ServletUpgradeResponse resp) {
req.getExtensions().clear();
if (!webSocketProcessor.handshake(request)) {
try {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "WebSocket requests rejected.");
} catch (IOException e) {
logger.trace("", e);
}
return null;
}
return new Jetty9WebSocketHandler(request, config.framework(), webSocketProcessor);
}
});
return super.acceptWebSocket(request, response);
}
};
try {
webSocketFactory.start();
} catch (Exception e) {
logger.error("", e);
}
}
|
diff --git a/src/main/groovy/servlet/TemplateServlet.java b/src/main/groovy/servlet/TemplateServlet.java
index a7a5d24b2..5666a0cd1 100644
--- a/src/main/groovy/servlet/TemplateServlet.java
+++ b/src/main/groovy/servlet/TemplateServlet.java
@@ -1,520 +1,522 @@
/*
* $Id$
*
* Copyright 2003 (C) James Strachan and Bob Mcwhirter. All Rights Reserved.
*
* Redistribution and use of this software and associated documentation
* ("Software"), with or without modification, are permitted provided that the
* following conditions are met:
*
* 1. Redistributions of source code must retain copyright statements and
* notices. Redistributions must also contain a copy of this document.
*
* 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 name "groovy" must not be used to endorse or promote products derived
* from this Software without prior written permission of The Codehaus. For
* written permission, please contact [email protected].
*
* 4. Products derived from this Software may not be called "groovy" nor may
* "groovy" appear in their names without prior written permission of The
* Codehaus. "groovy" is a registered trademark of The Codehaus.
*
* 5. Due credit should be given to The Codehaus - http://groovy.codehaus.org/
*
* THIS SOFTWARE IS PROVIDED BY THE CODEHAUS AND CONTRIBUTORS ``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 THE CODEHAUS 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 groovy.servlet;
import groovy.lang.MetaClass;
import groovy.text.SimpleTemplateEngine;
import groovy.text.Template;
import groovy.text.TemplateEngine;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.StringReader;
import java.io.Writer;
import java.util.Map;
import java.util.WeakHashMap;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* A generic servlet for serving (mostly HTML) templates.
*
* It wraps a <code>groovy.text.TemplateEngine</code> to process HTTP
* requests. By default, it uses the
* <code>groovy.text.SimpleTemplateEngine</code> which interprets JSP-like (or
* Canvas-like) templates. The init parameter <code>templateEngine</code>
* defines the fully qualified class name of the template to use.<br>
*
* <p>
* Headless <code>helloworld.html</code> example
* <pre><code>
* <html>
* <body>
* <% 3.times { %>
* Hello World!
* <% } %>
* <br>
* session.id = ${session.id}
* </body>
* </html>
* </code></pre>
* </p>
*
* @see TemplateServlet#setVariables(ServletBinding)
*
* @author Christian Stein
* @author Guillaume Laforge
* @version 2.0
*/
public class TemplateServlet extends AbstractHttpServlet {
/**
* Simple cache entry that validates against last modified and length
* attributes of the specified file.
*
* @author Sormuras
*/
private static class TemplateCacheEntry {
long lastModified;
long length;
Template template;
public TemplateCacheEntry(File file, Template template) {
if (file == null) {
throw new NullPointerException("file");
}
if (template == null) {
throw new NullPointerException("template");
}
this.lastModified = file.lastModified();
this.length = file.length();
this.template = template;
}
/**
* Checks the passed file attributes against those cached ones.
*
* @param file
* Other file handle to compare to the cached values.
* @return <code>true</code> if all measured values match, else <code>false</code>
*/
public boolean validate(File file) {
if (file == null) {
throw new NullPointerException("file");
}
if (file.lastModified() != this.lastModified) {
return false;
}
if (file.length() != this.length) {
return false;
}
return true;
}
}
/*
* Enables more log statements.
*/
private static final boolean VERBOSE = true;
/**
* Simple file name to template cache map.
*/
// Java5 private final Map<String, TemplateCacheEntry> cache;
private final Map cache;
/**
* Servlet (or the application) context.
*/
private ServletContext context;
/**
* Underlying template engine used to evaluate template source files.
*/
private TemplateEngine engine;
/**
* Flag that controls the appending of the "Generated by ..." comment.
*/
private boolean generatedBy;
/**
* Create new TemplateSerlvet.
*/
public TemplateServlet() {
// Java 5 this.cache = new WeakHashMap<String, TemplateCacheEntry>();
this.cache = new WeakHashMap();
this.context = null; // assigned later by init()
this.engine = null; // assigned later by init()
this.generatedBy = true; // may be changed by init()
}
/**
* Triggers the template creation eliminating all new line characters.
*
* Its a work around
*
* @see TemplateServlet#getTemplate(File)
* @see BufferedReader#readLine()
*/
private Template createTemplate(int bufferCapacity, FileReader fileReader)
throws Exception {
StringBuffer sb = new StringBuffer(bufferCapacity);
BufferedReader reader = new BufferedReader(fileReader);
try {
String line = reader.readLine();
while (line != null) {
sb.append(line);
//if (VERBOSE) { // prints the entire source file
// log(" | " + line);
//}
line = reader.readLine();
}
}
finally {
if (reader != null) {
reader.close();
}
}
StringReader stringReader = new StringReader(sb.toString());
Template template = engine.createTemplate(stringReader);
stringReader.close();
return template;
}
/**
* Gets the template created by the underlying engine parsing the request.
*
* <p>
* This method looks up a simple (weak) hash map for an existing template
* object that matches the source file. If the source file didn't change in
* length and its last modified stamp hasn't changed compared to a precompiled
* template object, this template is used. Otherwise, there is no or an
* invalid template object cache entry, a new one is created by the underlying
* template engine. This new instance is put to the cache for consecutive
* calls.
* </p>
*
* @return The template that will produce the response text.
* @param file
* The HttpServletRequest.
* @throws IOException
* If the request specified an invalid template source file
*/
protected Template getTemplate(File file) throws ServletException {
String key = file.getAbsolutePath();
Template template = null;
//
// Test cache for a valid template bound to the key.
//
TemplateCacheEntry entry = (TemplateCacheEntry) cache.get(key);
if (entry != null) {
if (entry.validate(file)) { // log("Valid cache hit! :)");
template = entry.template;
} // else log("Cached template needs recompiliation!");
} // else log("Cache miss.");
//
// Template not cached or the source file changed - compile new template!
//
if (template == null) {
if (VERBOSE) {
log("Creating new template from file " + file + "...");
}
FileReader reader = null;
try {
reader = new FileReader(file);
//
// FIXME Template creation should eliminate '\n' by default?!
//
// template = engine.createTemplate(reader);
//
// General error during parsing:
// expecting anything but ''\n''; got it anyway
//
template = createTemplate((int) file.length(), reader);
}
catch (Exception e) {
throw new ServletException("Creation of template failed: " + e, e);
}
finally {
if (reader != null) {
try {
reader.close();
}
catch (IOException ignore) {
// e.printStackTrace();
}
}
}
cache.put(key, new TemplateCacheEntry(file, template));
if (VERBOSE) {
log("Created and added template to cache. [key=" + key + "]");
}
}
//
// Last sanity check.
//
if (template == null) {
throw new ServletException("Template is null? Should not happen here!");
}
return template;
}
/**
* Initializes the servlet from hints the container passes.
* <p>
* Delegates to sub-init methods and parses the following parameters:
* <ul>
* <li> <tt>"generatedBy"</tt> : boolean, appends "Generated by ..." to the
* HTML response text generated by this servlet.
* </li>
* </ul>
* @param config
* Passed by the servlet container.
* @throws ServletException
* if this method encountered difficulties
*
* @see TemplateServlet#initTemplateEngine(ServletConfig)
*/
public void init(ServletConfig config) throws ServletException {
super.init(config);
this.context = config.getServletContext();
if (context == null) {
throw new ServletException("Context must not be null!");
}
this.engine = initTemplateEngine(config);
if (engine == null) {
throw new ServletException("Template engine not instantiated.");
}
// Use reflection, some containers don't load classes properly
MetaClass.setUseReflection(true);
String value = config.getInitParameter("generatedBy");
if (value != null) {
this.generatedBy = Boolean.valueOf(value).booleanValue();
}
if (VERBOSE) {
log(getClass().getName() + " initialized on " + engine.getClass());
}
}
/**
* Creates the template engine.
*
* Called by {@link TemplateServlet#init(ServletConfig)} and returns just
* <code>new groovy.text.SimpleTemplateEngine()</code> if the init parameter
* <code>templateEngine</code> is not set by the container configuration.
*
* @param config
* Current serlvet configuration passed by the container.
*
* @return The underlying template engine or <code>null</code> on error.
*
* @see TemplateServlet#initTemplateEngine(javax.servlet.ServletConfig)
*/
protected TemplateEngine initTemplateEngine(ServletConfig config) {
String name = config.getInitParameter("templateEngine");
if (name == null) {
return new SimpleTemplateEngine();
}
try {
return (TemplateEngine) Class.forName(name).newInstance();
}
catch (InstantiationException e) {
log("Could not instantiate template engine: " + name, e);
}
catch (IllegalAccessException e) {
log("Could not access template engine class: " + name, e);
}
catch (ClassNotFoundException e) {
log("Could not find template engine class: " + name, e);
}
return null;
}
/**
* Services the request with a response.
* <p>
* First the request is parsed for the source file uri. If the specified file
* could not be found or can not be read an error message is sent as response.
*
* </p>
* @param request
* The http request.
* @param response
* The http response.
* @throws IOException
* if an input or output error occurs while the servlet is
* handling the HTTP request
* @throws ServletException
* if the HTTP request cannot be handled
*/
public void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if (VERBOSE) {
log("Creating/getting cached template...");
}
//
// Get the template source file handle.
//
File file = super.getScriptUriAsFile(request, context);
if (!file.exists()) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return; // throw new IOException(file.getAbsolutePath());
}
if (!file.canRead()) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Can not read!");
return; // throw new IOException(file.getAbsolutePath());
}
//
// Get the requested template.
//
long getMillis = System.currentTimeMillis();
Template template = getTemplate(file);
getMillis = System.currentTimeMillis() - getMillis;
//
// Create new binding for the current request.
//
ServletBinding binding = new ServletBinding(request, response, context);
setVariables(binding);
//
// Prepare the response buffer content type _before_ getting the writer.
//
response.setContentType(CONTENT_TYPE_TEXT_HTML);
//
// Get the output stream writer from the binding.
//
Writer out = (Writer) binding.getVariable("out");
if (out == null) {
out = response.getWriter();
}
//
// Evaluate the template.
//
if (VERBOSE) {
log("Making template...");
}
// String made = template.make(binding.getVariables()).toString();
// log(" = " + made);
long makeMillis = System.currentTimeMillis();
template.make(binding.getVariables()).writeTo(out);
makeMillis = System.currentTimeMillis() - makeMillis;
if (generatedBy) {
+ /*
out.append("\n<!-- Generated by Groovy TemplateServlet [create/get=");
out.append(Long.toString(getMillis));
out.append(" ms, make=");
out.append(Long.toString(makeMillis));
out.append(" ms] -->\n");
+ */
}
//
// Set status code and flush the response buffer.
//
response.setStatus(HttpServletResponse.SC_OK);
response.flushBuffer();
if (VERBOSE) {
log("Template request responded. [create/get=" + getMillis
+ " ms, make=" + makeMillis + " ms]");
}
}
/**
* Override this method to set your variables to the Groovy binding.
* <p>
* All variables bound the binding are passed to the template source text,
* e.g. the HTML file, when the template is merged.
* </p>
* <p>
* The binding provided by TemplateServlet does already include some default
* variables. As of this writing, they are (copied from
* {@link groovy.servlet.ServletBinding}):
* <ul>
* <li><tt>"request"</tt> : HttpServletRequest </li>
* <li><tt>"response"</tt> : HttpServletResponse </li>
* <li><tt>"context"</tt> : ServletContext </li>
* <li><tt>"application"</tt> : ServletContext </li>
* <li><tt>"session"</tt> : request.getSession(true) </li>
* </ul>
* </p>
* <p>
* And via explicit hard-coded keywords:
* <ul>
* <li><tt>"out"</tt> : response.getWriter() </li>
* <li><tt>"sout"</tt> : response.getOutputStream() </li>
* <li><tt>"html"</tt> : new MarkupBuilder(response.getWriter()) </li>
* </ul>
* </p>
*
* <p>Example binding all servlet context variables:
* <pre><code>
* class Mytlet extends TemplateServlet {
*
* private ServletContext context;
*
* public void init(ServletConfig config) {
* this.context = config.getServletContext();
* }
*
* protected void setVariables(ServletBinding binding) {
* Enumeration enumeration = context.getAttributeNames();
* while (enumeration.hasMoreElements()) {
* String name = (String) enumeration.nextElement();
* binding.setVariable(name, context.getAttribute(name));
* }
* }
*
* }
* <code></pre>
* </p>
*
* @param binding
* to get modified
*
* @see TemplateServlet
*/
protected void setVariables(ServletBinding binding) {
// empty
}
}
| false | true | public void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if (VERBOSE) {
log("Creating/getting cached template...");
}
//
// Get the template source file handle.
//
File file = super.getScriptUriAsFile(request, context);
if (!file.exists()) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return; // throw new IOException(file.getAbsolutePath());
}
if (!file.canRead()) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Can not read!");
return; // throw new IOException(file.getAbsolutePath());
}
//
// Get the requested template.
//
long getMillis = System.currentTimeMillis();
Template template = getTemplate(file);
getMillis = System.currentTimeMillis() - getMillis;
//
// Create new binding for the current request.
//
ServletBinding binding = new ServletBinding(request, response, context);
setVariables(binding);
//
// Prepare the response buffer content type _before_ getting the writer.
//
response.setContentType(CONTENT_TYPE_TEXT_HTML);
//
// Get the output stream writer from the binding.
//
Writer out = (Writer) binding.getVariable("out");
if (out == null) {
out = response.getWriter();
}
//
// Evaluate the template.
//
if (VERBOSE) {
log("Making template...");
}
// String made = template.make(binding.getVariables()).toString();
// log(" = " + made);
long makeMillis = System.currentTimeMillis();
template.make(binding.getVariables()).writeTo(out);
makeMillis = System.currentTimeMillis() - makeMillis;
if (generatedBy) {
out.append("\n<!-- Generated by Groovy TemplateServlet [create/get=");
out.append(Long.toString(getMillis));
out.append(" ms, make=");
out.append(Long.toString(makeMillis));
out.append(" ms] -->\n");
}
//
// Set status code and flush the response buffer.
//
response.setStatus(HttpServletResponse.SC_OK);
response.flushBuffer();
if (VERBOSE) {
log("Template request responded. [create/get=" + getMillis
+ " ms, make=" + makeMillis + " ms]");
}
}
| public void service(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
if (VERBOSE) {
log("Creating/getting cached template...");
}
//
// Get the template source file handle.
//
File file = super.getScriptUriAsFile(request, context);
if (!file.exists()) {
response.sendError(HttpServletResponse.SC_NOT_FOUND);
return; // throw new IOException(file.getAbsolutePath());
}
if (!file.canRead()) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "Can not read!");
return; // throw new IOException(file.getAbsolutePath());
}
//
// Get the requested template.
//
long getMillis = System.currentTimeMillis();
Template template = getTemplate(file);
getMillis = System.currentTimeMillis() - getMillis;
//
// Create new binding for the current request.
//
ServletBinding binding = new ServletBinding(request, response, context);
setVariables(binding);
//
// Prepare the response buffer content type _before_ getting the writer.
//
response.setContentType(CONTENT_TYPE_TEXT_HTML);
//
// Get the output stream writer from the binding.
//
Writer out = (Writer) binding.getVariable("out");
if (out == null) {
out = response.getWriter();
}
//
// Evaluate the template.
//
if (VERBOSE) {
log("Making template...");
}
// String made = template.make(binding.getVariables()).toString();
// log(" = " + made);
long makeMillis = System.currentTimeMillis();
template.make(binding.getVariables()).writeTo(out);
makeMillis = System.currentTimeMillis() - makeMillis;
if (generatedBy) {
/*
out.append("\n<!-- Generated by Groovy TemplateServlet [create/get=");
out.append(Long.toString(getMillis));
out.append(" ms, make=");
out.append(Long.toString(makeMillis));
out.append(" ms] -->\n");
*/
}
//
// Set status code and flush the response buffer.
//
response.setStatus(HttpServletResponse.SC_OK);
response.flushBuffer();
if (VERBOSE) {
log("Template request responded. [create/get=" + getMillis
+ " ms, make=" + makeMillis + " ms]");
}
}
|
diff --git a/src/main/java/jline/console/ConsoleReader.java b/src/main/java/jline/console/ConsoleReader.java
index 42eb623..4067088 100644
--- a/src/main/java/jline/console/ConsoleReader.java
+++ b/src/main/java/jline/console/ConsoleReader.java
@@ -1,1651 +1,1653 @@
/*
* Copyright (c) 2002-2007, Marc Prud'hommeaux. All rights reserved.
*
* This software is distributable under the BSD license. See the terms of the
* BSD license in the documentation provided with this software.
*/
package jline.console;
import jline.Terminal;
import jline.TerminalFactory;
import jline.console.completer.CandidateListCompletionHandler;
import jline.console.completer.Completer;
import jline.console.completer.CompletionHandler;
import jline.console.history.History;
import jline.console.history.MemoryHistory;
import jline.internal.Log;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.event.ActionListener;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Reader;
import java.io.Writer;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
/**
* A reader for console applications. It supports custom tab-completion,
* saveable command history, and command line editing. On some platforms,
* platform-specific commands will need to be issued before the reader will
* function properly. See {@link jline.Terminal#init} for convenience
* methods for issuing platform-specific setup commands.
*
* @author <a href="mailto:[email protected]">Marc Prud'hommeaux</a>
* @author <a href="mailto:[email protected]">Jason Dillon</a>
*/
public class ConsoleReader
{
public static final String JLINE_NOBELL = "jline.nobell";
public static final char BACKSPACE = '\b';
public static final char RESET_LINE = '\r';
public static final char KEYBOARD_BELL = '\07';
public static final char NULL_MASK = 0;
public static final int TAB_WIDTH = 4;
private static final ResourceBundle
resources = ResourceBundle.getBundle(CandidateListCompletionHandler.class.getName());
private final Terminal terminal;
private InputStream in;
private final Writer out;
private final CursorBuffer buf = new CursorBuffer();
private String prompt;
private boolean bellEnabled = true;
private Character mask;
private Character echoCharacter;
public ConsoleReader(final InputStream in, final Writer out, final InputStream bindings, final Terminal term) throws
IOException
{
this.in = in;
this.out = out;
this.terminal = term != null ? term : TerminalFactory.get();
this.keyBindings = loadKeyBindings(bindings);
if (Boolean.getBoolean(JLINE_NOBELL)) {
setBellEnabled(false);
}
}
public ConsoleReader(final InputStream in, final Writer out, final Terminal term) throws IOException {
this(in, out, null, term);
}
public ConsoleReader(final InputStream in, final Writer out) throws IOException {
this(in, out, null, null);
}
/**
* Create a new reader using {@link FileDescriptor#in} for input and
* {@link System#out} for output.
* <p/>
* {@link FileDescriptor#in} is used because it has a better chance of not being buffered.
*/
public ConsoleReader() throws IOException {
this(new FileInputStream(FileDescriptor.in), new PrintWriter(new OutputStreamWriter(System.out)), null, null);
}
// FIXME: Only used for tests
void setInput(final InputStream in) {
this.in = in;
}
public InputStream getInput() {
return in;
}
public Writer getOutput() {
return out;
}
public Terminal getTerminal() {
return terminal;
}
public CursorBuffer getCursorBuffer() {
return buf;
}
public void setBellEnabled(final boolean enabled) {
this.bellEnabled = enabled;
}
public boolean isBellEnabled() {
return bellEnabled;
}
public void setPrompt(final String prompt) {
this.prompt = prompt;
}
public String getPrompt() {
return prompt;
}
/**
* Set the echo character. For example, to have "*" entered when a password is typed:
* <p/>
* <pre>
* myConsoleReader.setEchoCharacter(new Character('*'));
* </pre>
* <p/>
* Setting the character to
* <p/>
* <pre>
* null
* </pre>
* <p/>
* will restore normal character echoing. Setting the character to
* <p/>
* <pre>
* new Character(0)
* </pre>
* <p/>
* will cause nothing to be echoed.
*
* @param c the character to echo to the console in place of the typed character.
*/
public void setEchoCharacter(final Character c) {
this.echoCharacter = c;
}
/**
* Returns the echo character.
*/
public Character getEchoCharacter() {
return echoCharacter;
}
/**
* Erase the current line.
*
* @return false if we failed (e.g., the buffer was empty)
*/
final boolean resetLine() throws IOException {
if (buf.cursor == 0) {
return false;
}
backspaceAll();
return true;
}
int getCursorPosition() {
// FIXME: does not handle anything but a line with a prompt absolute position
String prompt = getPrompt();
return (prompt == null ? 0 : prompt.length()) + buf.cursor;
}
/**
* Move the cursor position to the specified absolute index.
*/
public final boolean setCursorPosition(final int position) throws IOException {
return moveCursor(position - buf.cursor) != 0;
}
/**
* Set the current buffer's content to the specified {@link String}. The
* visual console will be modified to show the current buffer.
*
* @param buffer the new contents of the buffer.
*/
private void setBuffer(final String buffer) throws IOException {
// don't bother modifying it if it is unchanged
if (buffer.equals(buf.buffer.toString())) {
return;
}
// obtain the difference between the current buffer and the new one
int sameIndex = 0;
for (int i = 0, l1 = buffer.length(), l2 = buf.buffer.length(); (i < l1)
&& (i < l2); i++) {
if (buffer.charAt(i) == buf.buffer.charAt(i)) {
sameIndex++;
}
else {
break;
}
}
int diff = buf.buffer.length() - sameIndex;
backspace(diff); // go back for the differences
killLine(); // clear to the end of the line
buf.buffer.setLength(sameIndex); // the new length
putString(buffer.substring(sameIndex)); // append the differences
}
private void setBuffer(final CharSequence buffer) throws IOException {
setBuffer(String.valueOf(buffer));
}
/**
* Output put the prompt + the current buffer
*/
public final void drawLine() throws IOException {
String prompt = getPrompt();
if (prompt != null) {
print(prompt);
}
print(buf.buffer.toString());
if (buf.length() != buf.cursor) { // not at end of line
back(buf.length() - buf.cursor - 1);
}
}
/**
* Clear the line and redraw it.
*/
public final void redrawLine() throws IOException {
print(RESET_LINE);
flush();
drawLine();
}
/**
* Clear the buffer and add its contents to the history.
*
* @return the former contents of the buffer.
*/
final String finishBuffer() { // FIXME: Package protected because used by tests
String str = buf.buffer.toString();
// we only add it to the history if the buffer is not empty
// and if mask is null, since having a mask typically means
// the string was a password. We clear the mask after this call
if (str.length() > 0) {
if (mask == null && isHistoryEnabled()) {
history.add(str);
}
else {
mask = null;
}
}
history.moveToEnd();
buf.buffer.setLength(0);
buf.cursor = 0;
return str;
}
/**
* Write out the specified string to the buffer and the output stream.
*/
public final void putString(final CharSequence str) throws IOException {
buf.write(str);
print(str);
drawBuffer();
}
/**
* Output the specified character, both to the buffer and the output stream.
*/
private void putChar(final int c, final boolean print) throws IOException {
buf.write((char) c);
if (print) {
if (mask == null) {
// no masking
print(c);
}
else if (mask == NULL_MASK) {
// Don't print anything
}
else {
print(mask);
}
drawBuffer();
}
}
/**
* Redraw the rest of the buffer from the cursor onwards. This is necessary
* for inserting text into the buffer.
*
* @param clear the number of characters to clear after the end of the buffer
*/
private void drawBuffer(final int clear) throws IOException {
// debug ("drawBuffer: " + clear);
if (buf.cursor == buf.length() && clear == 0) {
return;
}
char[] chars = buf.buffer.substring(buf.cursor).toCharArray();
if (mask != null) {
Arrays.fill(chars, mask);
}
print(chars);
clearAhead(clear);
if (terminal.isAnsiSupported()) {
if (chars.length > 0) {
// don't ask, it works
back(Math.max(chars.length - 1, 1));
}
} else {
back(chars.length);
}
flush();
}
/**
* Redraw the rest of the buffer from the cursor onwards. This is necessary
* for inserting text into the buffer.
*/
private void drawBuffer() throws IOException {
drawBuffer(0);
}
/**
* Clear ahead the specified number of characters without moving the cursor.
*/
private void clearAhead(final int num) throws IOException {
if (num == 0) {
return;
}
if (terminal.isAnsiSupported()) {
printAnsiSequence("J");
return;
}
// print blank extra characters
print(' ', num);
// we need to flush here so a "clever" console doesn't just ignore the redundancy
// of a space followed by a backspace.
flush();
// reset the visual cursor
back(num);
flush();
}
/**
* Move the visual cursor backwards without modifying the buffer cursor.
*/
private void back(final int num) throws IOException {
if (num == 0) return;
if (terminal.isAnsiSupported()) {
int width = getTerminal().getWidth();
int cursor = getCursorPosition();
// debug("back: " + cursor + " + " + num + " on " + width);
int currRow = (cursor + num) / width;
int newRow = cursor / width;
int newCol = cursor % width + 1;
// debug(" old row: " + currRow + " new row: " + newRow);
if (newRow < currRow) {
printAnsiSequence((currRow - newRow) + "A");
}
printAnsiSequence(newCol + "G");
return;
}
print(BACKSPACE, num);
flush();
}
/**
* Flush the console output stream. This is important for printout out single characters (like a backspace or
* keyboard) that we want the console to handle immediately.
*/
public void flush() throws IOException {
out.flush();
}
private int backspaceAll() throws IOException {
return backspace(Integer.MAX_VALUE);
}
/**
* Issue <em>num</em> backspaces.
*
* @return the number of characters backed up
*/
private int backspace(final int num) throws IOException {
if (buf.cursor == 0) {
return 0;
}
int count = 0;
int termwidth = getTerminal().getWidth();
int lines = getCursorPosition() / termwidth;
count = moveCursor(-1 * num) * -1;
buf.buffer.delete(buf.cursor, buf.cursor + count);
if (getCursorPosition() / termwidth != lines) {
if (terminal.isAnsiSupported()) {
// debug("doing backspace redraw: " + getCursorPosition() + " on " + termwidth + ": " + lines);
printAnsiSequence("J");
}
}
drawBuffer(count);
return count;
}
/**
* Issue a backspace.
*
* @return true if successful
*/
public boolean backspace() throws IOException {
return backspace(1) == 1;
}
private boolean moveToEnd() throws IOException {
return moveCursor(buf.length() - buf.cursor) > 0;
}
/**
* Delete the character at the current position and redraw the remainder of the buffer.
*/
private boolean deleteCurrentCharacter() throws IOException {
if (buf.length() == 0 || buf.cursor == buf.length()) {
return false;
}
buf.buffer.deleteCharAt(buf.cursor);
drawBuffer(1);
return true;
}
private boolean previousWord() throws IOException {
while (isDelimiter(buf.current()) && (moveCursor(-1) != 0)) {
// nothing
}
while (!isDelimiter(buf.current()) && (moveCursor(-1) != 0)) {
// nothing
}
return true;
}
private boolean nextWord() throws IOException {
while (isDelimiter(buf.current()) && (moveCursor(1) != 0)) {
// nothing
}
while (!isDelimiter(buf.current()) && (moveCursor(1) != 0)) {
// nothing
}
return true;
}
private boolean deletePreviousWord() throws IOException {
while (isDelimiter(buf.current()) && backspace()) {
// nothing
}
while (!isDelimiter(buf.current()) && backspace()) {
// nothing
}
return true;
}
/**
* Move the cursor <i>where</i> characters.
*
* @param num If less than 0, move abs(<i>where</i>) to the left, otherwise move <i>where</i> to the right.
* @return The number of spaces we moved
*/
public int moveCursor(final int num) throws IOException {
int where = num;
if ((buf.cursor == 0) && (where <= 0)) {
return 0;
}
if ((buf.cursor == buf.buffer.length()) && (where >= 0)) {
return 0;
}
if ((buf.cursor + where) < 0) {
where = -buf.cursor;
}
else if ((buf.cursor + where) > buf.buffer.length()) {
where = buf.buffer.length() - buf.cursor;
}
moveInternal(where);
return where;
}
/**
* Move the cursor <i>where</i> characters, without checking the current buffer.
*
* @param where the number of characters to move to the right or left.
*/
private void moveInternal(final int where) throws IOException {
// debug ("move cursor " + where + " ("
// + buf.cursor + " => " + (buf.cursor + where) + ")");
buf.cursor += where;
if (terminal.isAnsiSupported()) {
if (where < 0) {
back(Math.abs(where));
} else {
int width = getTerminal().getWidth();
int cursor = getCursorPosition();
int oldLine = (cursor - where) / width;
int newLine = cursor / width;
if (newLine > oldLine) {
printAnsiSequence((newLine - oldLine) + "B");
}
printAnsiSequence(1 +(cursor % width) + "G");
}
flush();
return;
}
char c;
if (where < 0) {
int len = 0;
for (int i = buf.cursor; i < buf.cursor - where; i++) {
if (buf.buffer.charAt(i) == '\t') {
len += TAB_WIDTH;
}
else {
len++;
}
}
char chars[] = new char[len];
Arrays.fill(chars, BACKSPACE);
out.write(chars);
return;
}
else if (buf.cursor == 0) {
return;
}
else if (mask != null) {
c = mask;
}
else {
print(buf.buffer.substring(buf.cursor - where, buf.cursor).toCharArray());
return;
}
// null character mask: don't output anything
if (mask == NULL_MASK) {
return;
}
print(c, Math.abs(where));
}
// FIXME: replace() is not used
public final boolean replace(final int num, final String replacement) {
buf.buffer.replace(buf.cursor - num, buf.cursor, replacement);
try {
moveCursor(-num);
drawBuffer(Math.max(0, num - replacement.length()));
moveCursor(replacement.length());
}
catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
//
// Key reading
//
/**
* Read a character from the console.
*
* @return the character, or -1 if an EOF is received.
*/
public final int readVirtualKey() throws IOException {
int c = terminal.readVirtualKey(in);
Log.trace("Keystroke: ", c);
// clear any echo characters
clearEcho(c);
return c;
}
/**
* Clear the echoed characters for the specified character code.
*/
private int clearEcho(final int c) throws IOException {
// if the terminal is not echoing, then ignore
if (!terminal.isEchoEnabled()) {
return 0;
}
// otherwise, clear
int num = countEchoCharacters((char) c);
back(num);
drawBuffer(num);
return num;
}
private int countEchoCharacters(final char c) {
// tabs as special: we need to determine the number of spaces
// to cancel based on what out current cursor position is
if (c == 9) {
int tabStop = 8; // will this ever be different?
int position = getCursorPosition();
return tabStop - (position % tabStop);
}
return getPrintableCharacters(c).length();
}
/**
* Return the number of characters that will be printed when the specified
* character is echoed to the screen
*
* Adapted from cat by Torbjorn Granlund, as repeated in stty by David MacKenzie.
*/
private StringBuilder getPrintableCharacters(final char ch) {
StringBuilder sbuff = new StringBuilder();
if (ch >= 32) {
if (ch < 127) {
sbuff.append(ch);
}
else if (ch == 127) {
sbuff.append('^');
sbuff.append('?');
}
else {
sbuff.append('M');
sbuff.append('-');
if (ch >= (128 + 32)) {
if (ch < (128 + 127)) {
sbuff.append((char) (ch - 128));
}
else {
sbuff.append('^');
sbuff.append('?');
}
}
else {
sbuff.append('^');
sbuff.append((char) (ch - 128 + 64));
}
}
}
else {
sbuff.append('^');
sbuff.append((char) (ch + 64));
}
return sbuff;
}
public final int readCharacter(final char... allowed) throws IOException {
// if we restrict to a limited set and the current character is not in the set, then try again.
char c;
Arrays.sort(allowed); // always need to sort before binarySearch
while (Arrays.binarySearch(allowed, c = (char) readVirtualKey()) < 0) {
// nothing
}
return c;
}
//
// Key Bindings
//
public static final String JLINE_COMPLETION_THRESHOLD = "jline.completion.threshold";
public static final String JLINE_KEYBINDINGS = "jline.keybindings";
public static final String JLINEBINDINGS_PROPERTIES = ".jlinebindings.properties";
/**
* The map for logical operations.
*/
private final short[] keyBindings;
private short[] loadKeyBindings(InputStream input) throws IOException {
if (input == null) {
try {
File file = new File(System.getProperty("user.home", JLINEBINDINGS_PROPERTIES));
String path = System.getProperty(JLINE_KEYBINDINGS);
if (path != null) {
file = new File(path);
}
if (file.isFile()) {
Log.debug("Loading user bindings from: ", file);
input = new FileInputStream(file);
}
}
catch (Exception e) {
Log.error("Failed to load user bindings", e);
}
}
if (input == null) {
Log.debug("Using default bindings");
input = getTerminal().getDefaultBindings();
}
short[] keyBindings = new short[Character.MAX_VALUE * 2];
Arrays.fill(keyBindings, Operation.UNKNOWN.code);
// Loads the key bindings. Bindings file is in the format:
//
// keycode: operation name
if (input != null) {
input = new BufferedInputStream(input);
Properties p = new Properties();
p.load(input);
input.close();
for (Object key : p.keySet()) {
String val = (String) key;
try {
short code = Short.parseShort(val);
String name = p.getProperty(val);
Operation op = Operation.valueOf(name);
keyBindings[code] = op.code;
}
catch (NumberFormatException e) {
Log.error("Failed to convert binding code: ", val, e);
}
}
// hardwired arrow key bindings
// keybindings[VK_UP] = PREV_HISTORY;
// keybindings[VK_DOWN] = NEXT_HISTORY;
// keybindings[VK_LEFT] = PREV_CHAR;
// keybindings[VK_RIGHT] = NEXT_CHAR;
}
return keyBindings;
}
int getKeyForAction(final short logicalAction) {
for (int i = 0; i < keyBindings.length; i++) {
if (keyBindings[i] == logicalAction) {
return i;
}
}
return -1;
}
int getKeyForAction(final Operation op) {
assert op != null;
return getKeyForAction(op.code);
}
/**
* Reads the console input and returns an array of the form [raw, key binding].
*/
private int[] readBinding() throws IOException {
int c = readVirtualKey();
if (c == -1) {
return null;
}
// extract the appropriate key binding
short code = keyBindings[c];
Log.trace("Translated: ", c, " -> ", code);
return new int[]{c, code};
}
//
// Line Reading
//
/**
* Read the next line and return the contents of the buffer.
*/
public String readLine() throws IOException {
return readLine((String) null);
}
/**
* Read the next line with the specified character mask. If null, then
* characters will be echoed. If 0, then no characters will be echoed.
*/
public String readLine(final Character mask) throws IOException {
return readLine(null, mask);
}
public String readLine(final String prompt) throws IOException {
return readLine(prompt, null);
}
/**
* Read a line from the <i>in</i> {@link InputStream}, and return the line
* (without any trailing newlines).
*
* @param prompt The prompt to issue to the console, may be null.
* @return A line that is read from the terminal, or null if there was null input (e.g., <i>CTRL-D</i>
* was pressed).
*/
public String readLine(String prompt, final Character mask) throws IOException {
// prompt may be null
// mask may be null
// FIXME: This blows, each call to readLine will reset the console's state which doesn't seem very nice.
this.mask = mask;
if (prompt != null) {
setPrompt(prompt);
}
else {
prompt = getPrompt();
}
try {
if (!terminal.isSupported()) {
beforeReadLine(prompt, mask);
}
if (prompt != null && prompt.length() > 0) {
out.write(prompt);
out.flush();
}
// if the terminal is unsupported, just use plain-java reading
if (!terminal.isSupported()) {
return readLine(in);
}
while (true) {
int[] next = readBinding();
if (next == null) {
return null;
}
int c = next[0];
// int code = next[1];
Operation code = Operation.valueOf(next[1]);
if (c == -1) {
return null;
}
boolean success = true;
switch (code) {
case EXIT: // ctrl-d
if (buf.buffer.length() == 0) {
return null;
+ } else {
+ deleteCurrentCharacter();
}
break;
case COMPLETE: // tab
success = complete();
break;
case MOVE_TO_BEG:
success = setCursorPosition(0);
break;
case KILL_LINE: // CTRL-K
success = killLine();
break;
case CLEAR_SCREEN: // CTRL-L
success = clearScreen();
break;
case KILL_LINE_PREV: // CTRL-U
success = resetLine();
break;
case NEWLINE: // enter
moveToEnd();
println(); // output newline
return finishBuffer();
case DELETE_PREV_CHAR: // backspace
success = backspace();
break;
case DELETE_NEXT_CHAR: // delete
success = deleteCurrentCharacter();
break;
case MOVE_TO_END:
success = moveToEnd();
break;
case PREV_CHAR:
success = moveCursor(-1) != 0;
break;
case NEXT_CHAR:
success = moveCursor(1) != 0;
break;
case NEXT_HISTORY:
success = moveHistory(true);
break;
case PREV_HISTORY:
success = moveHistory(false);
break;
case REDISPLAY:
break;
case PASTE:
success = paste();
break;
case DELETE_PREV_WORD:
success = deletePreviousWord();
break;
case PREV_WORD:
success = previousWord();
break;
case NEXT_WORD:
success = nextWord();
break;
case START_OF_HISTORY:
success = history.moveToFirst();
if (success) {
setBuffer(history.current());
}
break;
case END_OF_HISTORY:
success = history.moveToLast();
if (success) {
setBuffer(history.current());
}
break;
case CLEAR_LINE:
moveInternal(-(buf.buffer.length()));
killLine();
break;
case INSERT:
buf.setOverTyping(!buf.isOverTyping());
break;
case UNKNOWN:
default:
if (c != 0) { // ignore null chars
ActionListener action = triggeredActions.get((char) c);
if (action != null) {
action.actionPerformed(null);
}
else {
putChar(c, true);
}
}
else {
success = false;
}
}
if (!success) {
beep();
}
flush();
}
}
finally {
if (!terminal.isSupported()) {
afterReadLine();
}
}
}
/**
* Read a line for unsupported terminals.
*/
private String readLine(final InputStream in) throws IOException {
StringBuilder buff = new StringBuilder();
while (true) {
int i = in.read();
if (i == -1 || i == '\n' || i == '\r') {
return buff.toString();
}
buff.append((char) i);
}
// return new BufferedReader (new InputStreamReader (in)).readLine ();
}
//
// Completion
//
private final List<Completer> completers = new LinkedList<Completer>();
private CompletionHandler completionHandler = new CandidateListCompletionHandler();
/**
* Add the specified {@link jline.console.completer.Completer} to the list of handlers for tab-completion.
*
* @param completer the {@link jline.console.completer.Completer} to add
* @return true if it was successfully added
*/
public boolean addCompleter(final Completer completer) {
return completers.add(completer);
}
/**
* Remove the specified {@link jline.console.completer.Completer} from the list of handlers for tab-completion.
*
* @param completer The {@link Completer} to remove
* @return True if it was successfully removed
*/
public boolean removeCompleter(final Completer completer) {
return completers.remove(completer);
}
/**
* Returns an unmodifiable list of all the completers.
*/
public Collection<Completer> getCompleters() {
return Collections.unmodifiableList(completers);
}
public void setCompletionHandler(final CompletionHandler handler) {
assert handler != null;
this.completionHandler = handler;
}
public CompletionHandler getCompletionHandler() {
return this.completionHandler;
}
/**
* Use the completers to modify the buffer with the appropriate completions.
*
* @return true if successful
*/
private boolean complete() throws IOException {
// debug ("tab for (" + buf + ")");
if (completers.size() == 0) {
return false;
}
List<CharSequence> candidates = new LinkedList<CharSequence>();
String bufstr = buf.buffer.toString();
int cursor = buf.cursor;
int position = -1;
for (Completer comp : completers) {
if ((position = comp.complete(bufstr, cursor, candidates)) != -1) {
break;
}
}
return candidates.size() != 0 && getCompletionHandler().complete(this, candidates, position);
}
/**
* The number of tab-completion candidates above which a warning will be
* prompted before showing all the candidates.
*/
private int autoprintThreshold = Integer.getInteger(JLINE_COMPLETION_THRESHOLD, 100); // same default as bash
/**
* @param threshold the number of candidates to print without issuing a warning.
*/
public void setAutoprintThreshold(final int threshold) {
this.autoprintThreshold = threshold;
}
/**
* @return the number of candidates to print without issuing a warning.
*/
public int getAutoprintThreshold() {
return autoprintThreshold;
}
private boolean paginationEnabled;
/**
* Whether to use pagination when the number of rows of candidates exceeds the height of the terminal.
*/
public void setPaginationEnabled(final boolean enabled) {
this.paginationEnabled = enabled;
}
/**
* Whether to use pagination when the number of rows of candidates exceeds the height of the terminal.
*/
public boolean isPaginationEnabled() {
return paginationEnabled;
}
//
// History
//
private History history = new MemoryHistory();
public void setHistory(final History history) {
this.history = history;
}
public History getHistory() {
return history;
}
private boolean historyEnabled = true;
/**
* Whether or not to add new commands to the history buffer.
*/
public void setHistoryEnabled(final boolean enabled) {
this.historyEnabled = enabled;
}
/**
* Whether or not to add new commands to the history buffer.
*/
public boolean isHistoryEnabled() {
return historyEnabled;
}
/**
* Move up or down the history tree.
*/
private boolean moveHistory(final boolean next) throws IOException {
if (next && !history.next()) {
return false;
}
else if (!next && !history.previous()) {
return false;
}
setBuffer(history.current());
return true;
}
//
// Printing
//
public static final String CR = System.getProperty("line.separator");
/**
* Output the specified character to the output stream without manipulating the current buffer.
*/
private void print(final int c) throws IOException {
if (c == '\t') {
char chars[] = new char[TAB_WIDTH];
Arrays.fill(chars, ' ');
out.write(chars);
return;
}
out.write(c);
}
/**
* Output the specified characters to the output stream without manipulating the current buffer.
*/
private void print(final char... buff) throws IOException {
int len = 0;
for (char c : buff) {
if (c == '\t') {
len += TAB_WIDTH;
}
else {
len++;
}
}
char chars[];
if (len == buff.length) {
chars = buff;
}
else {
chars = new char[len];
int pos = 0;
for (char c : buff) {
if (c == '\t') {
Arrays.fill(chars, pos, pos + TAB_WIDTH, ' ');
pos += TAB_WIDTH;
}
else {
chars[pos] = c;
pos++;
}
}
}
out.write(chars);
}
private void print(final char c, final int num) throws IOException {
if (num == 1) {
print(c);
}
else {
char[] chars = new char[num];
Arrays.fill(chars, c);
print(chars);
}
}
/**
* Output the specified string to the output stream (but not the buffer).
*/
public final void print(final CharSequence s) throws IOException {
assert s != null;
print(s.toString().toCharArray());
}
public final void println(final CharSequence s) throws IOException {
assert s != null;
print(s.toString().toCharArray());
println();
}
/**
* Output a platform-dependant newline.
*/
public final void println() throws IOException {
print(CR);
flush();
}
//
// Actions
//
/**
* Issue a delete.
*
* @return true if successful
*/
public final boolean delete() throws IOException {
return delete(1) == 1;
}
// FIXME: delete(int) only used by above + the return is always 1 and num is ignored
/**
* Issue <em>num</em> deletes.
*
* @return the number of characters backed up
*/
private int delete(final int num) throws IOException {
// TODO: Try to use jansi for this
/* Commented out because of DWA-2949:
if (buf.cursor == 0) {
return 0;
}
*/
buf.buffer.delete(buf.cursor, buf.cursor + 1);
drawBuffer(1);
return 1;
}
/**
* Kill the buffer ahead of the current cursor position.
*
* @return true if successful
*/
public boolean killLine() throws IOException {
// TODO: USe jansi for this
int cp = buf.cursor;
int len = buf.buffer.length();
if (cp >= len) {
return false;
}
int num = buf.buffer.length() - cp;
clearAhead(num);
for (int i = 0; i < num; i++) {
buf.buffer.deleteCharAt(len - i - 1);
}
return true;
}
/**
* Clear the screen by issuing the ANSI "clear screen" code.
*/
public boolean clearScreen() throws IOException {
// TODO: use jansi for this
if (!terminal.isAnsiSupported()) {
return false;
}
// send the ANSI code to clear the screen
printAnsiSequence("2J");
// then send the ANSI code to go to position 1,1
printAnsiSequence("1;1H");
redrawLine();
return true;
}
/**
* Issue an audible keyboard bell, if {@link #isBellEnabled} return true.
*/
public void beep() throws IOException {
if (isBellEnabled()) {
print(KEYBOARD_BELL);
// need to flush so the console actually beeps
flush();
}
}
/**
* Paste the contents of the clipboard into the console buffer
*
* @return true if clipboard contents pasted
*/
public boolean paste() throws IOException {
Clipboard clipboard;
try { // May throw ugly exception on system without X
clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
}
catch (Exception e) {
return false;
}
if (clipboard == null) {
return false;
}
Transferable transferable = clipboard.getContents(null);
if (transferable == null) {
return false;
}
try {
Object content = transferable.getTransferData(DataFlavor.plainTextFlavor);
// This fix was suggested in bug #1060649 at
// http://sourceforge.net/tracker/index.php?func=detail&aid=1060649&group_id=64033&atid=506056
// to get around the deprecated DataFlavor.plainTextFlavor, but it
// raises a UnsupportedFlavorException on Mac OS X
if (content == null) {
try {
content = new DataFlavor().getReaderForText(transferable);
}
catch (Exception e) {
// ignore
}
}
if (content == null) {
return false;
}
String value;
if (content instanceof Reader) {
// TODO: we might want instead connect to the input stream
// so we can interpret individual lines
value = "";
String line;
BufferedReader read = new BufferedReader((Reader) content);
while ((line = read.readLine()) != null) {
if (value.length() > 0) {
value += "\n";
}
value += line;
}
}
else {
value = content.toString();
}
if (value == null) {
return true;
}
putString(value);
return true;
}
catch (UnsupportedFlavorException e) {
Log.error("Paste failed: ", e);
return false;
}
}
//
// Triggered Actions
//
private final Map<Character, ActionListener> triggeredActions = new HashMap<Character, ActionListener>();
/**
* Adding a triggered Action allows to give another curse of action if a character passed the pre-processing.
* <p/>
* Say you want to close the application if the user enter q.
* addTriggerAction('q', new ActionListener(){ System.exit(0); }); would do the trick.
*/
public void addTriggeredAction(final char c, final ActionListener listener) {
triggeredActions.put(c, listener);
}
//
// Formatted Output
//
/**
* Output the specified {@link Collection} in proper columns.
*/
public void printColumns(final Collection<? extends CharSequence> items) throws IOException {
if (items == null || items.isEmpty()) {
return;
}
int width = getTerminal().getWidth();
int height = getTerminal().getHeight();
int maxWidth = 0;
for (CharSequence item : items) {
maxWidth = Math.max(maxWidth, item.length());
}
Log.debug("Max width: ", maxWidth);
int showLines;
if (isPaginationEnabled()) {
showLines = height - 1; // page limit
}
else {
showLines = Integer.MAX_VALUE;
}
StringBuilder buff = new StringBuilder();
for (CharSequence item : items) {
if ((buff.length() + maxWidth) > width) {
println(buff);
buff.setLength(0);
if (--showLines == 0) {
// Overflow
print(resources.getString("display-more"));
flush();
int c = readVirtualKey();
if (c == '\r' || c == '\n') {
// one step forward
showLines = 1;
}
else if (c != 'q') {
// page forward
showLines = height - 1;
}
back(resources.getString("display-more").length());
if (c == 'q') {
// cancel
break;
}
}
}
// NOTE: toString() is important here due to AnsiString being retarded
buff.append(item.toString());
for (int i = 0; i < (maxWidth + 3 - item.length()); i++) {
buff.append(' ');
}
}
if (buff.length() > 0) {
println(buff);
}
}
//
// Non-supported Terminal Support
//
private Thread maskThread;
private void beforeReadLine(final String prompt, final Character mask) {
if (mask != null && maskThread == null) {
final String fullPrompt = "\r" + prompt
+ " "
+ " "
+ " "
+ "\r" + prompt;
maskThread = new Thread()
{
public void run() {
while (!interrupted()) {
try {
Writer out = getOutput();
out.write(fullPrompt);
out.flush();
sleep(3);
}
catch (IOException e) {
return;
}
catch (InterruptedException e) {
return;
}
}
}
};
maskThread.setPriority(Thread.MAX_PRIORITY);
maskThread.setDaemon(true);
maskThread.start();
}
}
private void afterReadLine() {
if (maskThread != null && maskThread.isAlive()) {
maskThread.interrupt();
}
maskThread = null;
}
//
// Helpers
//
/**
* Checks to see if the specified character is a delimiter. We consider a
* character a delimiter if it is anything but a letter or digit.
*
* @param c The character to test
* @return True if it is a delimiter
*/
private boolean isDelimiter(final char c) {
return !Character.isLetterOrDigit(c);
}
private void printAnsiSequence(String sequence) throws IOException {
print(27);
print('[');
print(sequence);
flush();
}
}
| true | true | public String readLine(String prompt, final Character mask) throws IOException {
// prompt may be null
// mask may be null
// FIXME: This blows, each call to readLine will reset the console's state which doesn't seem very nice.
this.mask = mask;
if (prompt != null) {
setPrompt(prompt);
}
else {
prompt = getPrompt();
}
try {
if (!terminal.isSupported()) {
beforeReadLine(prompt, mask);
}
if (prompt != null && prompt.length() > 0) {
out.write(prompt);
out.flush();
}
// if the terminal is unsupported, just use plain-java reading
if (!terminal.isSupported()) {
return readLine(in);
}
while (true) {
int[] next = readBinding();
if (next == null) {
return null;
}
int c = next[0];
// int code = next[1];
Operation code = Operation.valueOf(next[1]);
if (c == -1) {
return null;
}
boolean success = true;
switch (code) {
case EXIT: // ctrl-d
if (buf.buffer.length() == 0) {
return null;
}
break;
case COMPLETE: // tab
success = complete();
break;
case MOVE_TO_BEG:
success = setCursorPosition(0);
break;
case KILL_LINE: // CTRL-K
success = killLine();
break;
case CLEAR_SCREEN: // CTRL-L
success = clearScreen();
break;
case KILL_LINE_PREV: // CTRL-U
success = resetLine();
break;
case NEWLINE: // enter
moveToEnd();
println(); // output newline
return finishBuffer();
case DELETE_PREV_CHAR: // backspace
success = backspace();
break;
case DELETE_NEXT_CHAR: // delete
success = deleteCurrentCharacter();
break;
case MOVE_TO_END:
success = moveToEnd();
break;
case PREV_CHAR:
success = moveCursor(-1) != 0;
break;
case NEXT_CHAR:
success = moveCursor(1) != 0;
break;
case NEXT_HISTORY:
success = moveHistory(true);
break;
case PREV_HISTORY:
success = moveHistory(false);
break;
case REDISPLAY:
break;
case PASTE:
success = paste();
break;
case DELETE_PREV_WORD:
success = deletePreviousWord();
break;
case PREV_WORD:
success = previousWord();
break;
case NEXT_WORD:
success = nextWord();
break;
case START_OF_HISTORY:
success = history.moveToFirst();
if (success) {
setBuffer(history.current());
}
break;
case END_OF_HISTORY:
success = history.moveToLast();
if (success) {
setBuffer(history.current());
}
break;
case CLEAR_LINE:
moveInternal(-(buf.buffer.length()));
killLine();
break;
case INSERT:
buf.setOverTyping(!buf.isOverTyping());
break;
case UNKNOWN:
default:
if (c != 0) { // ignore null chars
ActionListener action = triggeredActions.get((char) c);
if (action != null) {
action.actionPerformed(null);
}
else {
putChar(c, true);
}
}
else {
success = false;
}
}
if (!success) {
beep();
}
flush();
}
}
finally {
if (!terminal.isSupported()) {
afterReadLine();
}
}
}
| public String readLine(String prompt, final Character mask) throws IOException {
// prompt may be null
// mask may be null
// FIXME: This blows, each call to readLine will reset the console's state which doesn't seem very nice.
this.mask = mask;
if (prompt != null) {
setPrompt(prompt);
}
else {
prompt = getPrompt();
}
try {
if (!terminal.isSupported()) {
beforeReadLine(prompt, mask);
}
if (prompt != null && prompt.length() > 0) {
out.write(prompt);
out.flush();
}
// if the terminal is unsupported, just use plain-java reading
if (!terminal.isSupported()) {
return readLine(in);
}
while (true) {
int[] next = readBinding();
if (next == null) {
return null;
}
int c = next[0];
// int code = next[1];
Operation code = Operation.valueOf(next[1]);
if (c == -1) {
return null;
}
boolean success = true;
switch (code) {
case EXIT: // ctrl-d
if (buf.buffer.length() == 0) {
return null;
} else {
deleteCurrentCharacter();
}
break;
case COMPLETE: // tab
success = complete();
break;
case MOVE_TO_BEG:
success = setCursorPosition(0);
break;
case KILL_LINE: // CTRL-K
success = killLine();
break;
case CLEAR_SCREEN: // CTRL-L
success = clearScreen();
break;
case KILL_LINE_PREV: // CTRL-U
success = resetLine();
break;
case NEWLINE: // enter
moveToEnd();
println(); // output newline
return finishBuffer();
case DELETE_PREV_CHAR: // backspace
success = backspace();
break;
case DELETE_NEXT_CHAR: // delete
success = deleteCurrentCharacter();
break;
case MOVE_TO_END:
success = moveToEnd();
break;
case PREV_CHAR:
success = moveCursor(-1) != 0;
break;
case NEXT_CHAR:
success = moveCursor(1) != 0;
break;
case NEXT_HISTORY:
success = moveHistory(true);
break;
case PREV_HISTORY:
success = moveHistory(false);
break;
case REDISPLAY:
break;
case PASTE:
success = paste();
break;
case DELETE_PREV_WORD:
success = deletePreviousWord();
break;
case PREV_WORD:
success = previousWord();
break;
case NEXT_WORD:
success = nextWord();
break;
case START_OF_HISTORY:
success = history.moveToFirst();
if (success) {
setBuffer(history.current());
}
break;
case END_OF_HISTORY:
success = history.moveToLast();
if (success) {
setBuffer(history.current());
}
break;
case CLEAR_LINE:
moveInternal(-(buf.buffer.length()));
killLine();
break;
case INSERT:
buf.setOverTyping(!buf.isOverTyping());
break;
case UNKNOWN:
default:
if (c != 0) { // ignore null chars
ActionListener action = triggeredActions.get((char) c);
if (action != null) {
action.actionPerformed(null);
}
else {
putChar(c, true);
}
}
else {
success = false;
}
}
if (!success) {
beep();
}
flush();
}
}
finally {
if (!terminal.isSupported()) {
afterReadLine();
}
}
}
|
diff --git a/srcj/com/sun/electric/tool/io/output/Spice.java b/srcj/com/sun/electric/tool/io/output/Spice.java
index e02c42cf4..e2bf69124 100644
--- a/srcj/com/sun/electric/tool/io/output/Spice.java
+++ b/srcj/com/sun/electric/tool/io/output/Spice.java
@@ -1,3019 +1,3019 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: Spice.java
* Original C Code written by Steven M. Rubin and Sid Penstone
* Translated to Java by Steven M. Rubin, Sun Microsystems.
*
* Copyright (c) 2004 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.io.output;
import com.sun.electric.database.geometry.GeometryHandler;
import com.sun.electric.database.geometry.Poly;
import com.sun.electric.database.geometry.PolyBase;
import com.sun.electric.database.geometry.PolyMerge;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.hierarchy.Export;
import com.sun.electric.database.hierarchy.HierarchyEnumerator;
import com.sun.electric.database.hierarchy.Nodable;
import com.sun.electric.database.hierarchy.View;
import com.sun.electric.database.network.Global;
import com.sun.electric.database.network.Netlist;
import com.sun.electric.database.network.Network;
import com.sun.electric.database.prototype.NodeProto;
import com.sun.electric.database.prototype.PortProto;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.database.text.Version;
import com.sun.electric.database.topology.ArcInst;
import com.sun.electric.database.topology.NodeInst;
import com.sun.electric.database.topology.PortInst;
import com.sun.electric.database.variable.CodeExpression;
import com.sun.electric.database.variable.TextDescriptor;
import com.sun.electric.database.variable.VarContext;
import com.sun.electric.database.variable.Variable;
import com.sun.electric.technology.ArcProto;
import com.sun.electric.technology.Foundry;
import com.sun.electric.technology.Layer;
import com.sun.electric.technology.PrimitiveNode;
import com.sun.electric.technology.PrimitiveNodeSize;
import com.sun.electric.technology.Technology;
import com.sun.electric.technology.TransistorSize;
import com.sun.electric.technology.technologies.Generic;
import com.sun.electric.technology.technologies.Schematics;
import com.sun.electric.tool.generator.sclibrary.SCLibraryGen;
import com.sun.electric.tool.io.FileType;
import com.sun.electric.tool.io.input.Simulate;
import com.sun.electric.tool.io.input.spicenetlist.SpiceNetlistReader;
import com.sun.electric.tool.io.input.spicenetlist.SpiceSubckt;
import com.sun.electric.tool.ncc.basic.NccCellAnnotations;
import com.sun.electric.tool.ncc.basic.NccCellAnnotations.NamePattern;
import com.sun.electric.tool.simulation.Simulation;
import com.sun.electric.tool.user.Exec;
import com.sun.electric.tool.user.User;
import com.sun.electric.tool.user.dialogs.ExecDialog;
import com.sun.electric.tool.user.ui.TopLevel;
import com.sun.electric.tool.user.waveform.WaveformWindow;
import java.awt.geom.AffineTransform;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* This is the Simulation Interface tool.
*/
public class Spice extends Topology
{
private static final boolean DETECT_SPICE_PARAMS = true;
private static final boolean USE_JAVA_CODE = true;
/** key of Variable holding generic Spice templates. */ public static final Variable.Key SPICE_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template");
/** key of Variable holding Spice 2 templates. */ public static final Variable.Key SPICE_2_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_spice2");
/** key of Variable holding Spice 3 templates. */ public static final Variable.Key SPICE_3_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_spice3");
/** key of Variable holding HSpice templates. */ public static final Variable.Key SPICE_H_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_hspice");
/** key of Variable holding PSpice templates. */ public static final Variable.Key SPICE_P_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_pspice");
/** key of Variable holding GnuCap templates. */ public static final Variable.Key SPICE_GC_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_gnucap");
/** key of Variable holding Smart Spice templates. */ public static final Variable.Key SPICE_SM_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_smartspice");
/** key of Variable holding Smart Spice templates. */ public static final Variable.Key SPICE_A_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_assura");
/** key of Variable holding Smart Spice templates. */ public static final Variable.Key SPICE_C_TEMPLATE_KEY = Variable.newKey("ATTR_SPICE_template_calibre");
/** key of Variable holding Spice model file. */ public static final Variable.Key SPICE_NETLIST_FILE_KEY = Variable.newKey("ATTR_SPICE_netlist_file");
/** key of Variable holding SPICE code. */ public static final Variable.Key SPICE_CARD_KEY = Variable.newKey("SIM_spice_card");
/** key of Variable holding SPICE declaration. */ public static final Variable.Key SPICE_DECLARATION_KEY = Variable.newKey("SIM_spice_declaration");
/** key of Variable holding SPICE model. */ public static final Variable.Key SPICE_MODEL_KEY = Variable.newKey("SIM_spice_model");
/** key of Variable holding SPICE flat code. */ public static final Variable.Key SPICE_CODE_FLAT_KEY = Variable.newKey("SIM_spice_code_flat");
/** key of Variable holding generic CDL templates. */ public static final Variable.Key CDL_TEMPLATE_KEY = Variable.newKey("ATTR_CDL_template");
/** Prefix for spice extension. */ public static final String SPICE_EXTENSION_PREFIX = "Extension ";
/** Prefix for spice null extension. */ public static final String SPICE_NOEXTENSION_PREFIX = "N O N E ";
/** maximum subcircuit name length */ private static final int SPICEMAXLENSUBCKTNAME = 70;
/** maximum subcircuit name length */ private static final int CDLMAXLENSUBCKTNAME = 40;
/** maximum subcircuit name length */ private static final int SPICEMAXLENLINE = 78;
/** legal characters in a spice deck */ private static final String SPICELEGALCHARS = "!#$%*+-/<>[]_@";
/** legal characters in a spice deck */ private static final String PSPICELEGALCHARS = "!#$%*+-/<>[]_";
/** legal characters in a CDL deck */ private static final String CDLNOBRACKETLEGALCHARS = "!#$%*+-/<>_";
/** if CDL writes out empty subckt definitions */ private static final boolean CDLWRITESEMPTYSUBCKTS = false;
/** A mark for uniquify */ private static final Set<Variable.Key> UNIQUIFY_MARK = Collections.emptySet();
/** default Technology to use. */ private Technology layoutTechnology;
/** Mask shrink factor (default =1) */ private double maskScale;
/** True to write CDL format */ private boolean useCDL;
/** Legal characters */ private String legalSpiceChars;
/** Template Key for current spice engine */ private Variable.Key preferedEngineTemplateKey;
/** Special case for HSpice for Assura */ private boolean assuraHSpice = false;
/** Spice type: 2, 3, H, P, etc */ private Simulation.SpiceEngine spiceEngine;
/** those cells that have overridden models */ private Map<Cell,String> modelOverrides = new HashMap<Cell,String>();
/** Parameters used for Spice */ private Map<NodeProto,Set<Variable.Key>> allSpiceParams = new HashMap<NodeProto,Set<Variable.Key>>();
/** for RC parasitics */ private SpiceParasiticsGeneral parasiticInfo;
/** Networks exempted during parasitic ext */ private SpiceExemptedNets exemptedNets;
/** Whether or not to write empty subckts */ private boolean writeEmptySubckts = true;
/** max length per line */ private int spiceMaxLenLine = SPICEMAXLENLINE;
/** Flat measurements file */ private FlatSpiceCodeVisitor spiceCodeFlat = null;
/** map of "parameterized" cells not covered by Topology */ private Map<Cell,Cell> uniquifyCells;
/** uniqueID */ private int uniqueID;
/** map of shortened instance names */ private Map<String,Integer> uniqueNames;
/**
* Constructor for the Spice netlister.
*/
Spice() {}
/**
* The main entry point for Spice deck writing.
* @param cell the top-level cell to write.
* @param context the hierarchical context to the cell.
* @param filePath the disk file to create.
* @param cdl true if this is CDL output (false for Spice).
*/
public static void writeSpiceFile(Cell cell, VarContext context, String filePath, boolean cdl)
{
Spice out = new Spice();
out.useCDL = cdl;
if (out.openTextOutputStream(filePath)) return;
if (out.writeCell(cell, context)) return;
if (out.closeTextOutputStream()) return;
System.out.println(filePath + " written");
// write CDL support file if requested
if (out.useCDL)
{
// write the control files
String deckFile = filePath;
String deckPath = "";
int lastDirSep = deckFile.lastIndexOf(File.separatorChar);
if (lastDirSep > 0)
{
deckPath = deckFile.substring(0, lastDirSep);
deckFile = deckFile.substring(lastDirSep+1);
}
String templateFile = deckPath + File.separator + cell.getName() + ".cdltemplate";
if (out.openTextOutputStream(templateFile)) return;
String libName = Simulation.getCDLLibName();
String libPath = Simulation.getCDLLibPath();
out.printWriter.print("cdlInKeys = list(nil\n");
out.printWriter.print(" 'searchPath \"" + deckFile + "");
if (libPath.length() > 0)
out.printWriter.print("\n " + libPath);
out.printWriter.print("\"\n");
out.printWriter.print(" 'cdlFile \"" + deckPath + File.separator + deckFile + "\"\n");
out.printWriter.print(" 'userSkillFile \"\"\n");
out.printWriter.print(" 'opusLib \"" + libName + "\"\n");
out.printWriter.print(" 'primaryCell \"" + cell.getName() + "\"\n");
out.printWriter.print(" 'caseSensitivity \"lower\"\n");
out.printWriter.print(" 'hierarchy \"flatten\"\n");
out.printWriter.print(" 'cellTable \"\"\n");
out.printWriter.print(" 'viewName \"netlist\"\n");
out.printWriter.print(" 'viewType \"\"\n");
out.printWriter.print(" 'pr nil\n");
out.printWriter.print(" 'skipDevice nil\n");
out.printWriter.print(" 'schemaLib \"sample\"\n");
out.printWriter.print(" 'refLib \"\"\n");
out.printWriter.print(" 'globalNodeExpand \"full\"\n");
out.printWriter.print(")\n");
if (out.closeTextOutputStream()) return;
System.out.println(templateFile + " written");
}
String runSpice = Simulation.getSpiceRunChoice();
if (!runSpice.equals(Simulation.spiceRunChoiceDontRun)) {
String command = Simulation.getSpiceRunProgram() + " " + Simulation.getSpiceRunProgramArgs();
// see if user specified custom dir to run process in
String workdir = User.getWorkingDirectory();
String rundir = workdir;
if (Simulation.getSpiceUseRunDir()) {
rundir = Simulation.getSpiceRunDir();
}
File dir = new File(rundir);
int start = filePath.lastIndexOf(File.separator);
if (start == -1) start = 0; else {
start++;
if (start > filePath.length()) start = filePath.length();
}
int end = filePath.lastIndexOf(".");
if (end == -1) end = filePath.length();
String filename_noext = filePath.substring(start, end);
String filename = filePath.substring(start, filePath.length());
// replace vars in command and args
command = command.replaceAll("\\$\\{WORKING_DIR}", workdir);
command = command.replaceAll("\\$\\{USE_DIR}", rundir);
command = command.replaceAll("\\$\\{FILENAME}", filename);
command = command.replaceAll("\\$\\{FILENAME_NO_EXT}", filename_noext);
// set up run probe
FileType type = Simulate.getCurrentSpiceOutputType();
String [] extensions = type.getExtensions();
String outFile = rundir + File.separator + filename_noext + "." + extensions[0];
Exec.FinishedListener l = new SpiceFinishedListener(cell, type, outFile);
if (runSpice.equals(Simulation.spiceRunChoiceRunIgnoreOutput)) {
Exec e = new Exec(command, null, dir, null, null);
if (Simulation.getSpiceRunProbe()) e.addFinishedListener(l);
e.start();
}
if (runSpice.equals(Simulation.spiceRunChoiceRunReportOutput)) {
ExecDialog dialog = new ExecDialog(TopLevel.getCurrentJFrame(), false);
if (Simulation.getSpiceRunProbe()) dialog.addFinishedListener(l);
dialog.startProcess(command, null, dir);
}
System.out.println("Running spice command: "+command);
}
if (Simulation.isParasiticsBackAnnotateLayout() && out.parasiticInfo != null)
{
out.parasiticInfo.backAnnotate();
}
}
/**
* Method called once by the traversal mechanism.
* Initializes Spice netlisting and writes headers.
*/
protected void start()
{
// find the proper technology to use if this is schematics
if (topCell.getTechnology().isLayout())
layoutTechnology = topCell.getTechnology();
else
layoutTechnology = Schematics.getDefaultSchematicTechnology();
// make sure key is cached
spiceEngine = Simulation.getSpiceEngine();
preferedEngineTemplateKey = SPICE_TEMPLATE_KEY;
assuraHSpice = false;
switch (spiceEngine)
{
case SPICE_ENGINE_2: preferedEngineTemplateKey = SPICE_2_TEMPLATE_KEY; break;
case SPICE_ENGINE_3: preferedEngineTemplateKey = SPICE_3_TEMPLATE_KEY; break;
case SPICE_ENGINE_H: preferedEngineTemplateKey = SPICE_H_TEMPLATE_KEY; break;
case SPICE_ENGINE_P: preferedEngineTemplateKey = SPICE_P_TEMPLATE_KEY; break;
case SPICE_ENGINE_G: preferedEngineTemplateKey = SPICE_GC_TEMPLATE_KEY; break;
case SPICE_ENGINE_S: preferedEngineTemplateKey = SPICE_SM_TEMPLATE_KEY; break;
case SPICE_ENGINE_H_ASSURA: preferedEngineTemplateKey = SPICE_A_TEMPLATE_KEY; assuraHSpice = true; break;
case SPICE_ENGINE_H_CALIBRE: preferedEngineTemplateKey = SPICE_C_TEMPLATE_KEY; assuraHSpice = true; break;
}
if (useCDL) {
preferedEngineTemplateKey = CDL_TEMPLATE_KEY;
}
if (assuraHSpice || (useCDL && !CDLWRITESEMPTYSUBCKTS) ||
(!useCDL && !Simulation.isSpiceWriteEmtpySubckts())) {
writeEmptySubckts = false;
}
// get the mask scale
maskScale = 1.0;
// Variable scaleVar = layoutTechnology.getVar("SIM_spice_mask_scale");
// if (scaleVar != null) maskScale = TextUtils.atof(scaleVar.getObject().toString());
// set up the parameterized cells
uniquifyCells = new HashMap<Cell,Cell>();
uniqueID = 0;
uniqueNames = new HashMap<String,Integer>();
markCellsToUniquify(topCell);
// setup the legal characters
legalSpiceChars = SPICELEGALCHARS;
if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_P ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_G) legalSpiceChars = PSPICELEGALCHARS;
// start writing the spice deck
if (useCDL)
{
// setup bracket conversion for CDL
if (Simulation.isCDLConvertBrackets())
legalSpiceChars = CDLNOBRACKETLEGALCHARS;
multiLinePrint(true, "* First line is ignored\n");
// see if include file specified
String headerPath = TextUtils.getFilePath(topCell.getLibrary().getLibFile());
String filePart = Simulation.getCDLIncludeFile();
if (!filePart.equals("")) {
String fileName = headerPath + filePart;
File test = new File(fileName);
if (test.exists())
{
multiLinePrint(true, "* Primitives described in this file:\n");
addIncludeFile(filePart);
} else {
System.out.println("Warning: CDL Include file not found: "+fileName);
}
}
} else
{
writeHeader(topCell);
spiceCodeFlat = new FlatSpiceCodeVisitor(filePath+".flatcode", this);
HierarchyEnumerator.enumerateCell(topCell, VarContext.globalContext, spiceCodeFlat, getShortResistorsFlat());
spiceCodeFlat.close();
}
if (Simulation.isParasiticsUseExemptedNetsFile()) {
String headerPath = TextUtils.getFilePath(topCell.getLibrary().getLibFile());
exemptedNets = new SpiceExemptedNets(new File(headerPath + File.separator + "exemptedNets.txt"));
}
}
/**
* Method called once at the end of netlisting.
*/
protected void done()
{
if (!useCDL)
{
writeTrailer(topCell);
if (Simulation.isSpiceWriteFinalDotEnd())
multiLinePrint(false, ".END\n");
}
}
/**
* Method called by traversal mechanism to write one level of hierarchy in the Spice netlist.
* This could be the top level or a subcircuit.
* The bulk of the Spice netlisting happens here.
*/
protected void writeCellTopology(Cell cell, CellNetInfo cni, VarContext context, Topology.MyCellInfo info)
{
// if this is the top level cell, write globals
if (cell == topCell)
{
Netlist netList = cni.getNetList();
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (!Simulation.isSpiceUseNodeNames() || spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_3)
{
if (globalSize > 0)
{
StringBuffer infstr = new StringBuffer();
infstr.append("\n.global");
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
String name = global.getName();
if (global == Global.power) { if (getPowerName(null) != null) name = getPowerName(null); }
if (global == Global.ground) { if (getGroundName(null) != null) name = getGroundName(null); }
infstr.append(" " + name);
}
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
}
// make sure power and ground appear at the top level
if (!Simulation.isSpiceForceGlobalPwrGnd())
{
if (cni.getPowerNet() == null)
System.out.println("WARNING: cannot find power at top level of circuit");
if (cni.getGroundNet() == null)
System.out.println("WARNING: cannot find ground at top level of circuit");
}
}
// create electrical nets (SpiceNet) for every Network in the cell
Netlist netList = cni.getNetList();
Map<Network,SpiceNet> spiceNetMap = new HashMap<Network,SpiceNet>();
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
SpiceNet spNet = new SpiceNet(net);
spiceNetMap.put(net, spNet);
}
// for non-simple parasitics, create a SpiceSegmentedNets object to deal with them
Simulation.SpiceParasitics spLevel = Simulation.getSpiceParasiticsLevel();
if (useCDL || cell.getView() != View.LAYOUT) spLevel = Simulation.SpiceParasitics.SIMPLE;
SpiceSegmentedNets segmentedNets = null;
if (spLevel != Simulation.SpiceParasitics.SIMPLE)
{
// make the parasitics info object if it does not already exist
if (parasiticInfo == null)
{
if (spLevel == Simulation.SpiceParasitics.RC_PROXIMITY)
{
parasiticInfo = new SpiceParasitic();
} else if (spLevel == Simulation.SpiceParasitics.RC_CONSERVATIVE)
{
parasiticInfo = new SpiceRCSimple();
}
}
segmentedNets = parasiticInfo.initializeSegments(cell, cni, layoutTechnology, exemptedNets, info);
}
// count the number of different transistor types
int bipolarTrans = 0, nmosTrans = 0, pmosTrans = 0;
for(Iterator<NodeInst> aIt = cell.getNodes(); aIt.hasNext(); )
{
NodeInst ni = aIt.next();
addNodeInformation(netList, spiceNetMap, ni);
PrimitiveNode.Function fun = ni.getFunction();
if (fun == PrimitiveNode.Function.TRANPN || fun == PrimitiveNode.Function.TRA4NPN ||
fun == PrimitiveNode.Function.TRAPNP || fun == PrimitiveNode.Function.TRA4PNP ||
fun == PrimitiveNode.Function.TRANS) bipolarTrans++; else
if (fun.isNTypeTransistor()) nmosTrans++; else
if (fun.isPTypeTransistor()) pmosTrans++;
}
// accumulate geometry of all arcs
for(Iterator<ArcInst> aIt = cell.getArcs(); aIt.hasNext(); )
{
ArcInst ai = aIt.next();
// don't count non-electrical arcs
if (ai.getProto().getFunction() == ArcProto.Function.NONELEC) continue;
// ignore busses
// if (ai->network->buswidth > 1) continue;
Network net = netList.getNetwork(ai, 0);
SpiceNet spNet = spiceNetMap.get(net);
if (spNet == null) continue;
addArcInformation(spNet.merge, ai);
}
// get merged polygons so far
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
SpiceNet spNet = spiceNetMap.get(net);
for (Layer layer : spNet.merge.getKeySet())
{
List<PolyBase> polyList = spNet.merge.getMergedPoints(layer, true);
if (polyList == null) continue;
if (polyList.size() > 1)
Collections.sort(polyList, GeometryHandler.shapeSort);
for(PolyBase poly : polyList)
{
// compute perimeter and area
double perim = poly.getPerimeter();
double area = poly.getArea();
// accumulate this information
double scale = layoutTechnology.getScale(); // scale to convert units to nanometers
if (layer.isDiffusionLayer()) {
spNet.diffArea += area * maskScale * maskScale;
spNet.diffPerim += perim * maskScale;
} else {
area = area * scale * scale / 1000000; // area in square microns
perim = perim * scale / 1000; // perim in microns
spNet.nonDiffCapacitance += layer.getCapacitance() * area * maskScale * maskScale;
spNet.nonDiffCapacitance += layer.getEdgeCapacitance() * perim * maskScale;
}
}
}
}
// make sure the ground net is number zero
Network groundNet = cni.getGroundNet();
Network powerNet = cni.getPowerNet();
if (pmosTrans != 0 && powerNet == null)
{
String message = "WARNING: no power connection for P-transistor wells in " + cell;
dumpErrorMessage(message);
}
if (nmosTrans != 0 && groundNet == null)
{
String message = "WARNING: no ground connection for N-transistor wells in " + cell;
dumpErrorMessage(message);
}
// generate header for subckt or top-level cell
boolean forceEval = useCDL || !Simulation.isSpiceUseCellParameters() || detectSpiceParams(cell) == UNIQUIFY_MARK;
String topLevelInstance = "";
if (cell == topCell && !useCDL && !Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(true, "\n*** TOP LEVEL CELL: " + cell.describe(false) + "\n");
} else
{
if (!writeEmptySubckts) {
if (cellIsEmpty(cell))
return;
}
String cellName = cni.getParameterizedName();
multiLinePrint(true, "\n*** CELL: " + cell.describe(false) + "\n");
StringBuffer infstr = new StringBuffer();
infstr.append(".SUBCKT " + cellName);
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
if (ignoreSubcktPort(cs)) continue;
if (!cs.isGlobal() && cs.getExport() == null) continue;
// special case for parasitic extraction
if (parasiticInfo != null && !cs.isGlobal() && cs.getExport() != null)
{
parasiticInfo.writeSubcircuitHeader(cs, infstr);
} else
{
infstr.append(" " + cs.getName());
}
}
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
// create top level instantiation
if (Simulation.isSpiceWriteTopCellInstance())
topLevelInstance = infstr.toString().replaceFirst("\\.SUBCKT ", "X") + " " + cellName;
}
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this cell
Set<Variable.Key> spiceParams = detectSpiceParams(cell);
for(Iterator<Variable> it = cell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
if (DETECT_SPICE_PARAMS && !spiceParams.contains(paramVar.getKey())) continue;
String value = paramVar.getPureValue(-1);
if (USE_JAVA_CODE) {
value = evalParam(context, info.getParentInst(), paramVar, forceEval);
} else if (!isNetlistableParam(paramVar))
continue;
infstr.append(" " + paramVar.getTrueName() + "=" + value);
}
}
infstr.append("\n");
multiLinePrint(false, infstr.toString());
// generate pin descriptions for reference (when not using node names)
if (!Simulation.isSpiceUseNodeNames() || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3)
{
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
Network net = netList.getNetwork(global);
CellSignal cs = cni.getCellSignal(net);
multiLinePrint(true, "** GLOBAL " + cs.getName() + "\n");
}
}
}
// write out any directly-typed SPICE declaratons for the cell
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech().invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_DECLARATION_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Declaration nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false, forceEval);
}
}
// third pass through the node list, print it this time
for(Iterator<Nodable> nIt = netList.getNodables(); nIt.hasNext(); )
{
Nodable no = nIt.next();
NodeProto niProto = no.getProto();
// boolean includePwrVdd = Simulation.isSpiceWritePwrGndInTopCell();
// handle sub-cell calls
if (no.isCellInstance())
{
Cell subCell = (Cell)niProto;
// get the SPICE template on the prototype (if any)
Variable varTemplate = getEngineTemplate(subCell);
if (varTemplate != null)
{
if (varTemplate.getObject() instanceof Object[])
{
Object [] manyLines = (Object [])varTemplate.getObject();
for(int i=0; i<manyLines.length; i++)
{
String line = manyLines[i].toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false, forceEval);
// Writing MFactor if available. Not sure here
if (i == 0) writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
} else
{
String line = varTemplate.getObject().toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false, forceEval);
// Writing MFactor if available. Not sure here
writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
continue;
}
// get the ports on this node (in proper order)
CellNetInfo subCni = getCellNetInfo(parameterizedName(no, context));
if (subCni == null) continue;
if (!writeEmptySubckts)
{
// do not instantiate if empty
if (cellIsEmpty((Cell)niProto)) continue;
}
String modelChar = "X";
if (no.getName() != null) modelChar += getSafeNetName(no.getName(), false);
StringBuffer infstr = new StringBuffer();
infstr.append(modelChar);
for(Iterator<CellSignal> sIt = subCni.getCellSignals(); sIt.hasNext(); )
{
CellSignal subCS = sIt.next();
if (ignoreSubcktPort(subCS)) continue;
PortProto pp = subCS.getExport();
if (!subCS.isGlobal() && pp == null) continue;
// If global pwr/vdd will be included in the subcircuit
// Preparing code for bug #1828
// if (!Simulation.isSpiceWritePwrGndInTopCell() && pp!= null && subCS.isGlobal() && (subCS.isGround() || subCS.isPower()))
// continue;
Network net;
int exportIndex = subCS.getExportIndex();
// This checks if we are netlisting a schematic top level with swapped-in layout subcells
if (pp != null && cell.isSchematic() && (subCni.getCell().getView() == View.LAYOUT))
{
// find equivalent pp from layout to schematic
Network subNet = subCS.getNetwork(); // layout network name
boolean found = false;
for (Iterator<Export> eIt = subCell.getExports(); eIt.hasNext(); )
{
Export ex = eIt.next();
for (int i=0; i<ex.getNameKey().busWidth(); i++)
{
String exName = ex.getNameKey().subname(i).toString();
if (exName.equals(subNet.getName()))
{
pp = ex;
exportIndex = i;
found = true;
break;
}
}
if (found) break;
}
if (!found)
{
if (pp.isGround() && pp.getName().startsWith("gnd")) {
infstr.append(" gnd");
} else if (pp.isPower() && pp.getName().startsWith("vdd")) {
infstr.append(" vdd");
} else {
System.out.println("No matching export on schematic/icon found for export "+
subNet.getName()+" in cell "+subCni.getCell().describe(false));
infstr.append(" unknown");
}
continue;
}
}
if (subCS.isGlobal())
{
net = netList.getNetwork(no, subCS.getGlobal());
}
else
net = netList.getNetwork(no, pp, exportIndex);
if (net == null)
{
System.out.println("Warning: cannot find network for signal " + subCS.getName() + " in cell " +
subCni.getCell().describe(false));
continue;
}
CellSignal cs = cni.getCellSignal(net);
// special case for parasitic extraction
SpiceSegmentedNets subSN = null;
if (parasiticInfo != null && !cs.isGlobal())
subSN = parasiticInfo.getSegmentedNets((Cell)no.getProto());
if (subSN != null)
{
parasiticInfo.getParasiticName(no, subCS.getNetwork(), subSN, infstr);
} else
{
String name = cs.getName();
if (parasiticInfo != null)
{
name = segmentedNets.getNetName(no.getNodeInst().findPortInstFromProto(pp));
}
infstr.append(" " + name);
}
}
if (useCDL) infstr.append(" /"); else infstr.append(" ");
infstr.append(subCni.getParameterizedName());
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this instance
Set<Variable.Key> spiceParams = detectSpiceParams(subCell);
for(Iterator<Variable> it = subCell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
if (DETECT_SPICE_PARAMS && !spiceParams.contains(paramVar.getKey())) continue;
if (!USE_JAVA_CODE && !isNetlistableParam(paramVar)) continue;
Variable instVar = no.getParameter(paramVar.getKey());
String paramStr = "??";
if (instVar != null)
{
if (USE_JAVA_CODE)
{
paramStr = evalParam(context, no, instVar, forceEval);
} else
{
Object obj = null;
if (isNetlistableParam(instVar))
{
obj = context.evalSpice(instVar, false);
} else
{
obj = context.evalVar(instVar, no);
}
if (obj != null)
paramStr = formatParam(String.valueOf(obj), instVar.getUnit(), false);
}
}
infstr.append(" " + paramVar.getTrueName() + "=" + paramStr);
}
}
// Writing MFactor if available.
writeMFactor(context, no, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
continue;
}
// get the type of this node
NodeInst ni = (NodeInst)no;
// look for a SPICE template on the primitive
String line = ((PrimitiveNode)ni.getProto()).getSpiceTemplate();
if (line != null)
{
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false, forceEval);
// Writing MFactor if available. Not sure here
writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
continue;
}
// handle resistors, inductors, capacitors, and diodes
PrimitiveNode.Function fun = ni.getFunction();
if (fun.isResistor() || fun.isCapacitor() ||
fun == PrimitiveNode.Function.INDUCT ||
fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
if (fun.isResistor())
{
if ((fun.isPolyOrWellResistor() && isShortExplicitResistors()) ||
(fun == PrimitiveNode.Function.RESIST && isShortResistors()))
continue;
Variable resistVar = ni.getVar(Schematics.SCHEM_RESISTANCE);
String extra = "";
String partName = "R";
if (resistVar != null)
{
if (USE_JAVA_CODE) {
extra = evalParam(context, ni, resistVar, forceEval);
} else {
if (resistVar.getCode() == CodeExpression.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(resistVar, false);
extra = String.valueOf(obj);
} else {
extra = resistVar.describe(context, ni);
}
}
if (extra == "")
extra = resistVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); //displayedUnits(pureValue, TextDescriptor.Unit.RESISTANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, resistVar.getUnit(), false);
}
} else {
// remove next 10 lines when PRESIST and WRESIST are finally deprecated
- if (fun == PrimitiveNode.Function.PRESIST)
- {
- if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) fun = PrimitiveNode.Function.RESPPOLY;
- if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) fun = PrimitiveNode.Function.RESNPOLY;
- }
- if (fun == PrimitiveNode.Function.WRESIST)
- {
- if (ni.getProto().getName().equals("P-Well-RPO-Resistor")) fun = PrimitiveNode.Function.RESPWELL;
- if (ni.getProto().getName().equals("N-Well-RPO-Resistor")) fun = PrimitiveNode.Function.RESNWELL;
- }
+// if (fun == PrimitiveNode.Function.PRESIST)
+// {
+// if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) fun = PrimitiveNode.Function.RESPPOLY;
+// if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) fun = PrimitiveNode.Function.RESNPOLY;
+// }
+// if (fun == PrimitiveNode.Function.WRESIST)
+// {
+// if (ni.getProto().getName().equals("P-Well-RPO-Resistor")) fun = PrimitiveNode.Function.RESPWELL;
+// if (ni.getProto().getName().equals("N-Well-RPO-Resistor")) fun = PrimitiveNode.Function.RESNWELL;
+// }
if (fun == PrimitiveNode.Function.RESPPOLY || fun == PrimitiveNode.Function.RESNPOLY ||
fun == PrimitiveNode.Function.RESPWELL || fun == PrimitiveNode.Function.RESNWELL)
{
partName = "XR";
double width = ni.getLambdaBaseYSize();
double length = ni.getLambdaBaseXSize();
if (Simulation.isSpiceWriteTransSizeInLambda())
{
extra = " L="+length+" W="+width;
} else
{
extra = " L="+formatParam(length+"*LAMBDA", TextDescriptor.Unit.NONE, false)+
" W="+formatParam(width+"*LAMBDA", TextDescriptor.Unit.NONE, false);
}
String prepend = "";
if (fun == PrimitiveNode.Function.RESPPOLY) prepend = "rppo1rpo"; else
if (fun == PrimitiveNode.Function.RESNPOLY) prepend = "rnpo1rpo"; else
if (fun == PrimitiveNode.Function.RESPWELL) prepend = "rpwod "; else
if (fun == PrimitiveNode.Function.RESNWELL) prepend = "rnwod ";
if (layoutTechnology == Technology.getCMOS90Technology() ||
(cell.getView() == View.LAYOUT && cell.getTechnology() == Technology.getCMOS90Technology()))
{
if (fun == PrimitiveNode.Function.RESPPOLY) prepend = "GND rpporpo"; else
if (fun == PrimitiveNode.Function.RESNPOLY) prepend = "GND rnporpo";
}
extra = prepend + extra;
}
}
writeTwoPort(ni, partName, extra, cni, netList, context, segmentedNets);
} else if (fun.isCapacitor())
{
Variable capacVar = ni.getVar(Schematics.SCHEM_CAPACITANCE);
String extra = "";
if (capacVar != null)
{
if (USE_JAVA_CODE) {
extra = evalParam(context, no, capacVar, forceEval);
} else {
if (capacVar.getCode() == CodeExpression.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(capacVar, false);
extra = String.valueOf(obj);
} else {
extra = capacVar.describe(context, ni);
}
}
if (extra == "")
extra = capacVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.CAPACITANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, capacVar.getUnit(), false);
}
}
writeTwoPort(ni, "C", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.INDUCT)
{
Variable inductVar = ni.getVar(Schematics.SCHEM_INDUCTANCE);
String extra = "";
if (inductVar != null)
{
if (USE_JAVA_CODE) {
extra = evalParam(context, no, inductVar, forceEval);
} else {
if (inductVar.getCode() == CodeExpression.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(inductVar, false);
extra = String.valueOf(obj);
} else {
extra = inductVar.describe(context, ni);
}
}
if (extra == "")
extra = inductVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.INDUCTANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, inductVar.getUnit(), false);
}
}
writeTwoPort(ni, "L", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
Variable diodeVar = ni.getVar(Schematics.SCHEM_DIODE);
String extra = "";
if (diodeVar != null)
extra = diodeVar.describe(context, ni);
if (extra.length() == 0) extra = "DIODE";
writeTwoPort(ni, "D", extra, cni, netList, context, segmentedNets);
}
continue;
}
// the default is to handle everything else as a transistor
if (((PrimitiveNode)niProto).getGroupFunction() != PrimitiveNode.Function.TRANS)
continue;
Network gateNet = netList.getNetwork(ni.getTransistorGatePort());
CellSignal gateCs = cni.getCellSignal(gateNet);
Network sourceNet = netList.getNetwork(ni.getTransistorSourcePort());
CellSignal sourceCs = cni.getCellSignal(sourceNet);
Network drainNet = netList.getNetwork(ni.getTransistorDrainPort());
CellSignal drainCs = cni.getCellSignal(drainNet);
CellSignal biasCs = null;
PortInst biasPort = ni.getTransistorBiasPort();
if (biasPort != null)
{
biasCs = cni.getCellSignal(netList.getNetwork(biasPort));
}
// make sure transistor is connected to nets
if (gateCs == null || sourceCs == null || drainCs == null)
{
String message = "WARNING: " + ni + " not fully connected in " + cell;
dumpErrorMessage(message);
}
// get model information
String modelName = null;
String defaultBulkName = null;
Variable modelVar = ni.getVar(SPICE_MODEL_KEY);
if (modelVar != null) modelName = modelVar.getObject().toString();
// special case for ST090 technology which has stupid non-standard transistor
// models which are subcircuits
boolean st090laytrans = false;
boolean tsmc090laytrans = false;
if (cell.getView() == View.LAYOUT && layoutTechnology == Technology.getCMOS90Technology()) {
if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.TSMC)
tsmc090laytrans = true;
else if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.ST)
st090laytrans = true;
}
String modelChar = "";
if (fun == PrimitiveNode.Function.TRANSREF) // self-referential transistor
{
modelChar = "X";
biasCs = cni.getCellSignal(groundNet);
modelName = niProto.getName();
} else if (fun == PrimitiveNode.Function.TRANMOS) // NMOS (Enhancement) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
defaultBulkName = "gnd";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRA4NMOS) // NMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRADMOS) // DMOS (Depletion) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRA4DMOS) // DMOS (Depletion) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRAPMOS) // PMOS (Complementary) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(powerNet);
defaultBulkName = "vdd";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRA4PMOS) // PMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRANPN) // NPN (Junction) transistor
{
modelChar = "Q";
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRA4NPN) // NPN (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRAPNP) // PNP (Junction) transistor
{
modelChar = "Q";
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRA4PNP) // PNP (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRANJFET) // NJFET (N Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRA4NJFET) // NJFET (N Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRAPJFET) // PJFET (P Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRA4PJFET) // PJFET (P Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRADMES || // DMES (Depletion) transistor
fun == PrimitiveNode.Function.TRA4DMES) // DMES (Depletion) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "DMES";
} else if (fun == PrimitiveNode.Function.TRAEMES || // EMES (Enhancement) transistor
fun == PrimitiveNode.Function.TRA4EMES) // EMES (Enhancement) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "EMES";
} else if (fun == PrimitiveNode.Function.TRANS) // special transistor
{
modelChar = "Q";
}
if (ni.getName() != null) modelChar += getSafeNetName(ni.getName(), false);
StringBuffer infstr = new StringBuffer();
String drainName = drainCs.getName();
String gateName = gateCs.getName();
String sourceName = sourceCs.getName();
if (segmentedNets != null) {
drainName = segmentedNets.getNetName(ni.getTransistorDrainPort());
gateName = segmentedNets.getNetName(ni.getTransistorGatePort());
sourceName = segmentedNets.getNetName(ni.getTransistorSourcePort());
}
infstr.append(modelChar + " " + drainName + " " + gateName + " " + sourceName);
if (biasCs != null) {
String biasName = biasCs.getName();
if (segmentedNets != null && ni.getTransistorBiasPort() != null)
biasName = segmentedNets.getNetName(ni.getTransistorBiasPort());
infstr.append(" " + biasName);
} else {
if (cell.getView() == View.LAYOUT && defaultBulkName != null)
infstr.append(" " + defaultBulkName);
}
if (modelName != null) infstr.append(" " + modelName);
// compute length and width (or area for nonMOS transistors)
TransistorSize size = ni.getTransistorSize(context);
if (size == null)
System.out.println("Warning: transistor with null size " + ni.getName());
else
{
if (size.getDoubleWidth() > 0 || size.getDoubleLength() > 0)
{
double w = maskScale * size.getDoubleWidth();
double l = maskScale * size.getDoubleLength();
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
l -= lengthSubtraction;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
// make into microns (convert to nanometers then divide by 1000)
l *= layoutTechnology.getScale() / 1000.0;
w *= layoutTechnology.getScale() / 1000.0;
}
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS ||
((fun == PrimitiveNode.Function.TRANJFET || fun == PrimitiveNode.Function.TRAPJFET ||
fun == PrimitiveNode.Function.TRADMES || fun == PrimitiveNode.Function.TRAEMES) &&
(spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_ASSURA)))
{
// schematic transistors may be text
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE, false) + " - "+ lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE, false));
} else {
infstr.append(" L=" + TextUtils.formatDouble(l));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String)) {
infstr.append(" W="+formatParam((String)size.getWidth(), TextDescriptor.Unit.DISTANCE, false));
} else {
infstr.append(" W=" + TextUtils.formatDouble(w));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
if (fun != PrimitiveNode.Function.TRANMOS && fun != PrimitiveNode.Function.TRA4NMOS &&
fun != PrimitiveNode.Function.TRAPMOS && fun != PrimitiveNode.Function.TRA4PMOS &&
fun != PrimitiveNode.Function.TRADMOS && fun != PrimitiveNode.Function.TRA4DMOS)
{
infstr.append(" AREA=" + TextUtils.formatDouble(l*w));
if (!Simulation.isSpiceWriteTransSizeInLambda()) infstr.append("P");
}
} else {
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE, false) + " - "+lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE, false));
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String))
infstr.append(" W="+formatParam((String)size.getWidth(), TextDescriptor.Unit.DISTANCE, false));
}
}
// make sure transistor is connected to nets
SpiceNet spNetGate = spiceNetMap.get(gateNet);
SpiceNet spNetSource = spiceNetMap.get(sourceNet);
SpiceNet spNetDrain = spiceNetMap.get(drainNet);
if (spNetGate == null || spNetSource == null || spNetDrain == null) continue;
// compute area of source and drain
if (!useCDL)
{
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS)
{
double as = 0, ad = 0, ps = 0, pd = 0;
if (spNetSource.transistorCount != 0)
{
as = spNetSource.diffArea / spNetSource.transistorCount;
ps = spNetSource.diffPerim / spNetSource.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
as *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
ps *= layoutTechnology.getScale() / 1000.0;
}
}
if (spNetDrain.transistorCount != 0)
{
ad = spNetDrain.diffArea / spNetDrain.transistorCount;
pd = spNetDrain.diffPerim / spNetDrain.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
ad *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
pd *= layoutTechnology.getScale() / 1000.0;
}
}
if (as > 0.0)
{
infstr.append(" AS=" + TextUtils.formatDouble(as));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ad > 0.0)
{
infstr.append(" AD=" + TextUtils.formatDouble(ad));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ps > 0.0)
{
infstr.append(" PS=" + TextUtils.formatDouble(ps));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if (pd > 0.0)
{
infstr.append(" PD=" + TextUtils.formatDouble(pd));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
}
// Writing MFactor if available.
writeMFactor(context, ni, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
// print resistances and capacitances
if (segmentedNets != null)
{
if (spLevel == Simulation.SpiceParasitics.RC_PROXIMITY)
{
parasiticInfo.writeNewSpiceCode(cell, cni, layoutTechnology, this);
} else {
// write caps
int capCount = 0;
multiLinePrint(true, "** Extracted Parasitic Capacitors ***\n");
for (SpiceSegmentedNets.NetInfo netInfo : segmentedNets.getUniqueSegments()) {
if (netInfo.getCap() > cell.getTechnology().getMinCapacitance()) {
if (netInfo.getName().equals("gnd")) continue; // don't write out caps from gnd to gnd
multiLinePrint(false, "C" + capCount + " " + netInfo.getName() + " 0 " + TextUtils.formatDouble(netInfo.getCap()) + "fF\n");
capCount++;
}
}
// write resistors
int resCount = 0;
multiLinePrint(true, "** Extracted Parasitic Resistors ***\n");
for (Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); ) {
ArcInst ai = it.next();
Double res = segmentedNets.getRes(ai);
if (res == null) continue;
String n0 = segmentedNets.getNetName(ai.getHeadPortInst());
String n1 = segmentedNets.getNetName(ai.getTailPortInst());
int arcPImodels = SpiceSegmentedNets.getNumPISegments(res.doubleValue(), layoutTechnology.getMaxSeriesResistance());
if (arcPImodels > 1) {
// have to break it up into smaller pieces
double segCap = segmentedNets.getArcCap(ai)/(arcPImodels+1);
double segRes = res.doubleValue()/arcPImodels;
String segn0 = n0;
String segn1 = n0;
for (int i=0; i<arcPImodels; i++) {
segn1 = n0 + "##" + i;
// print cap on intermediate node
if (i == (arcPImodels-1))
segn1 = n1;
multiLinePrint(false, "R"+resCount+" "+segn0+" "+segn1+" "+TextUtils.formatDouble(segRes)+"\n");
resCount++;
if (i < (arcPImodels-1)) {
if (!segn1.equals("gnd") && segCap > layoutTechnology.getMinCapacitance()) {
String capVal = TextUtils.formatDouble(segCap);
if (!capVal.equals("0.00")) {
multiLinePrint(false, "C"+capCount+" "+segn1+" 0 "+capVal+"fF\n");
capCount++;
}
}
}
segn0 = segn1;
}
} else {
multiLinePrint(false, "R" + resCount + " " + n0 + " " + n1 + " " + TextUtils.formatDouble(res.doubleValue()) + "\n");
resCount++;
}
}
}
}
// write out any directly-typed SPICE cards
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech().invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_CARD_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Code nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false, forceEval);
}
}
// finally, if this is the top level,
// write out some very small resistors between any networks
// that are asserted will be connected by the NCC annotation "exportsConnectedByParent"
// this should really be done internally in the network tool with a switch, but
// this hack works here for now
NccCellAnnotations anna = NccCellAnnotations.getAnnotations(cell);
if (cell == topCell && anna != null) {
// each list contains all name patterns that are be shorted together
if (anna.getExportsConnected().hasNext()) {
multiLinePrint(true, "\n*** Exports shorted due to NCC annotation 'exportsConnectedByParent':\n");
}
for (Iterator<List<NamePattern>> it = anna.getExportsConnected(); it.hasNext(); ) {
List<NamePattern> list = it.next();
List<Network> netsToConnect = new ArrayList<Network>();
// each name pattern can match any number of exports in the cell
for (NccCellAnnotations.NamePattern pat : list) {
for (Iterator<PortProto> it3 = cell.getPorts(); it3.hasNext(); ) {
Export e = (Export)it3.next();
String name = e.getName();
// keep track of networks to short together
if (pat.matches(name)) {
Network net = netList.getNetwork(e, 0);
if (!netsToConnect.contains(net))
netsToConnect.add(net);
}
}
}
// connect all nets in list of nets to connect
String name = null;
for (Network net : netsToConnect) {
if (name != null) {
multiLinePrint(false, "R"+name+" "+name+" "+net.getName()+" 0.001\n");
}
name = net.getName();
}
}
}
// now we're finished writing the subcircuit.
if (cell != topCell || useCDL || Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(false, ".ENDS " + cni.getParameterizedName() + "\n");
}
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
multiLinePrint(false, "\n\n"+topLevelInstance+"\n\n");
}
}
/****************************** PARAMETERS ******************************/
/**
* Method to create a parameterized name for node instance "ni".
* If the node is not parameterized, returns zero.
* If it returns a name, that name must be deallocated when done.
*/
protected String parameterizedName(Nodable no, VarContext context)
{
Cell cell = (Cell)no.getProto();
StringBuffer uniqueCellName = new StringBuffer(getUniqueCellName(cell));
if (uniquifyCells.get(cell) != null && modelOverrides.get(cell) == null) {
// if this cell is marked to be make unique, make a unique name out of the var context
VarContext vc = context.push(no);
uniqueCellName.append("_"+vc.getInstPath("."));
} else {
boolean useCellParams = !useCDL && Simulation.isSpiceUseCellParameters();
if (canParameterizeNames() && no.isCellInstance() && !SCLibraryGen.isStandardCell(cell))
{
// if there are parameters, append them to this name
Set<Variable.Key> spiceParams = detectSpiceParams(cell);
List<Variable> paramValues = new ArrayList<Variable>();
for(Iterator<Variable> it = no.getDefinedParameters(); it.hasNext(); )
{
Variable var = it.next();
if (DETECT_SPICE_PARAMS && !spiceParams.contains(var.getKey())) continue;
if (USE_JAVA_CODE) {
if (useCellParams && !spiceParams.contains(null)) continue;
} else {
if (useCellParams && !var.isJava()) continue;
}
paramValues.add(var);
}
for(Variable var : paramValues)
{
String eval = var.describe(context, no);
//Object eval = context.evalVar(var, no);
if (eval == null) continue;
//uniqueCellName += "-" + var.getTrueName() + "-" + eval.toString();
uniqueCellName.append("-" + eval.toString());
}
}
}
// if it is over the length limit, truncate it
int limit = maxNameLength();
if (limit > 0 && uniqueCellName.length() > limit)
{
Integer i = uniqueNames.get(uniqueCellName.toString());
if (i == null) {
i = new Integer(uniqueID);
uniqueID++;
uniqueNames.put(uniqueCellName.toString(), i);
}
uniqueCellName = uniqueCellName.delete(limit-10, uniqueCellName.length());
uniqueCellName.append("-ID"+i);
}
// make it safe
return getSafeCellName(uniqueCellName.toString());
}
/**
* Returns true if variable can be netlisted as a spice parameter (unevaluated expression).
* If not, it should be evaluated before netlisting.
* @param var the var to check
* @return true if the variable should be netlisted as a spice parameter
*/
private boolean isNetlistableParam(Variable var)
{
if (USE_JAVA_CODE)
{
CodeExpression ce = var.getCodeExpression();
if (ce == null) return true;
if (ce.getHSpiceText(false) != null) return true;
return false;
}
if (var.isJava()) return false;
return true;
}
/**
* Returns text representation of instance parameter
* on specified Nodable in specified VarContext
* The text representation can be either spice parameter expression or
* a value evaluated in specified VarContext
* @param context specified VarContext
* @param no specified Nodable
* @param instParam instance parameter
* @param forceEval true to always evaluate param
* @return true if the variable should be netlisted as a spice parameter
*/
private String evalParam(VarContext context, Nodable no, Variable instParam, boolean forceEval)
{
return evalParam(context, no, instParam, forceEval, false, false);
}
/**
* Returns text representation of instance parameter
* on specified Nodable in specified VarContext
* The text representation can be either spice parameter expression or
* a value evaluated in specified VarContext
* @param context specified VarContext
* @param no specified Nodable
* @param instParam instance parameter
* @param forceEval true to always evaluate param
* @param wrapped true if the string is already "wrapped" (with parenthesis) and does not need to have quotes around it.
* @return true if the variable should be netlisted as a spice parameter
*/
private String evalParam(VarContext context, Nodable no, Variable instParam, boolean forceEval, boolean inPars, boolean wrapped) {
assert USE_JAVA_CODE;
Object obj = null;
if (!forceEval) {
CodeExpression ce = instParam.getCodeExpression();
if (ce != null)
obj = ce.getHSpiceText(inPars);
}
if (obj == null)
obj = context.evalVar(instParam, no);
if (obj instanceof Number)
obj = TextUtils.formatDoublePostFix(((Number)obj).doubleValue());
return formatParam(String.valueOf(obj), instParam.getUnit(), wrapped);
}
private Set<Variable.Key> detectSpiceParams(NodeProto np)
{
Set<Variable.Key> params = allSpiceParams.get(np);
if (params != null) return params;
if (np instanceof PrimitiveNode) {
params = getImportantVars((PrimitiveNode)np);
// if (!params.isEmpty())
// printlnParams(pn + " depends on:", params);
} else {
Cell cell = (Cell)np;
params = getTemplateVars(cell);
if (params == null) {
if (cell.isIcon() && cell.contentsView() != null) {
Cell schCell = cell.contentsView();
params = detectSpiceParams(schCell);
// printlnParams(cell + " inherits from " + schCell, params);
} else {
params = new HashSet<Variable.Key>();
boolean uniquify = false;
for (Iterator<NodeInst> nit = cell.getNodes(); nit.hasNext();) {
NodeInst ni = nit.next();
if (ni.isIconOfParent()) continue;
Set<Variable.Key> protoParams = detectSpiceParams(ni.getProto());
if (protoParams == UNIQUIFY_MARK)
uniquify = true;
for (Variable.Key protoParam: protoParams) {
Variable var = ni.getParameterOrVariable(protoParam);
if (var == null) continue;
CodeExpression ce = var.getCodeExpression();
if (ce == null) continue;
if (!isNetlistableParam(var)) uniquify = true;
Set<Variable.Key> depends = ce.dependsOn();
params.addAll(depends);
// if (!depends.isEmpty())
// printlnParams("\t" + ni + " added", depends);
}
if (ni.getProto() == Generic.tech().invisiblePinNode) {
findVarsInTemplate(ni.getVar(Spice.SPICE_DECLARATION_KEY), cell, false, params);
findVarsInTemplate(ni.getVar(Spice.SPICE_CARD_KEY), cell, false, params);
}
}
if (uniquify/* && USE_UNIQUIFY_MARK*/)
params = UNIQUIFY_MARK;
// printlnParams(cell + " collected params", params);
}
}
}
allSpiceParams.put(np, params);
return params;
}
// private static void printlnParams(String message, Set<Variable.Key> varKeys) {
// System.out.print(message);
// for (Variable.Key varKey: varKeys)
// System.out.print(" " + varKey);
// System.out.println();
// }
/**
* Method to tell which Variables are important for primitive node in this netlister
* @param pn primitive node to tell
* @return a set of important variables or null if all variables may be important
*/
protected Set<Variable.Key> getImportantVars(PrimitiveNode pn)
{
Set<Variable.Key> importantVars = new HashSet<Variable.Key>();
// look for a SPICE template on the primitive
String line = pn.getSpiceTemplate();
if (line != null) {
findVarsInLine(line, pn, true, importantVars);
// Writing MFactor if available. Not sure here
// No, this causes problems because "ATTR_M" does not actually exist on proto
//importantVars.add(Simulation.M_FACTOR_KEY);
return importantVars;
}
// handle resistors, inductors, capacitors, and diodes
PrimitiveNode.Function fun = pn.getFunction();
if (fun.isResistor()) {
importantVars.add(Schematics.SCHEM_RESISTANCE);
} else if (fun.isCapacitor()) {
importantVars.add(Schematics.SCHEM_CAPACITANCE);
} else if (fun == PrimitiveNode.Function.INDUCT) {
importantVars.add(Schematics.SCHEM_INDUCTANCE);
} else if (fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ) {
importantVars.add(Schematics.SCHEM_DIODE);
} else if (pn.getGroupFunction() == PrimitiveNode.Function.TRANS) {
// model information
importantVars.add(SPICE_MODEL_KEY);
// compute length and width (or area for nonMOS transistors)
if (pn.getTechnology() instanceof Schematics) {
importantVars.add(Schematics.ATTR_LENGTH);
importantVars.add(Schematics.ATTR_WIDTH);
importantVars.add(Schematics.ATTR_AREA);
} else {
importantVars.add(NodeInst.TRACE);
}
importantVars.add(Simulation.M_FACTOR_KEY);
} else if (pn == Generic.tech().invisiblePinNode) {
importantVars.add(Spice.SPICE_DECLARATION_KEY);
importantVars.add(Spice.SPICE_CARD_KEY);
}
return importantVars;
}
/****************************** TEMPLATE WRITING ******************************/
private void emitEmbeddedSpice(Variable cardVar, VarContext context, SpiceSegmentedNets segNets, HierarchyEnumerator.CellInfo info, boolean flatNetNames, boolean forceEval)
{
Object obj = cardVar.getObject();
if (!(obj instanceof String) && !(obj instanceof String[])) return;
if (!cardVar.isDisplay()) return;
if (obj instanceof String)
{
StringBuffer buf = replacePortsAndVars((String)obj, context.getNodable(), context.pop(), null, segNets, info, flatNetNames, forceEval);
buf.append('\n');
String msg = buf.toString();
boolean isComment = false;
if (msg.startsWith("*")) isComment = true;
multiLinePrint(isComment, msg);
} else
{
String [] strings = (String [])obj;
for(int i=0; i<strings.length; i++)
{
StringBuffer buf = replacePortsAndVars(strings[i], context.getNodable(), context.pop(), null, segNets, info, flatNetNames, forceEval);
buf.append('\n');
String msg = buf.toString();
boolean isComment = false;
if (msg.startsWith("*")) isComment = true;
multiLinePrint(isComment, msg);
}
}
}
/**
* Method to determine which Spice engine is being targeted and to get the proper
* template variable.
* Looks in associated icon/schematics cells to find it.
* @param cell the Cell being netlisted.
* @return a Variable with the proper Spice template (null if none).
*/
private Variable getEngineTemplate(Cell cell)
{
Variable varTemplate = getEngineTemplateJustThis(cell);
// try associated icon/schematic if no template found
if (varTemplate == null)
{
if (cell.isIcon())
{
Cell schCell = cell.contentsView();
if (schCell != null)
varTemplate = getEngineTemplateJustThis(schCell);
} else
{
Cell iconCell = cell.iconView();
if (iconCell != null)
varTemplate = getEngineTemplateJustThis(iconCell);
}
}
return varTemplate;
}
/**
* Method to determine which Spice engine is being targeted and to get the proper
* template variable.
* @param cell the Cell being netlisted.
* @return a Variable with the proper Spice template (null if none).
*/
private Variable getEngineTemplateJustThis(Cell cell)
{
Variable varTemplate = cell.getVar(preferedEngineTemplateKey);
// If not looking for the default spice templates, and special one is not found, try default
if (varTemplate == null && preferedEngineTemplateKey != SPICE_TEMPLATE_KEY)
varTemplate = cell.getVar(SPICE_TEMPLATE_KEY);
return varTemplate;
}
private Set<Variable.Key> getTemplateVars(Cell cell)
{
Variable varTemplate = getEngineTemplate(cell);
if (varTemplate == null) return null;
Set<Variable.Key> depends = new HashSet<Variable.Key>();
findVarsInTemplate(varTemplate, cell, true, depends);
//depends.add(Simulation.M_FACTOR_KEY);
return depends;
}
private void findVarsInTemplate(Variable varTemplate, NodeProto cell, boolean isPortReplacement, Set<Variable.Key> vars)
{
if (varTemplate == null) return;
Object value = varTemplate.getObject();
if (value instanceof Object[])
{
for (Object o : ((Object[]) value))
{
findVarsInLine(o.toString(), cell, isPortReplacement, vars);
}
} else
{
findVarsInLine(value.toString(), cell, isPortReplacement, vars);
}
}
/**
* Replace ports and vars in 'line'. Ports and Vars should be
* referenced via $(name)
* @param line the string to search and replace within
* @param no the nodable up the hierarchy that has the parameters on it
* @param context the context of the nodable
* @param cni the cell net info of cell in which the nodable exists (if cni is
* null, no port name replacement will be done)
* @param segNets
* @param info
* @param flatNetNames
* @param forceEval alsways evaluate parameters to numbers
* @return the modified line
*/
private StringBuffer replacePortsAndVars(String line, Nodable no, VarContext context,
CellNetInfo cni, SpiceSegmentedNets segNets,
HierarchyEnumerator.CellInfo info, boolean flatNetNames, boolean forceEval) {
StringBufferQuoteParity infstr = new StringBufferQuoteParity();
NodeProto prototype = null;
PrimitiveNode prim = null;
if (no != null)
{
prototype = no.getProto();
if (prototype instanceof PrimitiveNode) prim = (PrimitiveNode)prototype;
}
for(int pt = 0; pt < line.length(); pt++)
{
// see if the character is part of a substitution expression
char chr = line.charAt(pt);
if (chr != '$' || pt+1 >= line.length() || line.charAt(pt+1) != '(')
{
// not part of substitution: just emit it
infstr.append(chr);
continue;
}
// may be part of substitution expression: look for closing parenthesis
int start = pt + 2;
for(pt = start; pt < line.length(); pt++)
if (line.charAt(pt) == ')') break;
// do the parameter substitution
String paramName = line.substring(start, pt);
PortProto pp = null;
int ppIndex = -1;
if (prototype != null)
{
if (prototype instanceof Cell)
{
Cell subCell = (Cell)prototype;
Netlist nl = subCell.getNetlist();
for(Iterator<Export> it = subCell.getExports(); it.hasNext(); )
{
Export e = it.next();
int width = nl.getBusWidth(e);
for(int i=0; i<width; i++)
{
Network net = nl.getNetwork(e, i);
for(Iterator<String> nIt = net.getNames(); nIt.hasNext(); )
{
String netName = nIt.next();
if (netName.equals(paramName))
{
pp = e;
ppIndex = i;
break;
}
}
if (ppIndex >= 0) break;
}
if (ppIndex >= 0) break;
}
} else
{
pp = prototype.findPortProto(paramName);
}
}
Variable.Key varKey;
if (paramName.equalsIgnoreCase("node_name") && no != null)
{
String nodeName = getSafeNetName(no.getName(), false);
// nodeName = nodeName.replaceAll("[\\[\\]]", "_");
infstr.append(nodeName);
} else if (paramName.equalsIgnoreCase("width") && prim != null)
{
NodeInst ni = (NodeInst)no;
PrimitiveNodeSize npSize = ni.getPrimitiveDependentNodeSize(context);
if (npSize != null) infstr.append(npSize.getWidth().toString());
} else if (paramName.equalsIgnoreCase("length") && prim != null)
{
NodeInst ni = (NodeInst)no;
PrimitiveNodeSize npSize = ni.getPrimitiveDependentNodeSize(context);
if (npSize != null) infstr.append(npSize.getLength().toString());
} else if (cni != null && pp != null)
{
// port name found: use its spice node
if (ppIndex < 0) ppIndex = 0;
Network net = cni.getNetList().getNetwork(no, pp, ppIndex);
CellSignal cs = cni.getCellSignal(net);
String portName = cs.getName();
if (segNets != null) {
PortInst pi = no.getNodeInst().findPortInstFromProto(pp);
portName = segNets.getNetName(pi);
}
if (flatNetNames) {
portName = info.getUniqueNetName(net, ".");
}
infstr.append(portName);
} else if (no != null && (varKey = Variable.findKey("ATTR_" + paramName)) != null)
{
// no port name found, look for variable name
Variable attrVar = null;
//Variable.Key varKey = Variable.findKey("ATTR_" + paramName);
if (varKey != null) {
attrVar = no.getParameterOrVariable(varKey);
}
if (attrVar == null) infstr.append("??"); else
{
String pVal = "?";
Variable parentVar = attrVar;
if (prototype != null && prototype instanceof Cell)
parentVar = ((Cell)prototype).getParameterOrVariable(attrVar.getKey());
if (USE_JAVA_CODE) {
pVal = evalParam(context, no, attrVar, forceEval, true, infstr.inParens());
if (infstr.inQuotes()) pVal = trimSingleQuotes(pVal);
} else {
if (!useCDL && Simulation.isSpiceUseCellParameters() &&
parentVar.getCode() == CodeExpression.Code.SPICE) {
Object obj = context.evalSpice(attrVar, false);
if (obj != null)
pVal = obj.toString();
} else {
pVal = String.valueOf(context.evalVar(attrVar, no));
}
// if (attrVar.getCode() != TextDescriptor.Code.NONE)
if (infstr.inQuotes()) pVal = trimSingleQuotes(pVal); else
pVal = formatParam(pVal, attrVar.getUnit(), infstr.inParens());
}
infstr.append(pVal);
}
} else {
// look for the network name
boolean found = false;
String hierName = null;
String [] names = paramName.split("\\.");
if (names.length > 1 && flatNetNames) {
// hierarchical name, down hierarchy
Netlist thisNetlist = info.getNetlist();
VarContext thisContext = context;
if (no != null) {
// push it back on, it got popped off in "embedSpice..."
thisContext = thisContext.push(no);
}
for (int i=0; i<names.length-1; i++) {
boolean foundno = false;
for (Iterator<Nodable> it = thisNetlist.getNodables(); it.hasNext(); ) {
Nodable subno = it.next();
if (subno.getName().equals(names[i])) {
if (subno.getProto() instanceof Cell) {
thisNetlist = thisNetlist.getNetlist(subno);
thisContext = thisContext.push(subno);
}
foundno = true;
continue;
}
}
if (!foundno) {
System.out.println("Unable to find "+names[i]+" in "+paramName);
break;
}
}
Network net = findNet(thisNetlist, names[names.length-1]);
if (net != null) {
HierarchyEnumerator.NetNameProxy proxy = new HierarchyEnumerator.NetNameProxy(
thisContext, ".x", net);
Global g = getGlobal(proxy.getNet());
if (g != null)
hierName = g.getName();
else
hierName = proxy.toString();
}
} else {
// net may be exported and named at higher level, use getUniqueName
Network net = findNet(info.getNetlist(), paramName);
if (net != null) {
if (flatNetNames) {
HierarchyEnumerator.NetNameProxy proxy = info.getUniqueNetNameProxy(net, ".x");
Global g = getGlobal(proxy.getNet());
if (g != null)
hierName = g.getName();
else
hierName = proxy.toString();
} else {
hierName = cni.getCellSignal(net).getName();
}
}
}
// convert to spice format
if (hierName != null) {
if (flatNetNames) {
if (hierName.indexOf(".x") > 0) {
hierName = "x"+hierName;
}
// remove x in front of net name
int i = hierName.lastIndexOf(".x");
if (i > 0)
hierName = hierName.substring(0, i+1) + hierName.substring(i+2);
else {
i = hierName.lastIndexOf("."+paramName);
if (i > 0) {
hierName = hierName.substring(0, i) + "_" + hierName.substring(i+1);
}
}
}
infstr.append(hierName);
found = true;
}
if (!found) {
System.out.println("Cannot find parameter $("+paramName+") in cell "+
(prototype != null ? prototype.describe(false) : context.getInstPath(".")));
}
}
}
return infstr.getStringBuffer();
}
private static class StringBufferQuoteParity
{
private StringBuffer sb = new StringBuffer();
private int quoteCount;
private int parenDepth;
void append(String str)
{
sb.append(str);
for(int i=0; i<str.length(); i++)
{
char ch = str.charAt(i);
if (ch == '\'') quoteCount++; else
if (ch == '(') parenDepth++; else
if (ch == ')') parenDepth--;
}
}
void append(char c)
{
sb.append(c);
if (c == '\'') quoteCount++; else
if (c == '(') parenDepth++; else
if (c == ')') parenDepth--;
}
boolean inQuotes() { return (quoteCount&1) != 0; }
boolean inParens() { return parenDepth > 0; }
StringBuffer getStringBuffer() { return sb; }
}
/**
* Find vars in 'line'. Ports and Vars should be referenced via $(name)
* @param line the string to search and replace within
* @param prototype of instance that has the parameters on it
* @param isPortReplacement true if port name replacement will be done)
* @parm
*/
private void findVarsInLine(String line, NodeProto prototype, boolean isPortReplacement, Set<Variable.Key> vars) {
PrimitiveNode prim = null;
if (prototype != null) {
if (prototype instanceof PrimitiveNode) prim = (PrimitiveNode)prototype;
}
for(int pt = 0; pt < line.length(); pt++) {
// see if the character is part of a substitution expression
char chr = line.charAt(pt);
if (chr != '$' || pt+1 >= line.length() || line.charAt(pt+1) != '(') {
// not part of substitution: just emit it
continue;
}
// may be part of substitution expression: look for closing parenthesis
int start = pt + 2;
for(pt = start; pt < line.length(); pt++)
if (line.charAt(pt) == ')') break;
// do the parameter substitution
String paramName = line.substring(start, pt);
PortProto pp = null;
if (prototype != null) {
pp = prototype.findPortProto(paramName);
}
Variable.Key varKey;
if (paramName.equalsIgnoreCase("node_name") && prototype != null) continue;
if (paramName.equalsIgnoreCase("width") && prim != null) continue;
if (paramName.equalsIgnoreCase("length") && prim != null) continue;
if (isPortReplacement && pp != null) continue;
if (prototype != null && (varKey = Variable.findKey("ATTR_" + paramName)) != null) {
if (prototype instanceof PrimitiveNode || ((Cell) prototype).getParameterOrVariable(varKey) != null)
vars.add(varKey);
}
}
}
private Network findNet(Netlist netlist, String netName)
{
Network foundnet = null;
for (Iterator<Network> it = netlist.getNetworks(); it.hasNext(); ) {
Network net = it.next();
if (net.hasName(netName)) {
foundnet = net;
break;
}
}
return foundnet;
}
/**
* Get the global associated with this net. Returns null if net is
* not a global.
* @param net
* @return global associated with this net, or null if not global
*/
private Global getGlobal(Network net)
{
Netlist netlist = net.getNetlist();
for (int i=0; i<netlist.getGlobals().size(); i++) {
Global g = netlist.getGlobals().get(i);
if (netlist.getNetwork(g) == net)
return g;
}
return null;
}
/****************************** SUBCLASSED METHODS FOR THE TOPOLOGY ANALYZER ******************************/
/**
* Method to adjust a cell name to be safe for Spice output.
* @param name the cell name.
* @return the name, adjusted for Spice output.
*/
protected String getSafeCellName(String name)
{
return getSafeNetName(name, false);
}
/** Method to return the proper name of Power */
protected String getPowerName(Network net)
{
if (net != null)
{
// favor "vdd" if it is present
for(Iterator<String> it = net.getNames(); it.hasNext(); )
{
String netName = it.next();
if (netName.equalsIgnoreCase("vdd")) return "vdd";
}
}
return null;
}
/** Method to return the proper name of Ground */
protected String getGroundName(Network net)
{
if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_2 ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_P ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_G) return "0";
if (net != null)
{
// favor "gnd" if it is present
for(Iterator<String> it = net.getNames(); it.hasNext(); )
{
String netName = it.next();
if (netName.equalsIgnoreCase("gnd")) return "gnd";
}
}
return null;
}
/** Method to return the proper name of a Global signal */
protected String getGlobalName(Global glob) { return glob.getName(); }
/** Method to report that export names do NOT take precedence over
* arc names when determining the name of the network. */
protected boolean isNetworksUseExportedNames() { return false; }
/** Method to report that library names are NOT always prepended to cell names. */
protected boolean isLibraryNameAlwaysAddedToCellName() { return false; }
/** Method to report that aggregate names (busses) are not used. */
protected boolean isAggregateNamesSupported() { return false; }
/** Abstract method to decide whether aggregate names (busses) can have gaps in their ranges. */
protected boolean isAggregateNameGapsSupported() { return false; }
/** Method to report whether input and output names are separated. */
protected boolean isSeparateInputAndOutput() { return false; }
/** Abstract method to decide whether netlister is case-sensitive (Verilog) or not (Spice). */
protected boolean isCaseSensitive() { return false; }
/**
* Method to adjust a network name to be safe for Spice output.
* Spice has a list of legal punctuation characters that it allows.
*/
protected String getSafeNetName(String name, boolean bus)
{
return getSafeNetName(name, bus, legalSpiceChars, spiceEngine);
}
/**
* Method called during hierarchy traversal.
* Called at the end of the enter cell phase.
*/
protected void enterCell(HierarchyEnumerator.CellInfo info)
{
if (exemptedNets != null)
exemptedNets.setExemptedNets(info);
}
/** Method to report that not to choose best export name among exports connected to signal. */
protected boolean isChooseBestExportName() { return false; }
/** If the netlister has requirments not to netlist certain cells and their
* subcells, override this method.
* If this cell has a spice template, skip it
*/
protected boolean skipCellAndSubcells(Cell cell)
{
// skip if there is a template
Variable varTemplate = null;
varTemplate = getEngineTemplate(cell);
if (varTemplate != null) return true;
// look for a model file for the current cell, can come from pref or on cell
String fileName = null;
if (CellModelPrefs.spiceModelPrefs.isUseModelFromFile(cell)) {
fileName = CellModelPrefs.spiceModelPrefs.getModelFile(cell);
}
varTemplate = cell.getVar(SPICE_NETLIST_FILE_KEY);
if (varTemplate != null) {
Object obj = varTemplate.getObject();
if (obj instanceof String) {
String str = (String)obj;
if (!str.equals("") && !str.equals("*Undefined"))
fileName = str;
}
}
if (fileName != null) {
if (!modelOverrides.containsKey(cell))
{
String absFileName = fileName;
if (!fileName.startsWith("/") && !fileName.startsWith("\\")) {
File spiceFile = new File(filePath);
absFileName = (new File(spiceFile.getParent(), fileName)).getPath();
}
boolean alreadyIncluded = false;
for (String includeFile : modelOverrides.values()) {
if (absFileName.equals(includeFile))
alreadyIncluded = true;
}
if (alreadyIncluded) {
multiLinePrint(true, "\n* " + cell + " is described in this file:\n");
multiLinePrint(true, "* "+fileName+" (already included) \n");
} else {
multiLinePrint(true, "\n* " + cell + " is described in this file:\n");
addIncludeFile(fileName);
}
modelOverrides.put(cell, absFileName);
}
return true;
}
return false;
}
/**
* Method called when a cell is skipped.
* Performs any checking to validate that no error occurs.
*/
protected void validateSkippedCell(HierarchyEnumerator.CellInfo info) {
String fileName = modelOverrides.get(info.getCell());
if (fileName != null) {
// validate included file
SpiceNetlistReader reader = new SpiceNetlistReader();
try {
reader.readFile(fileName, false);
HierarchyEnumerator.CellInfo parentInfo = info.getParentInfo();
Nodable no = info.getParentInst();
String parameterizedName = info.getCell().getName();
if (no != null && parentInfo != null) {
parameterizedName = parameterizedName(no, parentInfo.getContext());
}
CellNetInfo cni = getCellNetInfo(parameterizedName);
SpiceSubckt subckt = reader.getSubckt(parameterizedName);
if (cni != null && subckt != null) {
if (subckt == null) {
System.out.println("Error: No subckt for "+parameterizedName+" found in included file: "+fileName);
} else {
List<String> signals = new ArrayList<String>();
for (Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); ) {
CellSignal cs = sIt.next();
if (ignoreSubcktPort(cs)) continue;
signals.add(cs.getName());
}
List<String> subcktSignals = subckt.getPorts();
if (signals.size() != subcktSignals.size()) {
System.out.println("Warning: wrong number of ports for subckt "+
parameterizedName+": expected "+signals.size()+", but found "+
subcktSignals.size()+", in included file "+fileName);
}
int len = Math.min(signals.size(), subcktSignals.size());
for (int i=0; i<len; i++) {
String s1 = signals.get(i);
String s2 = subcktSignals.get(i);
if (!s1.equalsIgnoreCase(s2)) {
System.out.println("Warning: port "+i+" of subckt "+parameterizedName+
" is named "+s1+" in Electric, but "+s2+" in included file "+fileName);
}
}
}
}
} catch (FileNotFoundException e) {
System.out.println("Error validating included file for cell "+info.getCell().describe(true)+": "+e.getMessage());
}
}
}
/** Tell the Hierarchy enumerator how to short resistors */
@Override
protected Netlist.ShortResistors getShortResistors() {
// TODO use the value of Simulation.getSpiceShortResistors()
// switch (Simulation.getSpiceShortResistors())
// {
// case 0: return Netlist.ShortResistors.NO;
// case 1: return Netlist.ShortResistors.PARASITIC;
// case 2: return Netlist.ShortResistors.ALL;
// }
if (useCDL && Simulation.getCDLIgnoreResistors())
return Netlist.ShortResistors.PARASITIC;
// this option is used for writing spice netlists for LVS and RCX
if (Simulation.isSpiceIgnoreParasiticResistors())
return Netlist.ShortResistors.PARASITIC;
return Netlist.ShortResistors.NO;
}
/**
* Method to tell whether the topological analysis should mangle cell names that are parameterized.
*/
protected boolean canParameterizeNames() { return true; } //return !useCDL; }
/**
* Method to tell set a limit on the number of characters in a name.
* @return the limit to name size (SPICE limits to 32 character names?????).
*/
protected int maxNameLength() { if (useCDL) return CDLMAXLENSUBCKTNAME; return SPICEMAXLENSUBCKTNAME; }
protected boolean enumerateLayoutView(Cell cell) {
return (CellModelPrefs.spiceModelPrefs.isUseLayoutView(cell));
}
private Netlist.ShortResistors getShortResistorsFlat() {
return Netlist.ShortResistors.ALL;
}
/******************** DECK GENERATION SUPPORT ********************/
/**
* Method to write M factor information into a given string buffer
* @param context the context of the nodable for finding M-factors farther up the hierarchy.
* @param no Nodable representing the node
* @param infstr Buffer where to write to
*/
private void writeMFactor(VarContext context, Nodable no, StringBuffer infstr)
{
Variable mVar = no.getVar(Simulation.M_FACTOR_KEY);
if (mVar == null) return;
Object value = context.evalVar(mVar);
// check for M=@M, and warn user that this is a bad idea, and we will not write it out
if (mVar.getObject().toString().equals("@M") || (mVar.getObject().toString().equals("P(\"M\")")))
{
System.out.println("Warning: M=@M [eval=" + value + "] on " + no.getName() +
" is a bad idea, not writing it out: " + context.push(no).getInstPath("."));
return;
}
infstr.append(" M=" + formatParam(value.toString(), TextDescriptor.Unit.NONE, false));
}
/**
* write a header for "cell" to spice deck "sim_spice_file"
* The model cards come from a file specified by tech:~.SIM_spice_model_file
* or else tech:~.SIM_spice_header_level%ld
* The spice model file can be located in el_libdir
*/
private void writeHeader(Cell cell)
{
// Print the header line for SPICE
multiLinePrint(true, "*** SPICE deck for cell " + cell.noLibDescribe() +
" from library " + cell.getLibrary().getName() + "\n");
emitCopyright("*** ", "");
if (User.isIncludeDateAndVersionInOutput())
{
multiLinePrint(true, "*** Created on " + TextUtils.formatDate(topCell.getCreationDate()) + "\n");
multiLinePrint(true, "*** Last revised on " + TextUtils.formatDate(topCell.getRevisionDate()) + "\n");
multiLinePrint(true, "*** Written on " + TextUtils.formatDate(new Date()) +
" by Electric VLSI Design System, version " + Version.getVersion() + "\n");
} else
{
multiLinePrint(true, "*** Written by Electric VLSI Design System\n");
}
String foundry = layoutTechnology.getSelectedFoundry() == null ? "" : (", foundry "+layoutTechnology.getSelectedFoundry().toString());
multiLinePrint(true, "*** Layout tech: "+layoutTechnology.getTechName()+foundry+"\n");
multiLinePrint(true, "*** UC SPICE *** , MIN_RESIST " + layoutTechnology.getMinResistance() +
", MIN_CAPAC " + layoutTechnology.getMinCapacitance() + "FF\n");
boolean useParasitics = !useCDL &&
Simulation.getSpiceParasiticsLevel() != Simulation.SpiceParasitics.SIMPLE &&
cell.getView() == View.LAYOUT;
if (useParasitics) {
for (Layer layer : layoutTechnology.getLayersSortedByHeight()) {
if (layer.isPseudoLayer()) continue;
double edgecap = layer.getEdgeCapacitance();
double areacap = layer.getCapacitance();
double res = layer.getResistance();
if (edgecap != 0 || areacap != 0 || res != 0) {
multiLinePrint(true, "*** "+layer.getName()+":\tareacap="+areacap+"FF/um^2,\tedgecap="+edgecap+"FF/um,\tres="+res+"ohms/sq\n");
}
}
}
multiLinePrint(false, ".OPTIONS NOMOD NOPAGE\n");
if (Simulation.isSpiceUseCellParameters()) {
multiLinePrint(false, ".options parhier=local\n");
}
// if sizes to be written in lambda, tell spice conversion factor
if (Simulation.isSpiceWriteTransSizeInLambda())
{
double scale = layoutTechnology.getScale();
multiLinePrint(true, "*** Lambda Conversion ***\n");
multiLinePrint(false, ".opt scale=" + TextUtils.formatDouble(scale / 1000.0) + "U\n\n");
}
// see if spice model/option cards from file if specified
String headerFile = Simulation.getSpiceHeaderCardInfo();
if (headerFile.length() > 0 && !headerFile.startsWith(SPICE_NOEXTENSION_PREFIX))
{
if (headerFile.startsWith(SPICE_EXTENSION_PREFIX))
{
// extension specified: look for a file with the cell name and that extension
String headerPath = TextUtils.getFilePath(TextUtils.makeURLToFile(filePath));
String ext = headerFile.substring(SPICE_EXTENSION_PREFIX.length());
if (ext.startsWith(".")) ext = ext.substring(1);
String filePart = cell.getName() + "." + ext;
String fileName = headerPath + filePart;
File test = new File(fileName);
if (test.exists())
{
multiLinePrint(true, "* Model cards are described in this file:\n");
addIncludeFile(filePart);
System.out.println("Spice Header Card '" + fileName + "' is included");
return;
}
System.out.println("Spice Header Card '" + fileName + "' cannot be loaded");
} else
{
// normal header file specified
File test = new File(headerFile);
if (!test.exists())
System.out.println("Warning: cannot find model file '" + headerFile + "'");
multiLinePrint(true, "* Model cards are described in this file:\n");
addIncludeFile(headerFile);
return;
}
}
// no header files: write predefined header for this level and technology
int level = TextUtils.atoi(Simulation.getSpiceLevel());
String [] header = null;
switch (level)
{
case 1: header = layoutTechnology.getSpiceHeaderLevel1(); break;
case 2: header = layoutTechnology.getSpiceHeaderLevel2(); break;
case 3: header = layoutTechnology.getSpiceHeaderLevel3(); break;
}
if (header != null)
{
for(int i=0; i<header.length; i++)
multiLinePrint(false, header[i] + "\n");
return;
}
System.out.println("WARNING: no model cards for SPICE level " + level +
" in " + layoutTechnology.getTechName() + " technology");
}
/**
* Write a trailer from an external file, defined as a variable on
* the current technology in this library: tech:~.SIM_spice_trailer_file
* if it is available.
*/
private void writeTrailer(Cell cell)
{
// get spice trailer cards from file if specified
String trailerFile = Simulation.getSpiceTrailerCardInfo();
if (trailerFile.length() > 0 && !trailerFile.startsWith(SPICE_NOEXTENSION_PREFIX))
{
if (trailerFile.startsWith(SPICE_EXTENSION_PREFIX))
{
// extension specified: look for a file with the cell name and that extension
String trailerpath = TextUtils.getFilePath(TextUtils.makeURLToFile(filePath));
String ext = trailerFile.substring(SPICE_EXTENSION_PREFIX.length());
if (ext.startsWith(".")) ext = ext.substring(1);
String filePart = cell.getName() + "." + ext;
String fileName = trailerpath + filePart;
File test = new File(fileName);
if (test.exists())
{
multiLinePrint(true, "* Trailer cards are described in this file:\n");
addIncludeFile(filePart);
System.out.println("Spice Trailer Card '" + fileName + "' is included");
}
else
{
System.out.println("Spice Trailer Card '" + fileName + "' cannot be loaded");
}
} else
{
// normal trailer file specified
multiLinePrint(true, "* Trailer cards are described in this file:\n");
addIncludeFile(trailerFile);
System.out.println("Spice Trailer Card '" + trailerFile + "' is included");
}
}
}
/**
* Function to write a two port device to the file. Complain about any missing connections.
* Determine the port connections from the portprotos in the instance
* prototype. Get the part number from the 'part' number value;
* increment it. The type of device is declared in type; extra is the string
* data acquired before calling here.
* If the device is connected to the same net at both ends, do not
* write it. Is this OK?
*/
private void writeTwoPort(NodeInst ni, String partName, String extra, CellNetInfo cni, Netlist netList,
VarContext context, SpiceSegmentedNets segmentedNets)
{
PortInst port0 = ni.getPortInst(0);
PortInst port1 = ni.getPortInst(1);
Network net0 = netList.getNetwork(port0);
Network net1 = netList.getNetwork(port1);
CellSignal cs0 = cni.getCellSignal(net0);
CellSignal cs1 = cni.getCellSignal(net1);
// make sure the component is connected to nets
if (cs0 == null || cs1 == null)
{
String message = "WARNING: " + ni + " component not fully connected in " + ni.getParent();
dumpErrorMessage(message);
}
if (cs0 != null && cs1 != null && cs0 == cs1)
{
String message = "WARNING: " + ni + " component appears to be shorted on net " + net0.toString() +
" in " + ni.getParent();
dumpErrorMessage(message);
return;
}
if (ni.getName() != null) partName += getSafeNetName(ni.getName(), false);
// add Mfactor if there
StringBuffer sbExtra = new StringBuffer(extra);
writeMFactor(context, ni, sbExtra);
String name0 = cs0.getName();
String name1 = cs1.getName();
if (segmentedNets != null) {
name0 = segmentedNets.getNetName(port0);
name1 = segmentedNets.getNetName(port1);
}
multiLinePrint(false, partName + " " + name1 + " " + name0 + " " + sbExtra.toString() + "\n");
}
/******************** SIMPLE PARASITIC CALCULATIONS (AREA/PERIM) ********************/
/**
* Method to recursively determine the area of diffusion and capacitance
* associated with port "pp" of nodeinst "ni". If the node is mult_layer, then
* determine the dominant capacitance layer, and add its area; all other
* layers will be added as well to the extra_area total.
* Continue out of the ports on a complex cell
*/
private void addNodeInformation(Netlist netList, Map<Network,SpiceNet> spiceNets, NodeInst ni)
{
// cells have no area or capacitance (for now)
if (ni.isCellInstance()) return; // No area for complex nodes
PrimitiveNode.Function function = ni.getFunction();
// initialize to examine the polygons on this node
Technology tech = ni.getProto().getTechnology();
AffineTransform trans = ni.rotateOut();
// make linked list of polygons
Poly [] polyList = tech.getShapeOfNode(ni, true, true, null);
int tot = polyList.length;
for(int i=0; i<tot; i++)
{
Poly poly = polyList[i];
// make sure this layer connects electrically to the desired port
PortProto pp = poly.getPort();
if (pp == null) continue;
Network net = netList.getNetwork(ni, pp, 0);
// don't bother with layers without capacity
if (poly.isPseudoLayer()) continue;
Layer layer = poly.getLayer();
if (layer.getTechnology() != Technology.getCurrent()) continue;
if (!layer.isDiffusionLayer() && layer.getCapacitance() == 0.0) continue;
// leave out the gate capacitance of transistors
if (layer.getFunction() == Layer.Function.GATE) continue;
SpiceNet spNet = spiceNets.get(net);
if (spNet == null) continue;
// get the area of this polygon
poly.transform(trans);
spNet.merge.addPolygon(layer, poly);
// count the number of transistors on this net
if (layer.isDiffusionLayer() && function.isTransistor()) spNet.transistorCount++;
}
}
/**
* Method to recursively determine the area of diffusion, capacitance, (NOT
* resistance) on arc "ai". If the arc contains active device diffusion, then
* it will contribute to the area of sources and drains, and the other layers
* will be ignored. This is not quite the same as the rule used for
* contact (node) structures. Note: the earlier version of this
* function assumed that diffusion arcs would always have zero capacitance
* values for the other layers; this produces an error if any of these layers
* have non-zero values assigned for other reasons. So we will check for the
* function of the arc, and if it contains active device, we will ignore any
* other layers
*/
private void addArcInformation(PolyMerge merge, ArcInst ai)
{
boolean isDiffArc = ai.isDiffusionArc(); // check arc function
if (!isDiffArc) {
// all cap besides diffusion is handled by segmented nets
return;
}
Technology tech = ai.getProto().getTechnology();
Poly [] arcInstPolyList = tech.getShapeOfArc(ai);
int tot = arcInstPolyList.length;
for(int j=0; j<tot; j++)
{
Poly poly = arcInstPolyList[j];
if (poly.getStyle().isText()) continue;
if (poly.isPseudoLayer()) continue;
Layer layer = poly.getLayer();
if (layer.getTechnology() != Technology.getCurrent()) continue;
if (layer.isDiffusionLayer() ||
(!isDiffArc && layer.getCapacitance() > 0.0))
merge.addPolygon(layer, poly);
}
}
/******************** SUPPORT ********************/
private boolean ignoreSubcktPort(CellSignal cs)
{
if (Simulation.isSpiceUseNodeNames() && spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_3)
{
// ignore networks that aren't exported
PortProto pp = cs.getExport();
if (pp == null) return true;
}
return false;
}
/**
* Finds cells that must be uniquified during netlisting. These are
* cells that have parameters which are Java Code. Because the Java Code
* expression can return values that are different for different instances
* in the hierarchy, the hierarchy must be flattened above that instance.
* @param cell the cell hierarchy to check
* @return true if the cell has been marked to unquify (which is true if
* any cell below it has been marked).
*/
private boolean markCellsToUniquify(Cell cell)
{
if (uniquifyCells.containsKey(cell)) return uniquifyCells.get(cell) != null;
boolean mark = false;
for (Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); ) {
NodeInst ni = it.next();
if (ni.isIconOfParent()) continue;
Set<Variable.Key> varkeys = detectSpiceParams(ni.getProto());
// check vars on instance; only uniquify cells that contain instances with Java params
for (Variable.Key key : varkeys) {
Variable var = ni.getVar(key);
if (var != null && !isNetlistableParam(var)) mark = true;
}
if (!ni.isCellInstance()) continue;
Cell proto = ((Cell)ni.getProto()).contentsView();
if (proto == null) proto = (Cell)ni.getProto();
if (getEngineTemplate(proto) != null) continue;
if (markCellsToUniquify(proto)) { mark = true; }
}
boolean isUnique = detectSpiceParams(cell) == UNIQUIFY_MARK;
assert mark == isUnique;
if (mark)
uniquifyCells.put(cell, cell);
else
uniquifyCells.put(cell, null);
//System.out.println("---> "+cell.describe(false)+" is marked "+mark);
return mark;
}
private static final boolean CELLISEMPTYDEBUG = false;
private Map<Cell,Boolean> checkedCells = new HashMap<Cell,Boolean>();
private boolean cellIsEmpty(Cell cell)
{
Boolean b = checkedCells.get(cell);
if (b != null) return b.booleanValue();
boolean empty = true;
boolean useParasitics = !useCDL &&
Simulation.getSpiceParasiticsLevel() != Simulation.SpiceParasitics.SIMPLE &&
cell.getView() == View.LAYOUT;
if (useParasitics) return false;
List<Cell> emptyCells = new ArrayList<Cell>();
for (Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); ) {
NodeInst ni = it.next();
// if node is a cell, check if subcell is empty
if (ni.isCellInstance()) {
// ignore own icon
if (ni.isIconOfParent()) {
continue;
}
Cell iconCell = (Cell)ni.getProto();
Cell schCell = iconCell.contentsView();
if (schCell == null) schCell = iconCell;
if (cellIsEmpty(schCell)) {
if (CELLISEMPTYDEBUG) emptyCells.add(schCell);
continue;
}
empty = false;
break;
}
// otherwise, this is a primitive
PrimitiveNode.Function fun = ni.getFunction();
// Passive devices used by spice/CDL
if (fun.isResistor() || // == PrimitiveNode.Function.RESIST ||
fun == PrimitiveNode.Function.INDUCT ||
fun.isCapacitor() || // == PrimitiveNode.Function.CAPAC || fun == PrimitiveNode.Function.ECAPAC ||
fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
empty = false;
break;
}
// active devices used by Spice/CDL
if (((PrimitiveNode)ni.getProto()).getGroupFunction() == PrimitiveNode.Function.TRANS) {
empty = false;
break;
}
// check for spice code on pins
if (ni.getVar(SPICE_CARD_KEY) != null) {
empty = false;
break;
}
}
// look for a model file on the current cell
if (modelOverrides.get(cell) != null) {
empty = false;
}
// check for spice template
if (getEngineTemplate(cell) != null) {
empty = false;
}
// empty
if (CELLISEMPTYDEBUG && empty) {
System.out.println(cell+" is empty and contains the following empty cells:");
for (Cell c : emptyCells)
System.out.println(" "+c.describe(true));
}
checkedCells.put(cell, Boolean.valueOf(empty));
return empty;
}
/******************** TEXT METHODS ********************/
/**
* Method to adjust a network name to be safe for Spice output.
* Spice has a list of legal punctuation characters that it allows.
*/
public static String getSafeNetName(String name)
{
String legalSpiceChars = SPICELEGALCHARS;
if (Simulation.getSpiceEngine() == Simulation.SpiceEngine.SPICE_ENGINE_P)
legalSpiceChars = PSPICELEGALCHARS;
return getSafeNetName(name, false, legalSpiceChars, Simulation.getSpiceEngine());
}
/**
* Method to adjust a network name to be safe for Spice output.
* Spice has a list of legal punctuation characters that it allows.
*/
private static String getSafeNetName(String name, boolean bus, String legalSpiceChars, Simulation.SpiceEngine spiceEngine)
{
// simple names are trivially accepted as is
boolean allAlNum = true;
int len = name.length();
if (len <= 0) return name;
for(int i=0; i<len; i++)
{
boolean valid = TextUtils.isLetterOrDigit(name.charAt(i));
if (i == 0) valid = Character.isLetter(name.charAt(i));
if (!valid)
{
allAlNum = false;
break;
}
}
if (allAlNum) return name;
StringBuffer sb = new StringBuffer();
if (TextUtils.isDigit(name.charAt(0)) &&
spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_G &&
spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_P &&
spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_2) sb.append('_');
for(int t=0; t<name.length(); t++)
{
char chr = name.charAt(t);
boolean legalChar = TextUtils.isLetterOrDigit(chr);
if (!legalChar)
{
for(int j=0; j<legalSpiceChars.length(); j++)
{
char legalChr = legalSpiceChars.charAt(j);
if (chr == legalChr) { legalChar = true; break; }
}
}
if (!legalChar) chr = '_';
sb.append(chr);
}
return sb.toString();
}
/**
* This adds formatting to a Spice parameter value. It adds single quotes
* around the param string if they do not already exist.
* @param param the string param value (without the name= part).
* @param wrapped true if the string is already "wrapped" (with parenthesis) and does not need to have quotes around it.
* @return a param string with single quotes around it
*/
private String formatParam(String param, TextDescriptor.Unit u, boolean wrapped)
{
// first remove quotes
String value = trimSingleQuotes(param);
// see if the result evaluates to a number
if (TextUtils.isANumberPostFix(value)) return value;
// if purely numeric, try converting to proper units
try {
Double v = Double.valueOf(value);
if (u == TextDescriptor.Unit.DISTANCE)
return TextUtils.formatDoublePostFix(v.doubleValue());
return value;
} catch (NumberFormatException e) {}
// not a number: if Spice engine cannot handle quotes, return stripped value
if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_2 ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3) return value;
// not a number but Spice likes quotes, enclose it
if (!wrapped) value = "'" + value + "'";
return value;
}
private String trimSingleQuotes(String param)
{
if (param.startsWith("'") && param.endsWith("'")) {
return param.substring(1, param.length()-1);
}
return param;
}
/**
* Method to insert an "include" of file "filename" into the stream "io".
*/
private void addIncludeFile(String fileName)
{
if (useCDL) {
multiLinePrint(false, ".include "+ fileName + "\n");
return;
}
if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_2 || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3 ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_G || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_S)
{
multiLinePrint(false, ".include " + fileName + "\n");
} else if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_ASSURA ||
spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_CALIBRE)
{
multiLinePrint(false, ".include '" + fileName + "'\n");
} else if (spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_P)
{
multiLinePrint(false, ".INC " + fileName + "\n");
}
}
/**
* Method to report an error that is built in the infinite string.
* The error is sent to the messages window and also to the SPICE deck "f".
*/
private void dumpErrorMessage(String message)
{
multiLinePrint(true, "*** " + message + "\n");
System.out.println(message);
}
/**
* Formatted output to file "stream". All spice output is in upper case.
* The buffer can contain no more than 1024 chars including the newlinelastMoveTo
* and null characters.
* Doesn't return anything.
*/
public void multiLinePrint(boolean isComment, String str)
{
// put in line continuations, if over 78 chars long
char contChar = '+';
if (isComment) contChar = '*';
int lastSpace = -1;
int count = 0;
boolean insideQuotes = false;
int lineStart = 0;
for (int pt = 0; pt < str.length(); pt++)
{
char chr = str.charAt(pt);
// if (sim_spice_machine == SPICE2)
// {
// if (islower(*pt)) *pt = toupper(*pt);
// }
if (chr == '\n')
{
printWriter.print(str.substring(lineStart, pt+1));
count = 0;
lastSpace = -1;
lineStart = pt+1;
} else
{
if (chr == ' ' && !insideQuotes) lastSpace = pt;
if (chr == '\'') insideQuotes = !insideQuotes;
count++;
if (count >= spiceMaxLenLine && !insideQuotes && lastSpace > -1)
{
String partial = str.substring(lineStart, lastSpace+1);
printWriter.print(partial + "\n" + contChar);
count = count - partial.length();
lineStart = lastSpace+1;
lastSpace = -1;
}
}
}
if (lineStart < str.length())
{
String partial = str.substring(lineStart);
printWriter.print(partial);
}
}
/******************** SUPPORT CLASSES ********************/
private static class SpiceNet
{
/** network object associated with this */ Network network;
/** merged geometry for this network */ PolyMerge merge;
/** area of diffusion */ double diffArea;
/** perimeter of diffusion */ double diffPerim;
/** amount of capacitance in non-diff */ float nonDiffCapacitance;
/** number of transistors on the net */ int transistorCount;
SpiceNet(Network net)
{
network = net;
transistorCount = 0;
diffArea = 0;
diffPerim = 0;
nonDiffCapacitance = 0;
merge = new PolyMerge();
}
}
private static class SpiceFinishedListener implements Exec.FinishedListener
{
private Cell cell;
private FileType type;
private String file;
private SpiceFinishedListener(Cell cell, FileType type, String file) {
this.cell = cell;
this.type = type;
this.file = file;
}
public void processFinished(Exec.FinishedEvent e) {
URL fileURL = TextUtils.makeURLToFile(file);
// create a new waveform window
WaveformWindow ww = WaveformWindow.findWaveformWindow(cell);
Simulate.plotSimulationResults(type, cell, fileURL, ww);
}
}
public static class FlatSpiceCodeVisitor extends HierarchyEnumerator.Visitor {
private PrintWriter printWriter;
private PrintWriter spicePrintWriter;
private String filePath;
Spice spice; // just used for file writing and formatting
SpiceSegmentedNets segNets;
public FlatSpiceCodeVisitor(String filePath, Spice spice) {
this.spice = spice;
this.spicePrintWriter = spice.printWriter;
this.filePath = filePath;
spice.spiceMaxLenLine = 1000;
segNets = null;
}
public boolean enterCell(HierarchyEnumerator.CellInfo info) {
return true;
}
public void exitCell(HierarchyEnumerator.CellInfo info) {
Cell cell = info.getCell();
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech().invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_CODE_FLAT_KEY);
if (cardVar != null) {
if (printWriter == null) {
try {
printWriter = new PrintWriter(new BufferedWriter(new FileWriter(filePath)));
} catch (IOException e) {
System.out.println("Unable to open "+filePath+" for write.");
return;
}
spice.printWriter = printWriter;
segNets = new SpiceSegmentedNets(null, false, null, Simulation.SpiceParasitics.SIMPLE);
}
spice.emitEmbeddedSpice(cardVar, info.getContext(), segNets, info, true, true);
}
}
}
public boolean visitNodeInst(Nodable ni, HierarchyEnumerator.CellInfo info) {
return true;
}
public void close() {
if (printWriter != null) {
System.out.println(filePath+" written");
spice.printWriter = spicePrintWriter;
printWriter.close();
}
spice.spiceMaxLenLine = SPICEMAXLENLINE;
}
}
}
| true | true | protected void writeCellTopology(Cell cell, CellNetInfo cni, VarContext context, Topology.MyCellInfo info)
{
// if this is the top level cell, write globals
if (cell == topCell)
{
Netlist netList = cni.getNetList();
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (!Simulation.isSpiceUseNodeNames() || spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_3)
{
if (globalSize > 0)
{
StringBuffer infstr = new StringBuffer();
infstr.append("\n.global");
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
String name = global.getName();
if (global == Global.power) { if (getPowerName(null) != null) name = getPowerName(null); }
if (global == Global.ground) { if (getGroundName(null) != null) name = getGroundName(null); }
infstr.append(" " + name);
}
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
}
// make sure power and ground appear at the top level
if (!Simulation.isSpiceForceGlobalPwrGnd())
{
if (cni.getPowerNet() == null)
System.out.println("WARNING: cannot find power at top level of circuit");
if (cni.getGroundNet() == null)
System.out.println("WARNING: cannot find ground at top level of circuit");
}
}
// create electrical nets (SpiceNet) for every Network in the cell
Netlist netList = cni.getNetList();
Map<Network,SpiceNet> spiceNetMap = new HashMap<Network,SpiceNet>();
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
SpiceNet spNet = new SpiceNet(net);
spiceNetMap.put(net, spNet);
}
// for non-simple parasitics, create a SpiceSegmentedNets object to deal with them
Simulation.SpiceParasitics spLevel = Simulation.getSpiceParasiticsLevel();
if (useCDL || cell.getView() != View.LAYOUT) spLevel = Simulation.SpiceParasitics.SIMPLE;
SpiceSegmentedNets segmentedNets = null;
if (spLevel != Simulation.SpiceParasitics.SIMPLE)
{
// make the parasitics info object if it does not already exist
if (parasiticInfo == null)
{
if (spLevel == Simulation.SpiceParasitics.RC_PROXIMITY)
{
parasiticInfo = new SpiceParasitic();
} else if (spLevel == Simulation.SpiceParasitics.RC_CONSERVATIVE)
{
parasiticInfo = new SpiceRCSimple();
}
}
segmentedNets = parasiticInfo.initializeSegments(cell, cni, layoutTechnology, exemptedNets, info);
}
// count the number of different transistor types
int bipolarTrans = 0, nmosTrans = 0, pmosTrans = 0;
for(Iterator<NodeInst> aIt = cell.getNodes(); aIt.hasNext(); )
{
NodeInst ni = aIt.next();
addNodeInformation(netList, spiceNetMap, ni);
PrimitiveNode.Function fun = ni.getFunction();
if (fun == PrimitiveNode.Function.TRANPN || fun == PrimitiveNode.Function.TRA4NPN ||
fun == PrimitiveNode.Function.TRAPNP || fun == PrimitiveNode.Function.TRA4PNP ||
fun == PrimitiveNode.Function.TRANS) bipolarTrans++; else
if (fun.isNTypeTransistor()) nmosTrans++; else
if (fun.isPTypeTransistor()) pmosTrans++;
}
// accumulate geometry of all arcs
for(Iterator<ArcInst> aIt = cell.getArcs(); aIt.hasNext(); )
{
ArcInst ai = aIt.next();
// don't count non-electrical arcs
if (ai.getProto().getFunction() == ArcProto.Function.NONELEC) continue;
// ignore busses
// if (ai->network->buswidth > 1) continue;
Network net = netList.getNetwork(ai, 0);
SpiceNet spNet = spiceNetMap.get(net);
if (spNet == null) continue;
addArcInformation(spNet.merge, ai);
}
// get merged polygons so far
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
SpiceNet spNet = spiceNetMap.get(net);
for (Layer layer : spNet.merge.getKeySet())
{
List<PolyBase> polyList = spNet.merge.getMergedPoints(layer, true);
if (polyList == null) continue;
if (polyList.size() > 1)
Collections.sort(polyList, GeometryHandler.shapeSort);
for(PolyBase poly : polyList)
{
// compute perimeter and area
double perim = poly.getPerimeter();
double area = poly.getArea();
// accumulate this information
double scale = layoutTechnology.getScale(); // scale to convert units to nanometers
if (layer.isDiffusionLayer()) {
spNet.diffArea += area * maskScale * maskScale;
spNet.diffPerim += perim * maskScale;
} else {
area = area * scale * scale / 1000000; // area in square microns
perim = perim * scale / 1000; // perim in microns
spNet.nonDiffCapacitance += layer.getCapacitance() * area * maskScale * maskScale;
spNet.nonDiffCapacitance += layer.getEdgeCapacitance() * perim * maskScale;
}
}
}
}
// make sure the ground net is number zero
Network groundNet = cni.getGroundNet();
Network powerNet = cni.getPowerNet();
if (pmosTrans != 0 && powerNet == null)
{
String message = "WARNING: no power connection for P-transistor wells in " + cell;
dumpErrorMessage(message);
}
if (nmosTrans != 0 && groundNet == null)
{
String message = "WARNING: no ground connection for N-transistor wells in " + cell;
dumpErrorMessage(message);
}
// generate header for subckt or top-level cell
boolean forceEval = useCDL || !Simulation.isSpiceUseCellParameters() || detectSpiceParams(cell) == UNIQUIFY_MARK;
String topLevelInstance = "";
if (cell == topCell && !useCDL && !Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(true, "\n*** TOP LEVEL CELL: " + cell.describe(false) + "\n");
} else
{
if (!writeEmptySubckts) {
if (cellIsEmpty(cell))
return;
}
String cellName = cni.getParameterizedName();
multiLinePrint(true, "\n*** CELL: " + cell.describe(false) + "\n");
StringBuffer infstr = new StringBuffer();
infstr.append(".SUBCKT " + cellName);
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
if (ignoreSubcktPort(cs)) continue;
if (!cs.isGlobal() && cs.getExport() == null) continue;
// special case for parasitic extraction
if (parasiticInfo != null && !cs.isGlobal() && cs.getExport() != null)
{
parasiticInfo.writeSubcircuitHeader(cs, infstr);
} else
{
infstr.append(" " + cs.getName());
}
}
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
// create top level instantiation
if (Simulation.isSpiceWriteTopCellInstance())
topLevelInstance = infstr.toString().replaceFirst("\\.SUBCKT ", "X") + " " + cellName;
}
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this cell
Set<Variable.Key> spiceParams = detectSpiceParams(cell);
for(Iterator<Variable> it = cell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
if (DETECT_SPICE_PARAMS && !spiceParams.contains(paramVar.getKey())) continue;
String value = paramVar.getPureValue(-1);
if (USE_JAVA_CODE) {
value = evalParam(context, info.getParentInst(), paramVar, forceEval);
} else if (!isNetlistableParam(paramVar))
continue;
infstr.append(" " + paramVar.getTrueName() + "=" + value);
}
}
infstr.append("\n");
multiLinePrint(false, infstr.toString());
// generate pin descriptions for reference (when not using node names)
if (!Simulation.isSpiceUseNodeNames() || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3)
{
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
Network net = netList.getNetwork(global);
CellSignal cs = cni.getCellSignal(net);
multiLinePrint(true, "** GLOBAL " + cs.getName() + "\n");
}
}
}
// write out any directly-typed SPICE declaratons for the cell
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech().invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_DECLARATION_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Declaration nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false, forceEval);
}
}
// third pass through the node list, print it this time
for(Iterator<Nodable> nIt = netList.getNodables(); nIt.hasNext(); )
{
Nodable no = nIt.next();
NodeProto niProto = no.getProto();
// boolean includePwrVdd = Simulation.isSpiceWritePwrGndInTopCell();
// handle sub-cell calls
if (no.isCellInstance())
{
Cell subCell = (Cell)niProto;
// get the SPICE template on the prototype (if any)
Variable varTemplate = getEngineTemplate(subCell);
if (varTemplate != null)
{
if (varTemplate.getObject() instanceof Object[])
{
Object [] manyLines = (Object [])varTemplate.getObject();
for(int i=0; i<manyLines.length; i++)
{
String line = manyLines[i].toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false, forceEval);
// Writing MFactor if available. Not sure here
if (i == 0) writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
} else
{
String line = varTemplate.getObject().toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false, forceEval);
// Writing MFactor if available. Not sure here
writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
continue;
}
// get the ports on this node (in proper order)
CellNetInfo subCni = getCellNetInfo(parameterizedName(no, context));
if (subCni == null) continue;
if (!writeEmptySubckts)
{
// do not instantiate if empty
if (cellIsEmpty((Cell)niProto)) continue;
}
String modelChar = "X";
if (no.getName() != null) modelChar += getSafeNetName(no.getName(), false);
StringBuffer infstr = new StringBuffer();
infstr.append(modelChar);
for(Iterator<CellSignal> sIt = subCni.getCellSignals(); sIt.hasNext(); )
{
CellSignal subCS = sIt.next();
if (ignoreSubcktPort(subCS)) continue;
PortProto pp = subCS.getExport();
if (!subCS.isGlobal() && pp == null) continue;
// If global pwr/vdd will be included in the subcircuit
// Preparing code for bug #1828
// if (!Simulation.isSpiceWritePwrGndInTopCell() && pp!= null && subCS.isGlobal() && (subCS.isGround() || subCS.isPower()))
// continue;
Network net;
int exportIndex = subCS.getExportIndex();
// This checks if we are netlisting a schematic top level with swapped-in layout subcells
if (pp != null && cell.isSchematic() && (subCni.getCell().getView() == View.LAYOUT))
{
// find equivalent pp from layout to schematic
Network subNet = subCS.getNetwork(); // layout network name
boolean found = false;
for (Iterator<Export> eIt = subCell.getExports(); eIt.hasNext(); )
{
Export ex = eIt.next();
for (int i=0; i<ex.getNameKey().busWidth(); i++)
{
String exName = ex.getNameKey().subname(i).toString();
if (exName.equals(subNet.getName()))
{
pp = ex;
exportIndex = i;
found = true;
break;
}
}
if (found) break;
}
if (!found)
{
if (pp.isGround() && pp.getName().startsWith("gnd")) {
infstr.append(" gnd");
} else if (pp.isPower() && pp.getName().startsWith("vdd")) {
infstr.append(" vdd");
} else {
System.out.println("No matching export on schematic/icon found for export "+
subNet.getName()+" in cell "+subCni.getCell().describe(false));
infstr.append(" unknown");
}
continue;
}
}
if (subCS.isGlobal())
{
net = netList.getNetwork(no, subCS.getGlobal());
}
else
net = netList.getNetwork(no, pp, exportIndex);
if (net == null)
{
System.out.println("Warning: cannot find network for signal " + subCS.getName() + " in cell " +
subCni.getCell().describe(false));
continue;
}
CellSignal cs = cni.getCellSignal(net);
// special case for parasitic extraction
SpiceSegmentedNets subSN = null;
if (parasiticInfo != null && !cs.isGlobal())
subSN = parasiticInfo.getSegmentedNets((Cell)no.getProto());
if (subSN != null)
{
parasiticInfo.getParasiticName(no, subCS.getNetwork(), subSN, infstr);
} else
{
String name = cs.getName();
if (parasiticInfo != null)
{
name = segmentedNets.getNetName(no.getNodeInst().findPortInstFromProto(pp));
}
infstr.append(" " + name);
}
}
if (useCDL) infstr.append(" /"); else infstr.append(" ");
infstr.append(subCni.getParameterizedName());
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this instance
Set<Variable.Key> spiceParams = detectSpiceParams(subCell);
for(Iterator<Variable> it = subCell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
if (DETECT_SPICE_PARAMS && !spiceParams.contains(paramVar.getKey())) continue;
if (!USE_JAVA_CODE && !isNetlistableParam(paramVar)) continue;
Variable instVar = no.getParameter(paramVar.getKey());
String paramStr = "??";
if (instVar != null)
{
if (USE_JAVA_CODE)
{
paramStr = evalParam(context, no, instVar, forceEval);
} else
{
Object obj = null;
if (isNetlistableParam(instVar))
{
obj = context.evalSpice(instVar, false);
} else
{
obj = context.evalVar(instVar, no);
}
if (obj != null)
paramStr = formatParam(String.valueOf(obj), instVar.getUnit(), false);
}
}
infstr.append(" " + paramVar.getTrueName() + "=" + paramStr);
}
}
// Writing MFactor if available.
writeMFactor(context, no, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
continue;
}
// get the type of this node
NodeInst ni = (NodeInst)no;
// look for a SPICE template on the primitive
String line = ((PrimitiveNode)ni.getProto()).getSpiceTemplate();
if (line != null)
{
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false, forceEval);
// Writing MFactor if available. Not sure here
writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
continue;
}
// handle resistors, inductors, capacitors, and diodes
PrimitiveNode.Function fun = ni.getFunction();
if (fun.isResistor() || fun.isCapacitor() ||
fun == PrimitiveNode.Function.INDUCT ||
fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
if (fun.isResistor())
{
if ((fun.isPolyOrWellResistor() && isShortExplicitResistors()) ||
(fun == PrimitiveNode.Function.RESIST && isShortResistors()))
continue;
Variable resistVar = ni.getVar(Schematics.SCHEM_RESISTANCE);
String extra = "";
String partName = "R";
if (resistVar != null)
{
if (USE_JAVA_CODE) {
extra = evalParam(context, ni, resistVar, forceEval);
} else {
if (resistVar.getCode() == CodeExpression.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(resistVar, false);
extra = String.valueOf(obj);
} else {
extra = resistVar.describe(context, ni);
}
}
if (extra == "")
extra = resistVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); //displayedUnits(pureValue, TextDescriptor.Unit.RESISTANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, resistVar.getUnit(), false);
}
} else {
// remove next 10 lines when PRESIST and WRESIST are finally deprecated
if (fun == PrimitiveNode.Function.PRESIST)
{
if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) fun = PrimitiveNode.Function.RESPPOLY;
if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) fun = PrimitiveNode.Function.RESNPOLY;
}
if (fun == PrimitiveNode.Function.WRESIST)
{
if (ni.getProto().getName().equals("P-Well-RPO-Resistor")) fun = PrimitiveNode.Function.RESPWELL;
if (ni.getProto().getName().equals("N-Well-RPO-Resistor")) fun = PrimitiveNode.Function.RESNWELL;
}
if (fun == PrimitiveNode.Function.RESPPOLY || fun == PrimitiveNode.Function.RESNPOLY ||
fun == PrimitiveNode.Function.RESPWELL || fun == PrimitiveNode.Function.RESNWELL)
{
partName = "XR";
double width = ni.getLambdaBaseYSize();
double length = ni.getLambdaBaseXSize();
if (Simulation.isSpiceWriteTransSizeInLambda())
{
extra = " L="+length+" W="+width;
} else
{
extra = " L="+formatParam(length+"*LAMBDA", TextDescriptor.Unit.NONE, false)+
" W="+formatParam(width+"*LAMBDA", TextDescriptor.Unit.NONE, false);
}
String prepend = "";
if (fun == PrimitiveNode.Function.RESPPOLY) prepend = "rppo1rpo"; else
if (fun == PrimitiveNode.Function.RESNPOLY) prepend = "rnpo1rpo"; else
if (fun == PrimitiveNode.Function.RESPWELL) prepend = "rpwod "; else
if (fun == PrimitiveNode.Function.RESNWELL) prepend = "rnwod ";
if (layoutTechnology == Technology.getCMOS90Technology() ||
(cell.getView() == View.LAYOUT && cell.getTechnology() == Technology.getCMOS90Technology()))
{
if (fun == PrimitiveNode.Function.RESPPOLY) prepend = "GND rpporpo"; else
if (fun == PrimitiveNode.Function.RESNPOLY) prepend = "GND rnporpo";
}
extra = prepend + extra;
}
}
writeTwoPort(ni, partName, extra, cni, netList, context, segmentedNets);
} else if (fun.isCapacitor())
{
Variable capacVar = ni.getVar(Schematics.SCHEM_CAPACITANCE);
String extra = "";
if (capacVar != null)
{
if (USE_JAVA_CODE) {
extra = evalParam(context, no, capacVar, forceEval);
} else {
if (capacVar.getCode() == CodeExpression.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(capacVar, false);
extra = String.valueOf(obj);
} else {
extra = capacVar.describe(context, ni);
}
}
if (extra == "")
extra = capacVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.CAPACITANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, capacVar.getUnit(), false);
}
}
writeTwoPort(ni, "C", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.INDUCT)
{
Variable inductVar = ni.getVar(Schematics.SCHEM_INDUCTANCE);
String extra = "";
if (inductVar != null)
{
if (USE_JAVA_CODE) {
extra = evalParam(context, no, inductVar, forceEval);
} else {
if (inductVar.getCode() == CodeExpression.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(inductVar, false);
extra = String.valueOf(obj);
} else {
extra = inductVar.describe(context, ni);
}
}
if (extra == "")
extra = inductVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.INDUCTANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, inductVar.getUnit(), false);
}
}
writeTwoPort(ni, "L", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
Variable diodeVar = ni.getVar(Schematics.SCHEM_DIODE);
String extra = "";
if (diodeVar != null)
extra = diodeVar.describe(context, ni);
if (extra.length() == 0) extra = "DIODE";
writeTwoPort(ni, "D", extra, cni, netList, context, segmentedNets);
}
continue;
}
// the default is to handle everything else as a transistor
if (((PrimitiveNode)niProto).getGroupFunction() != PrimitiveNode.Function.TRANS)
continue;
Network gateNet = netList.getNetwork(ni.getTransistorGatePort());
CellSignal gateCs = cni.getCellSignal(gateNet);
Network sourceNet = netList.getNetwork(ni.getTransistorSourcePort());
CellSignal sourceCs = cni.getCellSignal(sourceNet);
Network drainNet = netList.getNetwork(ni.getTransistorDrainPort());
CellSignal drainCs = cni.getCellSignal(drainNet);
CellSignal biasCs = null;
PortInst biasPort = ni.getTransistorBiasPort();
if (biasPort != null)
{
biasCs = cni.getCellSignal(netList.getNetwork(biasPort));
}
// make sure transistor is connected to nets
if (gateCs == null || sourceCs == null || drainCs == null)
{
String message = "WARNING: " + ni + " not fully connected in " + cell;
dumpErrorMessage(message);
}
// get model information
String modelName = null;
String defaultBulkName = null;
Variable modelVar = ni.getVar(SPICE_MODEL_KEY);
if (modelVar != null) modelName = modelVar.getObject().toString();
// special case for ST090 technology which has stupid non-standard transistor
// models which are subcircuits
boolean st090laytrans = false;
boolean tsmc090laytrans = false;
if (cell.getView() == View.LAYOUT && layoutTechnology == Technology.getCMOS90Technology()) {
if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.TSMC)
tsmc090laytrans = true;
else if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.ST)
st090laytrans = true;
}
String modelChar = "";
if (fun == PrimitiveNode.Function.TRANSREF) // self-referential transistor
{
modelChar = "X";
biasCs = cni.getCellSignal(groundNet);
modelName = niProto.getName();
} else if (fun == PrimitiveNode.Function.TRANMOS) // NMOS (Enhancement) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
defaultBulkName = "gnd";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRA4NMOS) // NMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRADMOS) // DMOS (Depletion) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRA4DMOS) // DMOS (Depletion) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRAPMOS) // PMOS (Complementary) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(powerNet);
defaultBulkName = "vdd";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRA4PMOS) // PMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRANPN) // NPN (Junction) transistor
{
modelChar = "Q";
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRA4NPN) // NPN (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRAPNP) // PNP (Junction) transistor
{
modelChar = "Q";
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRA4PNP) // PNP (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRANJFET) // NJFET (N Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRA4NJFET) // NJFET (N Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRAPJFET) // PJFET (P Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRA4PJFET) // PJFET (P Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRADMES || // DMES (Depletion) transistor
fun == PrimitiveNode.Function.TRA4DMES) // DMES (Depletion) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "DMES";
} else if (fun == PrimitiveNode.Function.TRAEMES || // EMES (Enhancement) transistor
fun == PrimitiveNode.Function.TRA4EMES) // EMES (Enhancement) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "EMES";
} else if (fun == PrimitiveNode.Function.TRANS) // special transistor
{
modelChar = "Q";
}
if (ni.getName() != null) modelChar += getSafeNetName(ni.getName(), false);
StringBuffer infstr = new StringBuffer();
String drainName = drainCs.getName();
String gateName = gateCs.getName();
String sourceName = sourceCs.getName();
if (segmentedNets != null) {
drainName = segmentedNets.getNetName(ni.getTransistorDrainPort());
gateName = segmentedNets.getNetName(ni.getTransistorGatePort());
sourceName = segmentedNets.getNetName(ni.getTransistorSourcePort());
}
infstr.append(modelChar + " " + drainName + " " + gateName + " " + sourceName);
if (biasCs != null) {
String biasName = biasCs.getName();
if (segmentedNets != null && ni.getTransistorBiasPort() != null)
biasName = segmentedNets.getNetName(ni.getTransistorBiasPort());
infstr.append(" " + biasName);
} else {
if (cell.getView() == View.LAYOUT && defaultBulkName != null)
infstr.append(" " + defaultBulkName);
}
if (modelName != null) infstr.append(" " + modelName);
// compute length and width (or area for nonMOS transistors)
TransistorSize size = ni.getTransistorSize(context);
if (size == null)
System.out.println("Warning: transistor with null size " + ni.getName());
else
{
if (size.getDoubleWidth() > 0 || size.getDoubleLength() > 0)
{
double w = maskScale * size.getDoubleWidth();
double l = maskScale * size.getDoubleLength();
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
l -= lengthSubtraction;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
// make into microns (convert to nanometers then divide by 1000)
l *= layoutTechnology.getScale() / 1000.0;
w *= layoutTechnology.getScale() / 1000.0;
}
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS ||
((fun == PrimitiveNode.Function.TRANJFET || fun == PrimitiveNode.Function.TRAPJFET ||
fun == PrimitiveNode.Function.TRADMES || fun == PrimitiveNode.Function.TRAEMES) &&
(spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_ASSURA)))
{
// schematic transistors may be text
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE, false) + " - "+ lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE, false));
} else {
infstr.append(" L=" + TextUtils.formatDouble(l));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String)) {
infstr.append(" W="+formatParam((String)size.getWidth(), TextDescriptor.Unit.DISTANCE, false));
} else {
infstr.append(" W=" + TextUtils.formatDouble(w));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
if (fun != PrimitiveNode.Function.TRANMOS && fun != PrimitiveNode.Function.TRA4NMOS &&
fun != PrimitiveNode.Function.TRAPMOS && fun != PrimitiveNode.Function.TRA4PMOS &&
fun != PrimitiveNode.Function.TRADMOS && fun != PrimitiveNode.Function.TRA4DMOS)
{
infstr.append(" AREA=" + TextUtils.formatDouble(l*w));
if (!Simulation.isSpiceWriteTransSizeInLambda()) infstr.append("P");
}
} else {
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE, false) + " - "+lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE, false));
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String))
infstr.append(" W="+formatParam((String)size.getWidth(), TextDescriptor.Unit.DISTANCE, false));
}
}
// make sure transistor is connected to nets
SpiceNet spNetGate = spiceNetMap.get(gateNet);
SpiceNet spNetSource = spiceNetMap.get(sourceNet);
SpiceNet spNetDrain = spiceNetMap.get(drainNet);
if (spNetGate == null || spNetSource == null || spNetDrain == null) continue;
// compute area of source and drain
if (!useCDL)
{
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS)
{
double as = 0, ad = 0, ps = 0, pd = 0;
if (spNetSource.transistorCount != 0)
{
as = spNetSource.diffArea / spNetSource.transistorCount;
ps = spNetSource.diffPerim / spNetSource.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
as *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
ps *= layoutTechnology.getScale() / 1000.0;
}
}
if (spNetDrain.transistorCount != 0)
{
ad = spNetDrain.diffArea / spNetDrain.transistorCount;
pd = spNetDrain.diffPerim / spNetDrain.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
ad *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
pd *= layoutTechnology.getScale() / 1000.0;
}
}
if (as > 0.0)
{
infstr.append(" AS=" + TextUtils.formatDouble(as));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ad > 0.0)
{
infstr.append(" AD=" + TextUtils.formatDouble(ad));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ps > 0.0)
{
infstr.append(" PS=" + TextUtils.formatDouble(ps));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if (pd > 0.0)
{
infstr.append(" PD=" + TextUtils.formatDouble(pd));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
}
// Writing MFactor if available.
writeMFactor(context, ni, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
// print resistances and capacitances
if (segmentedNets != null)
{
if (spLevel == Simulation.SpiceParasitics.RC_PROXIMITY)
{
parasiticInfo.writeNewSpiceCode(cell, cni, layoutTechnology, this);
} else {
// write caps
int capCount = 0;
multiLinePrint(true, "** Extracted Parasitic Capacitors ***\n");
for (SpiceSegmentedNets.NetInfo netInfo : segmentedNets.getUniqueSegments()) {
if (netInfo.getCap() > cell.getTechnology().getMinCapacitance()) {
if (netInfo.getName().equals("gnd")) continue; // don't write out caps from gnd to gnd
multiLinePrint(false, "C" + capCount + " " + netInfo.getName() + " 0 " + TextUtils.formatDouble(netInfo.getCap()) + "fF\n");
capCount++;
}
}
// write resistors
int resCount = 0;
multiLinePrint(true, "** Extracted Parasitic Resistors ***\n");
for (Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); ) {
ArcInst ai = it.next();
Double res = segmentedNets.getRes(ai);
if (res == null) continue;
String n0 = segmentedNets.getNetName(ai.getHeadPortInst());
String n1 = segmentedNets.getNetName(ai.getTailPortInst());
int arcPImodels = SpiceSegmentedNets.getNumPISegments(res.doubleValue(), layoutTechnology.getMaxSeriesResistance());
if (arcPImodels > 1) {
// have to break it up into smaller pieces
double segCap = segmentedNets.getArcCap(ai)/(arcPImodels+1);
double segRes = res.doubleValue()/arcPImodels;
String segn0 = n0;
String segn1 = n0;
for (int i=0; i<arcPImodels; i++) {
segn1 = n0 + "##" + i;
// print cap on intermediate node
if (i == (arcPImodels-1))
segn1 = n1;
multiLinePrint(false, "R"+resCount+" "+segn0+" "+segn1+" "+TextUtils.formatDouble(segRes)+"\n");
resCount++;
if (i < (arcPImodels-1)) {
if (!segn1.equals("gnd") && segCap > layoutTechnology.getMinCapacitance()) {
String capVal = TextUtils.formatDouble(segCap);
if (!capVal.equals("0.00")) {
multiLinePrint(false, "C"+capCount+" "+segn1+" 0 "+capVal+"fF\n");
capCount++;
}
}
}
segn0 = segn1;
}
} else {
multiLinePrint(false, "R" + resCount + " " + n0 + " " + n1 + " " + TextUtils.formatDouble(res.doubleValue()) + "\n");
resCount++;
}
}
}
}
// write out any directly-typed SPICE cards
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech().invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_CARD_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Code nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false, forceEval);
}
}
// finally, if this is the top level,
// write out some very small resistors between any networks
// that are asserted will be connected by the NCC annotation "exportsConnectedByParent"
// this should really be done internally in the network tool with a switch, but
// this hack works here for now
NccCellAnnotations anna = NccCellAnnotations.getAnnotations(cell);
if (cell == topCell && anna != null) {
// each list contains all name patterns that are be shorted together
if (anna.getExportsConnected().hasNext()) {
multiLinePrint(true, "\n*** Exports shorted due to NCC annotation 'exportsConnectedByParent':\n");
}
for (Iterator<List<NamePattern>> it = anna.getExportsConnected(); it.hasNext(); ) {
List<NamePattern> list = it.next();
List<Network> netsToConnect = new ArrayList<Network>();
// each name pattern can match any number of exports in the cell
for (NccCellAnnotations.NamePattern pat : list) {
for (Iterator<PortProto> it3 = cell.getPorts(); it3.hasNext(); ) {
Export e = (Export)it3.next();
String name = e.getName();
// keep track of networks to short together
if (pat.matches(name)) {
Network net = netList.getNetwork(e, 0);
if (!netsToConnect.contains(net))
netsToConnect.add(net);
}
}
}
// connect all nets in list of nets to connect
String name = null;
for (Network net : netsToConnect) {
if (name != null) {
multiLinePrint(false, "R"+name+" "+name+" "+net.getName()+" 0.001\n");
}
name = net.getName();
}
}
}
// now we're finished writing the subcircuit.
if (cell != topCell || useCDL || Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(false, ".ENDS " + cni.getParameterizedName() + "\n");
}
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
multiLinePrint(false, "\n\n"+topLevelInstance+"\n\n");
}
}
| protected void writeCellTopology(Cell cell, CellNetInfo cni, VarContext context, Topology.MyCellInfo info)
{
// if this is the top level cell, write globals
if (cell == topCell)
{
Netlist netList = cni.getNetList();
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (!Simulation.isSpiceUseNodeNames() || spiceEngine != Simulation.SpiceEngine.SPICE_ENGINE_3)
{
if (globalSize > 0)
{
StringBuffer infstr = new StringBuffer();
infstr.append("\n.global");
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
String name = global.getName();
if (global == Global.power) { if (getPowerName(null) != null) name = getPowerName(null); }
if (global == Global.ground) { if (getGroundName(null) != null) name = getGroundName(null); }
infstr.append(" " + name);
}
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
}
// make sure power and ground appear at the top level
if (!Simulation.isSpiceForceGlobalPwrGnd())
{
if (cni.getPowerNet() == null)
System.out.println("WARNING: cannot find power at top level of circuit");
if (cni.getGroundNet() == null)
System.out.println("WARNING: cannot find ground at top level of circuit");
}
}
// create electrical nets (SpiceNet) for every Network in the cell
Netlist netList = cni.getNetList();
Map<Network,SpiceNet> spiceNetMap = new HashMap<Network,SpiceNet>();
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
SpiceNet spNet = new SpiceNet(net);
spiceNetMap.put(net, spNet);
}
// for non-simple parasitics, create a SpiceSegmentedNets object to deal with them
Simulation.SpiceParasitics spLevel = Simulation.getSpiceParasiticsLevel();
if (useCDL || cell.getView() != View.LAYOUT) spLevel = Simulation.SpiceParasitics.SIMPLE;
SpiceSegmentedNets segmentedNets = null;
if (spLevel != Simulation.SpiceParasitics.SIMPLE)
{
// make the parasitics info object if it does not already exist
if (parasiticInfo == null)
{
if (spLevel == Simulation.SpiceParasitics.RC_PROXIMITY)
{
parasiticInfo = new SpiceParasitic();
} else if (spLevel == Simulation.SpiceParasitics.RC_CONSERVATIVE)
{
parasiticInfo = new SpiceRCSimple();
}
}
segmentedNets = parasiticInfo.initializeSegments(cell, cni, layoutTechnology, exemptedNets, info);
}
// count the number of different transistor types
int bipolarTrans = 0, nmosTrans = 0, pmosTrans = 0;
for(Iterator<NodeInst> aIt = cell.getNodes(); aIt.hasNext(); )
{
NodeInst ni = aIt.next();
addNodeInformation(netList, spiceNetMap, ni);
PrimitiveNode.Function fun = ni.getFunction();
if (fun == PrimitiveNode.Function.TRANPN || fun == PrimitiveNode.Function.TRA4NPN ||
fun == PrimitiveNode.Function.TRAPNP || fun == PrimitiveNode.Function.TRA4PNP ||
fun == PrimitiveNode.Function.TRANS) bipolarTrans++; else
if (fun.isNTypeTransistor()) nmosTrans++; else
if (fun.isPTypeTransistor()) pmosTrans++;
}
// accumulate geometry of all arcs
for(Iterator<ArcInst> aIt = cell.getArcs(); aIt.hasNext(); )
{
ArcInst ai = aIt.next();
// don't count non-electrical arcs
if (ai.getProto().getFunction() == ArcProto.Function.NONELEC) continue;
// ignore busses
// if (ai->network->buswidth > 1) continue;
Network net = netList.getNetwork(ai, 0);
SpiceNet spNet = spiceNetMap.get(net);
if (spNet == null) continue;
addArcInformation(spNet.merge, ai);
}
// get merged polygons so far
for(Iterator<Network> it = netList.getNetworks(); it.hasNext(); )
{
Network net = it.next();
SpiceNet spNet = spiceNetMap.get(net);
for (Layer layer : spNet.merge.getKeySet())
{
List<PolyBase> polyList = spNet.merge.getMergedPoints(layer, true);
if (polyList == null) continue;
if (polyList.size() > 1)
Collections.sort(polyList, GeometryHandler.shapeSort);
for(PolyBase poly : polyList)
{
// compute perimeter and area
double perim = poly.getPerimeter();
double area = poly.getArea();
// accumulate this information
double scale = layoutTechnology.getScale(); // scale to convert units to nanometers
if (layer.isDiffusionLayer()) {
spNet.diffArea += area * maskScale * maskScale;
spNet.diffPerim += perim * maskScale;
} else {
area = area * scale * scale / 1000000; // area in square microns
perim = perim * scale / 1000; // perim in microns
spNet.nonDiffCapacitance += layer.getCapacitance() * area * maskScale * maskScale;
spNet.nonDiffCapacitance += layer.getEdgeCapacitance() * perim * maskScale;
}
}
}
}
// make sure the ground net is number zero
Network groundNet = cni.getGroundNet();
Network powerNet = cni.getPowerNet();
if (pmosTrans != 0 && powerNet == null)
{
String message = "WARNING: no power connection for P-transistor wells in " + cell;
dumpErrorMessage(message);
}
if (nmosTrans != 0 && groundNet == null)
{
String message = "WARNING: no ground connection for N-transistor wells in " + cell;
dumpErrorMessage(message);
}
// generate header for subckt or top-level cell
boolean forceEval = useCDL || !Simulation.isSpiceUseCellParameters() || detectSpiceParams(cell) == UNIQUIFY_MARK;
String topLevelInstance = "";
if (cell == topCell && !useCDL && !Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(true, "\n*** TOP LEVEL CELL: " + cell.describe(false) + "\n");
} else
{
if (!writeEmptySubckts) {
if (cellIsEmpty(cell))
return;
}
String cellName = cni.getParameterizedName();
multiLinePrint(true, "\n*** CELL: " + cell.describe(false) + "\n");
StringBuffer infstr = new StringBuffer();
infstr.append(".SUBCKT " + cellName);
for(Iterator<CellSignal> sIt = cni.getCellSignals(); sIt.hasNext(); )
{
CellSignal cs = sIt.next();
if (ignoreSubcktPort(cs)) continue;
if (!cs.isGlobal() && cs.getExport() == null) continue;
// special case for parasitic extraction
if (parasiticInfo != null && !cs.isGlobal() && cs.getExport() != null)
{
parasiticInfo.writeSubcircuitHeader(cs, infstr);
} else
{
infstr.append(" " + cs.getName());
}
}
Global.Set globals = netList.getGlobals();
int globalSize = globals.size();
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
// create top level instantiation
if (Simulation.isSpiceWriteTopCellInstance())
topLevelInstance = infstr.toString().replaceFirst("\\.SUBCKT ", "X") + " " + cellName;
}
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this cell
Set<Variable.Key> spiceParams = detectSpiceParams(cell);
for(Iterator<Variable> it = cell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
if (DETECT_SPICE_PARAMS && !spiceParams.contains(paramVar.getKey())) continue;
String value = paramVar.getPureValue(-1);
if (USE_JAVA_CODE) {
value = evalParam(context, info.getParentInst(), paramVar, forceEval);
} else if (!isNetlistableParam(paramVar))
continue;
infstr.append(" " + paramVar.getTrueName() + "=" + value);
}
}
infstr.append("\n");
multiLinePrint(false, infstr.toString());
// generate pin descriptions for reference (when not using node names)
if (!Simulation.isSpiceUseNodeNames() || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_3)
{
for(int i=0; i<globalSize; i++)
{
Global global = globals.get(i);
Network net = netList.getNetwork(global);
CellSignal cs = cni.getCellSignal(net);
multiLinePrint(true, "** GLOBAL " + cs.getName() + "\n");
}
}
}
// write out any directly-typed SPICE declaratons for the cell
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech().invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_DECLARATION_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Declaration nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false, forceEval);
}
}
// third pass through the node list, print it this time
for(Iterator<Nodable> nIt = netList.getNodables(); nIt.hasNext(); )
{
Nodable no = nIt.next();
NodeProto niProto = no.getProto();
// boolean includePwrVdd = Simulation.isSpiceWritePwrGndInTopCell();
// handle sub-cell calls
if (no.isCellInstance())
{
Cell subCell = (Cell)niProto;
// get the SPICE template on the prototype (if any)
Variable varTemplate = getEngineTemplate(subCell);
if (varTemplate != null)
{
if (varTemplate.getObject() instanceof Object[])
{
Object [] manyLines = (Object [])varTemplate.getObject();
for(int i=0; i<manyLines.length; i++)
{
String line = manyLines[i].toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false, forceEval);
// Writing MFactor if available. Not sure here
if (i == 0) writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
} else
{
String line = varTemplate.getObject().toString();
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false, forceEval);
// Writing MFactor if available. Not sure here
writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
}
continue;
}
// get the ports on this node (in proper order)
CellNetInfo subCni = getCellNetInfo(parameterizedName(no, context));
if (subCni == null) continue;
if (!writeEmptySubckts)
{
// do not instantiate if empty
if (cellIsEmpty((Cell)niProto)) continue;
}
String modelChar = "X";
if (no.getName() != null) modelChar += getSafeNetName(no.getName(), false);
StringBuffer infstr = new StringBuffer();
infstr.append(modelChar);
for(Iterator<CellSignal> sIt = subCni.getCellSignals(); sIt.hasNext(); )
{
CellSignal subCS = sIt.next();
if (ignoreSubcktPort(subCS)) continue;
PortProto pp = subCS.getExport();
if (!subCS.isGlobal() && pp == null) continue;
// If global pwr/vdd will be included in the subcircuit
// Preparing code for bug #1828
// if (!Simulation.isSpiceWritePwrGndInTopCell() && pp!= null && subCS.isGlobal() && (subCS.isGround() || subCS.isPower()))
// continue;
Network net;
int exportIndex = subCS.getExportIndex();
// This checks if we are netlisting a schematic top level with swapped-in layout subcells
if (pp != null && cell.isSchematic() && (subCni.getCell().getView() == View.LAYOUT))
{
// find equivalent pp from layout to schematic
Network subNet = subCS.getNetwork(); // layout network name
boolean found = false;
for (Iterator<Export> eIt = subCell.getExports(); eIt.hasNext(); )
{
Export ex = eIt.next();
for (int i=0; i<ex.getNameKey().busWidth(); i++)
{
String exName = ex.getNameKey().subname(i).toString();
if (exName.equals(subNet.getName()))
{
pp = ex;
exportIndex = i;
found = true;
break;
}
}
if (found) break;
}
if (!found)
{
if (pp.isGround() && pp.getName().startsWith("gnd")) {
infstr.append(" gnd");
} else if (pp.isPower() && pp.getName().startsWith("vdd")) {
infstr.append(" vdd");
} else {
System.out.println("No matching export on schematic/icon found for export "+
subNet.getName()+" in cell "+subCni.getCell().describe(false));
infstr.append(" unknown");
}
continue;
}
}
if (subCS.isGlobal())
{
net = netList.getNetwork(no, subCS.getGlobal());
}
else
net = netList.getNetwork(no, pp, exportIndex);
if (net == null)
{
System.out.println("Warning: cannot find network for signal " + subCS.getName() + " in cell " +
subCni.getCell().describe(false));
continue;
}
CellSignal cs = cni.getCellSignal(net);
// special case for parasitic extraction
SpiceSegmentedNets subSN = null;
if (parasiticInfo != null && !cs.isGlobal())
subSN = parasiticInfo.getSegmentedNets((Cell)no.getProto());
if (subSN != null)
{
parasiticInfo.getParasiticName(no, subCS.getNetwork(), subSN, infstr);
} else
{
String name = cs.getName();
if (parasiticInfo != null)
{
name = segmentedNets.getNetName(no.getNodeInst().findPortInstFromProto(pp));
}
infstr.append(" " + name);
}
}
if (useCDL) infstr.append(" /"); else infstr.append(" ");
infstr.append(subCni.getParameterizedName());
if (!useCDL && Simulation.isSpiceUseCellParameters())
{
// add in parameters to this instance
Set<Variable.Key> spiceParams = detectSpiceParams(subCell);
for(Iterator<Variable> it = subCell.getParameters(); it.hasNext(); )
{
Variable paramVar = it.next();
if (DETECT_SPICE_PARAMS && !spiceParams.contains(paramVar.getKey())) continue;
if (!USE_JAVA_CODE && !isNetlistableParam(paramVar)) continue;
Variable instVar = no.getParameter(paramVar.getKey());
String paramStr = "??";
if (instVar != null)
{
if (USE_JAVA_CODE)
{
paramStr = evalParam(context, no, instVar, forceEval);
} else
{
Object obj = null;
if (isNetlistableParam(instVar))
{
obj = context.evalSpice(instVar, false);
} else
{
obj = context.evalVar(instVar, no);
}
if (obj != null)
paramStr = formatParam(String.valueOf(obj), instVar.getUnit(), false);
}
}
infstr.append(" " + paramVar.getTrueName() + "=" + paramStr);
}
}
// Writing MFactor if available.
writeMFactor(context, no, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
continue;
}
// get the type of this node
NodeInst ni = (NodeInst)no;
// look for a SPICE template on the primitive
String line = ((PrimitiveNode)ni.getProto()).getSpiceTemplate();
if (line != null)
{
StringBuffer infstr = replacePortsAndVars(line, no, context, cni, segmentedNets, info, false, forceEval);
// Writing MFactor if available. Not sure here
writeMFactor(context, no, infstr);
infstr.append('\n');
multiLinePrint(false, infstr.toString());
continue;
}
// handle resistors, inductors, capacitors, and diodes
PrimitiveNode.Function fun = ni.getFunction();
if (fun.isResistor() || fun.isCapacitor() ||
fun == PrimitiveNode.Function.INDUCT ||
fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
if (fun.isResistor())
{
if ((fun.isPolyOrWellResistor() && isShortExplicitResistors()) ||
(fun == PrimitiveNode.Function.RESIST && isShortResistors()))
continue;
Variable resistVar = ni.getVar(Schematics.SCHEM_RESISTANCE);
String extra = "";
String partName = "R";
if (resistVar != null)
{
if (USE_JAVA_CODE) {
extra = evalParam(context, ni, resistVar, forceEval);
} else {
if (resistVar.getCode() == CodeExpression.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(resistVar, false);
extra = String.valueOf(obj);
} else {
extra = resistVar.describe(context, ni);
}
}
if (extra == "")
extra = resistVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); //displayedUnits(pureValue, TextDescriptor.Unit.RESISTANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, resistVar.getUnit(), false);
}
} else {
// remove next 10 lines when PRESIST and WRESIST are finally deprecated
// if (fun == PrimitiveNode.Function.PRESIST)
// {
// if (ni.getProto().getName().equals("P-Poly-RPO-Resistor")) fun = PrimitiveNode.Function.RESPPOLY;
// if (ni.getProto().getName().equals("N-Poly-RPO-Resistor")) fun = PrimitiveNode.Function.RESNPOLY;
// }
// if (fun == PrimitiveNode.Function.WRESIST)
// {
// if (ni.getProto().getName().equals("P-Well-RPO-Resistor")) fun = PrimitiveNode.Function.RESPWELL;
// if (ni.getProto().getName().equals("N-Well-RPO-Resistor")) fun = PrimitiveNode.Function.RESNWELL;
// }
if (fun == PrimitiveNode.Function.RESPPOLY || fun == PrimitiveNode.Function.RESNPOLY ||
fun == PrimitiveNode.Function.RESPWELL || fun == PrimitiveNode.Function.RESNWELL)
{
partName = "XR";
double width = ni.getLambdaBaseYSize();
double length = ni.getLambdaBaseXSize();
if (Simulation.isSpiceWriteTransSizeInLambda())
{
extra = " L="+length+" W="+width;
} else
{
extra = " L="+formatParam(length+"*LAMBDA", TextDescriptor.Unit.NONE, false)+
" W="+formatParam(width+"*LAMBDA", TextDescriptor.Unit.NONE, false);
}
String prepend = "";
if (fun == PrimitiveNode.Function.RESPPOLY) prepend = "rppo1rpo"; else
if (fun == PrimitiveNode.Function.RESNPOLY) prepend = "rnpo1rpo"; else
if (fun == PrimitiveNode.Function.RESPWELL) prepend = "rpwod "; else
if (fun == PrimitiveNode.Function.RESNWELL) prepend = "rnwod ";
if (layoutTechnology == Technology.getCMOS90Technology() ||
(cell.getView() == View.LAYOUT && cell.getTechnology() == Technology.getCMOS90Technology()))
{
if (fun == PrimitiveNode.Function.RESPPOLY) prepend = "GND rpporpo"; else
if (fun == PrimitiveNode.Function.RESNPOLY) prepend = "GND rnporpo";
}
extra = prepend + extra;
}
}
writeTwoPort(ni, partName, extra, cni, netList, context, segmentedNets);
} else if (fun.isCapacitor())
{
Variable capacVar = ni.getVar(Schematics.SCHEM_CAPACITANCE);
String extra = "";
if (capacVar != null)
{
if (USE_JAVA_CODE) {
extra = evalParam(context, no, capacVar, forceEval);
} else {
if (capacVar.getCode() == CodeExpression.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(capacVar, false);
extra = String.valueOf(obj);
} else {
extra = capacVar.describe(context, ni);
}
}
if (extra == "")
extra = capacVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.CAPACITANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, capacVar.getUnit(), false);
}
}
writeTwoPort(ni, "C", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.INDUCT)
{
Variable inductVar = ni.getVar(Schematics.SCHEM_INDUCTANCE);
String extra = "";
if (inductVar != null)
{
if (USE_JAVA_CODE) {
extra = evalParam(context, no, inductVar, forceEval);
} else {
if (inductVar.getCode() == CodeExpression.Code.SPICE) {
if (!useCDL && Simulation.isSpiceUseCellParameters()) {
Object obj = context.evalSpice(inductVar, false);
extra = String.valueOf(obj);
} else {
extra = inductVar.describe(context, ni);
}
}
if (extra == "")
extra = inductVar.describe(context, ni);
if (TextUtils.isANumber(extra))
{
double pureValue = TextUtils.atof(extra);
extra = TextUtils.formatDoublePostFix(pureValue); // displayedUnits(pureValue, TextDescriptor.Unit.INDUCTANCE, TextUtils.UnitScale.NONE);
} else
extra = formatParam(extra, inductVar.getUnit(), false);
}
}
writeTwoPort(ni, "L", extra, cni, netList, context, segmentedNets);
} else if (fun == PrimitiveNode.Function.DIODE || fun == PrimitiveNode.Function.DIODEZ)
{
Variable diodeVar = ni.getVar(Schematics.SCHEM_DIODE);
String extra = "";
if (diodeVar != null)
extra = diodeVar.describe(context, ni);
if (extra.length() == 0) extra = "DIODE";
writeTwoPort(ni, "D", extra, cni, netList, context, segmentedNets);
}
continue;
}
// the default is to handle everything else as a transistor
if (((PrimitiveNode)niProto).getGroupFunction() != PrimitiveNode.Function.TRANS)
continue;
Network gateNet = netList.getNetwork(ni.getTransistorGatePort());
CellSignal gateCs = cni.getCellSignal(gateNet);
Network sourceNet = netList.getNetwork(ni.getTransistorSourcePort());
CellSignal sourceCs = cni.getCellSignal(sourceNet);
Network drainNet = netList.getNetwork(ni.getTransistorDrainPort());
CellSignal drainCs = cni.getCellSignal(drainNet);
CellSignal biasCs = null;
PortInst biasPort = ni.getTransistorBiasPort();
if (biasPort != null)
{
biasCs = cni.getCellSignal(netList.getNetwork(biasPort));
}
// make sure transistor is connected to nets
if (gateCs == null || sourceCs == null || drainCs == null)
{
String message = "WARNING: " + ni + " not fully connected in " + cell;
dumpErrorMessage(message);
}
// get model information
String modelName = null;
String defaultBulkName = null;
Variable modelVar = ni.getVar(SPICE_MODEL_KEY);
if (modelVar != null) modelName = modelVar.getObject().toString();
// special case for ST090 technology which has stupid non-standard transistor
// models which are subcircuits
boolean st090laytrans = false;
boolean tsmc090laytrans = false;
if (cell.getView() == View.LAYOUT && layoutTechnology == Technology.getCMOS90Technology()) {
if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.TSMC)
tsmc090laytrans = true;
else if (layoutTechnology.getSelectedFoundry().getType() == Foundry.Type.ST)
st090laytrans = true;
}
String modelChar = "";
if (fun == PrimitiveNode.Function.TRANSREF) // self-referential transistor
{
modelChar = "X";
biasCs = cni.getCellSignal(groundNet);
modelName = niProto.getName();
} else if (fun == PrimitiveNode.Function.TRANMOS) // NMOS (Enhancement) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
defaultBulkName = "gnd";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRA4NMOS) // NMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "N";
if (st090laytrans) {
modelChar = "XM";
modelName = "nsvt";
}
if (tsmc090laytrans) {
modelName = "nch";
}
} else if (fun == PrimitiveNode.Function.TRADMOS) // DMOS (Depletion) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(groundNet);
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRA4DMOS) // DMOS (Depletion) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "D";
} else if (fun == PrimitiveNode.Function.TRAPMOS) // PMOS (Complementary) transistor
{
modelChar = "M";
biasCs = cni.getCellSignal(powerNet);
defaultBulkName = "vdd";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRA4PMOS) // PMOS (Complementary) 4-port transistor
{
modelChar = "M";
if (modelName == null) modelName = "P";
if (st090laytrans) {
modelChar = "XM";
modelName = "psvt";
}
if (tsmc090laytrans) {
modelName = "pch";
}
} else if (fun == PrimitiveNode.Function.TRANPN) // NPN (Junction) transistor
{
modelChar = "Q";
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRA4NPN) // NPN (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "NBJT";
} else if (fun == PrimitiveNode.Function.TRAPNP) // PNP (Junction) transistor
{
modelChar = "Q";
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRA4PNP) // PNP (Junction) 4-port transistor
{
modelChar = "Q";
if (modelName == null) modelName = "PBJT";
} else if (fun == PrimitiveNode.Function.TRANJFET) // NJFET (N Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRA4NJFET) // NJFET (N Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "NJFET";
} else if (fun == PrimitiveNode.Function.TRAPJFET) // PJFET (P Channel) transistor
{
modelChar = "J";
biasCs = null;
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRA4PJFET) // PJFET (P Channel) 4-port transistor
{
modelChar = "J";
if (modelName == null) modelName = "PJFET";
} else if (fun == PrimitiveNode.Function.TRADMES || // DMES (Depletion) transistor
fun == PrimitiveNode.Function.TRA4DMES) // DMES (Depletion) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "DMES";
} else if (fun == PrimitiveNode.Function.TRAEMES || // EMES (Enhancement) transistor
fun == PrimitiveNode.Function.TRA4EMES) // EMES (Enhancement) 4-port transistor
{
modelChar = "Z";
biasCs = null;
modelName = "EMES";
} else if (fun == PrimitiveNode.Function.TRANS) // special transistor
{
modelChar = "Q";
}
if (ni.getName() != null) modelChar += getSafeNetName(ni.getName(), false);
StringBuffer infstr = new StringBuffer();
String drainName = drainCs.getName();
String gateName = gateCs.getName();
String sourceName = sourceCs.getName();
if (segmentedNets != null) {
drainName = segmentedNets.getNetName(ni.getTransistorDrainPort());
gateName = segmentedNets.getNetName(ni.getTransistorGatePort());
sourceName = segmentedNets.getNetName(ni.getTransistorSourcePort());
}
infstr.append(modelChar + " " + drainName + " " + gateName + " " + sourceName);
if (biasCs != null) {
String biasName = biasCs.getName();
if (segmentedNets != null && ni.getTransistorBiasPort() != null)
biasName = segmentedNets.getNetName(ni.getTransistorBiasPort());
infstr.append(" " + biasName);
} else {
if (cell.getView() == View.LAYOUT && defaultBulkName != null)
infstr.append(" " + defaultBulkName);
}
if (modelName != null) infstr.append(" " + modelName);
// compute length and width (or area for nonMOS transistors)
TransistorSize size = ni.getTransistorSize(context);
if (size == null)
System.out.println("Warning: transistor with null size " + ni.getName());
else
{
if (size.getDoubleWidth() > 0 || size.getDoubleLength() > 0)
{
double w = maskScale * size.getDoubleWidth();
double l = maskScale * size.getDoubleLength();
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
l -= lengthSubtraction;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
// make into microns (convert to nanometers then divide by 1000)
l *= layoutTechnology.getScale() / 1000.0;
w *= layoutTechnology.getScale() / 1000.0;
}
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS ||
((fun == PrimitiveNode.Function.TRANJFET || fun == PrimitiveNode.Function.TRAPJFET ||
fun == PrimitiveNode.Function.TRADMES || fun == PrimitiveNode.Function.TRAEMES) &&
(spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H || spiceEngine == Simulation.SpiceEngine.SPICE_ENGINE_H_ASSURA)))
{
// schematic transistors may be text
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE, false) + " - "+ lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE, false));
} else {
infstr.append(" L=" + TextUtils.formatDouble(l));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String)) {
infstr.append(" W="+formatParam((String)size.getWidth(), TextDescriptor.Unit.DISTANCE, false));
} else {
infstr.append(" W=" + TextUtils.formatDouble(w));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
if (fun != PrimitiveNode.Function.TRANMOS && fun != PrimitiveNode.Function.TRA4NMOS &&
fun != PrimitiveNode.Function.TRAPMOS && fun != PrimitiveNode.Function.TRA4PMOS &&
fun != PrimitiveNode.Function.TRADMOS && fun != PrimitiveNode.Function.TRA4DMOS)
{
infstr.append(" AREA=" + TextUtils.formatDouble(l*w));
if (!Simulation.isSpiceWriteTransSizeInLambda()) infstr.append("P");
}
} else {
// get gate length subtraction in lambda
double lengthSubtraction = layoutTechnology.getGateLengthSubtraction() / layoutTechnology.getScale() * 1000;
if ((size.getDoubleLength() == 0) && (size.getLength() instanceof String)) {
if (lengthSubtraction != 0)
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE, false) + " - "+lengthSubtraction);
else
infstr.append(" L="+formatParam((String)size.getLength(), TextDescriptor.Unit.DISTANCE, false));
}
if ((size.getDoubleWidth() == 0) && (size.getWidth() instanceof String))
infstr.append(" W="+formatParam((String)size.getWidth(), TextDescriptor.Unit.DISTANCE, false));
}
}
// make sure transistor is connected to nets
SpiceNet spNetGate = spiceNetMap.get(gateNet);
SpiceNet spNetSource = spiceNetMap.get(sourceNet);
SpiceNet spNetDrain = spiceNetMap.get(drainNet);
if (spNetGate == null || spNetSource == null || spNetDrain == null) continue;
// compute area of source and drain
if (!useCDL)
{
if (fun == PrimitiveNode.Function.TRANMOS || fun == PrimitiveNode.Function.TRA4NMOS ||
fun == PrimitiveNode.Function.TRAPMOS || fun == PrimitiveNode.Function.TRA4PMOS ||
fun == PrimitiveNode.Function.TRADMOS || fun == PrimitiveNode.Function.TRA4DMOS)
{
double as = 0, ad = 0, ps = 0, pd = 0;
if (spNetSource.transistorCount != 0)
{
as = spNetSource.diffArea / spNetSource.transistorCount;
ps = spNetSource.diffPerim / spNetSource.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
as *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
ps *= layoutTechnology.getScale() / 1000.0;
}
}
if (spNetDrain.transistorCount != 0)
{
ad = spNetDrain.diffArea / spNetDrain.transistorCount;
pd = spNetDrain.diffPerim / spNetDrain.transistorCount;
if (!Simulation.isSpiceWriteTransSizeInLambda())
{
ad *= layoutTechnology.getScale() * layoutTechnology.getScale() / 1000000.0;
pd *= layoutTechnology.getScale() / 1000.0;
}
}
if (as > 0.0)
{
infstr.append(" AS=" + TextUtils.formatDouble(as));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ad > 0.0)
{
infstr.append(" AD=" + TextUtils.formatDouble(ad));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("P");
}
if (ps > 0.0)
{
infstr.append(" PS=" + TextUtils.formatDouble(ps));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
if (pd > 0.0)
{
infstr.append(" PD=" + TextUtils.formatDouble(pd));
if (!Simulation.isSpiceWriteTransSizeInLambda() && !st090laytrans) infstr.append("U");
}
}
}
// Writing MFactor if available.
writeMFactor(context, ni, infstr);
infstr.append("\n");
multiLinePrint(false, infstr.toString());
}
// print resistances and capacitances
if (segmentedNets != null)
{
if (spLevel == Simulation.SpiceParasitics.RC_PROXIMITY)
{
parasiticInfo.writeNewSpiceCode(cell, cni, layoutTechnology, this);
} else {
// write caps
int capCount = 0;
multiLinePrint(true, "** Extracted Parasitic Capacitors ***\n");
for (SpiceSegmentedNets.NetInfo netInfo : segmentedNets.getUniqueSegments()) {
if (netInfo.getCap() > cell.getTechnology().getMinCapacitance()) {
if (netInfo.getName().equals("gnd")) continue; // don't write out caps from gnd to gnd
multiLinePrint(false, "C" + capCount + " " + netInfo.getName() + " 0 " + TextUtils.formatDouble(netInfo.getCap()) + "fF\n");
capCount++;
}
}
// write resistors
int resCount = 0;
multiLinePrint(true, "** Extracted Parasitic Resistors ***\n");
for (Iterator<ArcInst> it = cell.getArcs(); it.hasNext(); ) {
ArcInst ai = it.next();
Double res = segmentedNets.getRes(ai);
if (res == null) continue;
String n0 = segmentedNets.getNetName(ai.getHeadPortInst());
String n1 = segmentedNets.getNetName(ai.getTailPortInst());
int arcPImodels = SpiceSegmentedNets.getNumPISegments(res.doubleValue(), layoutTechnology.getMaxSeriesResistance());
if (arcPImodels > 1) {
// have to break it up into smaller pieces
double segCap = segmentedNets.getArcCap(ai)/(arcPImodels+1);
double segRes = res.doubleValue()/arcPImodels;
String segn0 = n0;
String segn1 = n0;
for (int i=0; i<arcPImodels; i++) {
segn1 = n0 + "##" + i;
// print cap on intermediate node
if (i == (arcPImodels-1))
segn1 = n1;
multiLinePrint(false, "R"+resCount+" "+segn0+" "+segn1+" "+TextUtils.formatDouble(segRes)+"\n");
resCount++;
if (i < (arcPImodels-1)) {
if (!segn1.equals("gnd") && segCap > layoutTechnology.getMinCapacitance()) {
String capVal = TextUtils.formatDouble(segCap);
if (!capVal.equals("0.00")) {
multiLinePrint(false, "C"+capCount+" "+segn1+" 0 "+capVal+"fF\n");
capCount++;
}
}
}
segn0 = segn1;
}
} else {
multiLinePrint(false, "R" + resCount + " " + n0 + " " + n1 + " " + TextUtils.formatDouble(res.doubleValue()) + "\n");
resCount++;
}
}
}
}
// write out any directly-typed SPICE cards
if (!useCDL)
{
boolean firstDecl = true;
for(Iterator<NodeInst> it = cell.getNodes(); it.hasNext(); )
{
NodeInst ni = it.next();
if (ni.getProto() != Generic.tech().invisiblePinNode) continue;
Variable cardVar = ni.getVar(SPICE_CARD_KEY);
if (cardVar == null) continue;
if (firstDecl)
{
firstDecl = false;
multiLinePrint(true, "\n* Spice Code nodes in cell " + cell + "\n");
}
emitEmbeddedSpice(cardVar, context, segmentedNets, info, false, forceEval);
}
}
// finally, if this is the top level,
// write out some very small resistors between any networks
// that are asserted will be connected by the NCC annotation "exportsConnectedByParent"
// this should really be done internally in the network tool with a switch, but
// this hack works here for now
NccCellAnnotations anna = NccCellAnnotations.getAnnotations(cell);
if (cell == topCell && anna != null) {
// each list contains all name patterns that are be shorted together
if (anna.getExportsConnected().hasNext()) {
multiLinePrint(true, "\n*** Exports shorted due to NCC annotation 'exportsConnectedByParent':\n");
}
for (Iterator<List<NamePattern>> it = anna.getExportsConnected(); it.hasNext(); ) {
List<NamePattern> list = it.next();
List<Network> netsToConnect = new ArrayList<Network>();
// each name pattern can match any number of exports in the cell
for (NccCellAnnotations.NamePattern pat : list) {
for (Iterator<PortProto> it3 = cell.getPorts(); it3.hasNext(); ) {
Export e = (Export)it3.next();
String name = e.getName();
// keep track of networks to short together
if (pat.matches(name)) {
Network net = netList.getNetwork(e, 0);
if (!netsToConnect.contains(net))
netsToConnect.add(net);
}
}
}
// connect all nets in list of nets to connect
String name = null;
for (Network net : netsToConnect) {
if (name != null) {
multiLinePrint(false, "R"+name+" "+name+" "+net.getName()+" 0.001\n");
}
name = net.getName();
}
}
}
// now we're finished writing the subcircuit.
if (cell != topCell || useCDL || Simulation.isSpiceWriteSubcktTopCell())
{
multiLinePrint(false, ".ENDS " + cni.getParameterizedName() + "\n");
}
if (cell == topCell && Simulation.isSpiceWriteSubcktTopCell()) {
multiLinePrint(false, "\n\n"+topLevelInstance+"\n\n");
}
}
|
diff --git a/src/test/java/com/asgeirnilsen/blog/logging/WtfLoggerTest.java b/src/test/java/com/asgeirnilsen/blog/logging/WtfLoggerTest.java
index 7caa230..67abdf6 100644
--- a/src/test/java/com/asgeirnilsen/blog/logging/WtfLoggerTest.java
+++ b/src/test/java/com/asgeirnilsen/blog/logging/WtfLoggerTest.java
@@ -1,18 +1,18 @@
package com.asgeirnilsen.blog.logging;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WtfLoggerTest {
@Test
public void test() {
Logger logger = LoggerFactory.getLogger(getClass());
logger.error("Oh My GOD!");
logger.warn("What The F*ck just happened?");
- logger.info("JYI it worked fine.");
+ logger.info("JFYI it worked fine.");
logger.debug("Oh by the way -- test this");
}
}
| true | true | public void test() {
Logger logger = LoggerFactory.getLogger(getClass());
logger.error("Oh My GOD!");
logger.warn("What The F*ck just happened?");
logger.info("JYI it worked fine.");
logger.debug("Oh by the way -- test this");
}
| public void test() {
Logger logger = LoggerFactory.getLogger(getClass());
logger.error("Oh My GOD!");
logger.warn("What The F*ck just happened?");
logger.info("JFYI it worked fine.");
logger.debug("Oh by the way -- test this");
}
|
diff --git a/baixing_quanleimu/src/com/quanleimu/util/Util.java b/baixing_quanleimu/src/com/quanleimu/util/Util.java
index bc16e112..71a5b39d 100644
--- a/baixing_quanleimu/src/com/quanleimu/util/Util.java
+++ b/baixing_quanleimu/src/com/quanleimu/util/Util.java
@@ -1,1000 +1,1000 @@
package com.quanleimu.util;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.Bitmap.CompressFormat;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.os.Environment;
import android.util.Log;
import android.view.Display;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.Paint;
public class Util {
private static String[] keys;
private static String[] values;
public static String qq_access_key="";
public static String qq_access_secret="";
/**
*
* @author henry_young
* @throws IOException
*
* @保存方式:Stream 数据流方式
*
* writeUTF(String str); 但是用Data包装后就会支持。
*
* @操作模式: Context.MODE_PRIVATE:新内容覆盖原内容
*
* Context.MODE_APPEND:新内容追加到原内容后
*
* Context.MODE_WORLD_READABLE:允许其他应用程序读取
*
* Context.MODE_WORLD_WRITEABLE:允许其他应用程序写入,会覆盖原数据。
*/
//数据保存SD卡
public static String saveDataToSdCard(String path, String file,
Object object) {
String res = null;
FileOutputStream fos = null;
ObjectOutputStream oos = null;
if (Environment.getExternalStorageState() != null) {
try {
File p = new File("/sdcard/" + path); // 创建目录
File f = new File("/sdcard/" + path + "/" + file + ".txt"); // 创建文件
if (!p.exists()) {
p.mkdir();
}
if (!f.exists()) {
f.createNewFile();
}
fos = new FileOutputStream(f);
oos = new ObjectOutputStream(fos);
oos.writeObject(object);
System.out.println(fos + "fos");
System.out.println(oos + "oos");
} catch (FileNotFoundException e) {
res = "没有找到文件";
e.printStackTrace();
} catch (IOException e) {
res = "没有数据";
e.printStackTrace();
} finally {
try {
oos.close();
fos.close();
res = "保存成功";
} catch (IOException e) {
res = "没有数据";
e.printStackTrace();
}
}
}
return res;
}
//从SD卡读取数据
public static Object loadDataFromSdCard(String path, String file) {
Object obj = null;
FileInputStream fis = null;
ObjectInputStream ois = null;
if (Environment.getExternalStorageState() != null) {
try {
fis = new FileInputStream("/sdcard/" + path + "/" + file
+ ".txt");
ois = new ObjectInputStream(fis);
obj = ois.readObject();
} catch (FileNotFoundException e) {
obj = null;
e.printStackTrace();
} catch (IOException e) {
obj = null;
e.printStackTrace();
} catch (ClassNotFoundException e) {
obj = null;
e.printStackTrace();
} finally {
try {
ois.close();
fis.close();
} catch (Exception e) {
obj = null;
e.printStackTrace();
}
}
}
return obj;
}
//将数据保存到手机内存中
public static String saveDataToLocate(Context context, String file,
Object object) {
if(file != null && !file.equals("") && file.charAt(0) != '_'){
file = "_" + file;
}
String res = null;
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = context.openFileOutput(file, Activity.MODE_PRIVATE);
oos = new ObjectOutputStream(fos);
oos.writeObject(object);
System.out.println(fos + "fos");
System.out.println(oos + "oos");
} catch (FileNotFoundException e) {
res = "没有找到文件";
e.printStackTrace();
} catch (IOException e) {
res = "没有数据";
e.printStackTrace();
} finally {
try {
oos.close();
fos.close();
res = "保存成功";
} catch (IOException e) {
res = "没有数据";
e.printStackTrace();
}
}
return res;
}
//将数据从手机内存中读出来
public static Object loadDataFromLocate(Context context,String file) {
if(file != null && !file.equals("") && file.charAt(0) != '_'){
file = "_" + file;
}
Object obj = null;
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = context.openFileInput(file);
ois = new ObjectInputStream(fis);
obj = ois.readObject();
} catch (FileNotFoundException e) {
obj = null;
System.out.println("文件没找到------>"+e.toString());
e.printStackTrace();
} catch (IOException e) {
obj = null;
System.out.println("输入输出错误------>"+e.toString());
e.printStackTrace();
} catch (ClassNotFoundException e) {
obj = null;
System.out.println("类型转换错误------>"+e.toString());
e.printStackTrace();
}catch (Exception e) {
obj = null;
System.out.println("异常------>"+e.toString());
e.printStackTrace();
} finally {
try {
ois.close();
fis.close();
} catch (Exception e) {
obj = null;
e.printStackTrace();
}
}
return obj;
}
public String[] getKeys() {
return keys;
}
public static void setKeys(Object...args) {
keys = new String[args.length];
for(int i=0;i<args.length;i++){
keys[i] = (String) args[i];
}
}
public static String[] getValues() {
return values;
}
public static void setValues(Object...args) {
values = new String[args.length];
for(int i=0;i<args.length;i++){
values[i] = (String) args[i];
}
}
//����vkey1
public static String getStr(){
String vkey = "";
//vkey = "api_key=" + Const.API_KEY;
for(int i=0;i<keys.length;i++){
vkey =vkey + "&" + keys[i] +"="+ values[i];
}
vkey = vkey.substring(1);
String vkey1 = vkey;
vkey = vkey + Const.API_SECRET;
System.out.println("vkey--->" + vkey);
vkey1 = vkey1 + "&access_token=" + MD5(vkey);
System.out.println(vkey1);
return vkey1;
}
//MD5加密
public static String MD5(String inStr) {
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (Exception e) {
//System.out.println(e.toString());
e.printStackTrace();
return "";
}
char[] charArray = inStr.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++)
byteArray[i] = (byte) charArray[i];
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16)
hexValue.append("0");
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
public static String getJsonDataFromURLByPost(String path,String params) throws SocketTimeoutException, UnknownHostException {
//����һ��URL����
// HttpURLConnection urlCon = null;
BufferedReader reader = null ;
String str = "";
try {
// URL url = new URL(path);
// urlCon = (HttpURLConnection) url.openConnection();
// urlCon.setDoOutput(true);
// urlCon.setDoInput(true);
// urlCon.setRequestMethod("POST");
// urlCon.setUseCaches(false);
// urlCon.setInstanceFollowRedirects(true);
// urlCon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// urlCon.connect();
HttpClient httpClient = NetworkProtocols.getInstance().getHttpClient();
HttpPost httpPost = new HttpPost(path);
ByteArrayEntity stringEntity = new ByteArrayEntity(params.getBytes());
stringEntity.setContentType("application/x-www-form-urlencoded");
httpPost.setEntity(stringEntity);
HttpResponse response = httpClient.execute(httpPost);
// DataOutputStream out = new DataOutputStream(urlCon.getOutputStream());
//
// out.writeBytes(params);
//
// out.flush();
// out.close();
reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
String temp = "";
while((temp=reader.readLine())!=null){
str += (temp + "\n");
}
httpClient.getConnectionManager().shutdown();
}catch(SocketTimeoutException ste){
Log.e("��ʱ", "��ʱ��");
throw ste;
}catch(UnknownHostException h){
Log.e("��·", "���粻��ͨ");
throw h;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(reader!=null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
// urlCon.disconnect();
}
Log.d("json", "activityjson--->" + str);
return str;
}
//post�ύ����
public static String sendString(String str, String urlString) throws IOException{
DataInputStream dis = null;
String readUrl = "";
try {
// URL url = new URL(urlString);
// HttpURLConnection urlConn = (HttpURLConnection) url
// .openConnection();
// urlConn.setRequestMethod("POST");
// urlConn.setDoOutput(true);
// urlConn.setDoInput(true);
// OutputStream os = urlConn.getOutputStream();
// os.write(str.getBytes());
HttpClient httpClient = NetworkProtocols.getInstance().getHttpClient();
HttpPost httpPost = new HttpPost(urlString);
StringEntity stringEntity = new StringEntity(str, "UTF-8");
httpPost.setEntity(stringEntity);
HttpResponse response = httpClient.execute(httpPost);
dis = new DataInputStream(response.getEntity().getContent());
readUrl = dis.readLine();
dis.close();
// os.close();
httpClient.getConnectionManager().shutdown();
} catch (MalformedURLException e) {
e.printStackTrace();
}
return readUrl;
}
public static String saveBitmapToSdCard(String path,String name,Bitmap bitmap) {
String res = null;
FileOutputStream fos = null;
if (Environment.getExternalStorageState() != null) {
try {
File p = new File("/sdcard/" + "quanleimu"); // 创建目录
File s = new File("/sdcard/" + "quanleimu" + "/" + path); // 创建目录
File f = new File("/sdcard/" + "quanleimu" + "/" + path + "/" + name + ".png"); // 创建文件
if (!p.exists()) {
p.mkdir();
}
if (!s.exists()) {
s.mkdir();
}
if (!f.exists()) {
f.createNewFile();
}
fos = new FileOutputStream(f);
bitmap.compress(CompressFormat.JPEG, 100, fos);
fos.close();
res = f.getAbsolutePath();
} catch (FileNotFoundException e) {
res = "没有找到文件";
e.printStackTrace();
} catch (Exception e) {
res = "SD卡未安装";
e.printStackTrace();
}
}else{
res = "无SD卡";
}
return res;
}
public static List<Bitmap> loadBitmapFromSdCard(String path,String name) {
List<Bitmap> b = new ArrayList<Bitmap>();
File file = new File("/sdcard/"+"quanleimu/"+path);
if (file != null) {
File[] files = file.listFiles();
if (files != null) {
for (File f : files) {
if(f.getAbsolutePath().contains(name)){
BitmapFactory.Options o = new BitmapFactory.Options();
o.inPurgeable = true;
b.add(BitmapFactory.decodeFile(f.getPath(), o));
}
}
}
}
b = replaceList(b);
return b;
}
public static List<Bitmap> replaceList(List<Bitmap> bit) {
List<Bitmap> b = new ArrayList<Bitmap>();
for (int i = bit.size() - 1; i > -1; i--) {
b.add(bit.get(i));
}
return b;
}
//下载图片
public static Bitmap getImage(String strURL)throws OutOfMemoryError{
Log.d("img", strURL);
Bitmap img = null;
URLConnection conn = null;
try {
URL url = new URL(strURL);
conn = (URLConnection) url.openConnection();
BitmapFactory.Options o = new BitmapFactory.Options();
o.inPurgeable = true;
Log.e("o", o.toString());
img = BitmapFactory.decodeStream(conn.getInputStream(), null, o);
}
catch (Exception e) {
img = null;
e.printStackTrace();
//conn.disconnect();
}
return img;
}
//将bitmap转成流存到file里面
public static void saveImage2File(Context context,Bitmap bmp,String fileName)
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bos);
byte[] file = bos.toByteArray();
FileOutputStream fos = null;
try {
fos = context.openFileOutput(fileName, Activity.MODE_PRIVATE);
fos.write(file);
System.out.println("存储成功");
fos.close();
} catch (FileNotFoundException e) {
System.out.println("FileNotFoundException ---- >" + e.toString());
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOException ---- >" + e.toString());
e.printStackTrace();
}
}
//将流转成bitmap里面
public static Bitmap getBitmapFromInputstream(Context context,String fileName)
{
Bitmap bmp = null;
FileInputStream fis = null;
byte[] aa = null;
try {
fis = context.openFileInput(fileName);
aa = new byte[fis.available()];
fis.read(aa);
} catch (FileNotFoundException e) {
fis = null;
System.out.println("没找到文件");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if(fis == null)
{
bmp = null;
}
else
{
// bmp = BitmapFactory.decodeStream(fis);
BitmapFactory.Options o = new BitmapFactory.Options();
o.inPurgeable = true;
bmp = BitmapFactory.decodeByteArray(aa, 0, aa.length, o);
}
return bmp;
}
//手机分辨率宽
public static int getWidth(Activity activity){
Display display = activity.getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int a = 0;
if(width == 240)
{
a = 1;
}
else if(width == 320)
{
a = 2;
}
else if(width == 480)
{
a = 3;
}
else if(width == 540)
{
a = 4;
}
else if(width == 640)
{
a = 5;
}else{
a = 5;
}
return a;
}
public static int getWidthByContext(Context context){
Display display = ((Activity) context).getWindowManager().getDefaultDisplay();
int width = display.getWidth();
// int a = 0;
// if(width == 240)
// {
// a = 1;
// }
// else if(width == 320)
// {
// a = 2;
// }
// else if(width == 480)
// {
// a = 3;
// }
// else if(width == 540)
// {
// a = 4;
// }
// else if(width == 640)
// {
// a = 5;
// }
return width;
}
public static int getHeightByContext(Context context){
Display display = ((Activity) context).getWindowManager().getDefaultDisplay();
int height = display.getHeight();
// int a = 0;
// if(width == 240)
// {
// a = 1;
// }
// else if(width == 320)
// {
// a = 2;
// }
// else if(width == 480)
// {
// a = 3;
// }
// else if(width == 540)
// {
// a = 4;
// }
// else if(width == 640)
// {
// a = 5;
// }
return height;
}
//获得手机屏幕焦点
public static Point getSrccenPoint(Activity activity){
Display display = activity.getWindowManager().getDefaultDisplay();
return new Point(display.getWidth(), display.getHeight());
}
public static Bitmap newBitmap(Bitmap b, int w, int h)
{
float scaleWidth = 0;
float scaleHeight = h;
int width = b.getWidth();
int height = b.getHeight();
if (w == h)
{
int minValue = Math.min(b.getWidth(), b.getHeight());
if (minValue >= w)
{
float ratio = (float) w / (float) minValue;
scaleWidth = ratio;
scaleHeight = ratio;
}
else
{
minValue = Math.max(b.getWidth(), b.getHeight());
float ratio = (float) w / (float) minValue;
scaleWidth = ratio;
scaleHeight = ratio;
}
}
else
{
scaleWidth = ((float) w) / width;
scaleHeight = ((float) h) / height;
}
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);// ����
return Bitmap.createBitmap(b, 0, 0, width, height, matrix, true);
}
//图片旋转
public static Bitmap rotate(Bitmap b, int degrees) {
if (degrees != 0 && b != null) {
Matrix m = new Matrix();
m.setRotate(degrees);
try {
Bitmap b2 = Bitmap.createBitmap(b, 0, 0, b.getWidth(), b
.getHeight(), m, true);
if (b != b2) {
b = b2;
}
} catch (OutOfMemoryError ex) {
ex.printStackTrace();
}
}
return b;
}
//һ����ת
public static List<Bitmap> rotateList(List<Bitmap> bitmaps) {
List<Bitmap> bits = new ArrayList<Bitmap>();
for(Bitmap b : bitmaps){
bits.add(Util.rotate(b, -90));
}
return bits;
}
public static List<Bitmap> newBitmapList(List<Bitmap> bitmaps,Activity activity) {
List<Bitmap> bits = new ArrayList<Bitmap>();
for(Bitmap b : bitmaps){
if(Util.getWidth(activity)==1){
bits.add(Util.newBitmap(b, 90, 90));
}else if(Util.getWidth(activity)== 2){
bits.add(Util.newBitmap(b, 135, 135));
}
else if(Util.getWidth(activity)== 3){
bits.add(Util.newBitmap(b, 60, 60));
}
else if(Util.getWidth(activity)== 4){
bits.add(Util.newBitmap(b, 160, 160));
}
else if(Util.getWidth(activity)== 5){
bits.add(Util.newBitmap(b, 180, 180));
}
}
return bits;
}
public static Bitmap scaleBitmap(Bitmap src, int outputX, int outputY, int leftMask, int topMask, int rightMask, int bottomMask){
Bitmap toRet = null;
BitmapFactory.Options o = new BitmapFactory.Options();
o.inPurgeable = true;
if(src.getWidth() > outputX){
Bitmap scaledBmp = newBitmap(src, outputX, (int)((((float)outputX) / src.getWidth()) * src.getHeight()));
if(outputY <= scaledBmp.getHeight()) return scaledBmp;
- Bitmap lineBk = Bitmap.createBitmap(outputX, 1, src.getConfig());
+ Bitmap lineBk = Bitmap.createBitmap(outputX, 1, Config.ARGB_4444);
Canvas canvas = new Canvas(lineBk);
Rect srcRc = new Rect();
srcRc.left = 0;
srcRc.top = topMask;
srcRc.right = outputX;
srcRc.bottom = topMask + 1;
Rect destRc = new Rect();
destRc.left = 0;
destRc.top = 0;
destRc.right = outputX;
destRc.bottom = 1;
canvas.drawBitmap(scaledBmp, srcRc, destRc, new Paint());
- toRet = Bitmap.createBitmap(outputX, outputY, src.getConfig());
+ toRet = Bitmap.createBitmap(outputX, outputY, Config.ARGB_4444);
canvas = new Canvas(toRet);
srcRc.left = 0;
srcRc.top = 0;
srcRc.right = outputX;
srcRc.bottom = topMask;
destRc.left = srcRc.left;
destRc.right = srcRc.right;
destRc.top = srcRc.top;
destRc.bottom = srcRc.bottom;
canvas.drawBitmap(scaledBmp, srcRc, destRc, new Paint());
srcRc.top = topMask;
srcRc.bottom = topMask + 1;
for(int i = 0; i < outputY - topMask - bottomMask; ++ i){
destRc.top = i + topMask;
destRc.bottom = i + topMask + 1;
canvas.drawBitmap(scaledBmp, srcRc, destRc, new Paint());
}
srcRc.top = scaledBmp.getHeight() - bottomMask;
srcRc.bottom = scaledBmp.getHeight();
destRc.top = outputY - bottomMask;
destRc.bottom = outputY;
canvas.drawBitmap(scaledBmp, srcRc, destRc, new Paint());
lineBk.recycle();
scaledBmp.recycle();
}
else
{
Bitmap scaledBmp = newBitmap(src, (int)((((float)outputY) / src.getHeight()) * src.getWidth()), outputY);
Bitmap lineBk = Bitmap.createBitmap(1, outputY, src.getConfig());
Canvas canvas = new Canvas(lineBk);
Rect srcRc = new Rect();
srcRc.left = leftMask;
srcRc.top = 0;
srcRc.right = leftMask + 1;
srcRc.bottom = scaledBmp.getHeight();
Rect destRc = new Rect();
destRc.left = 0;
destRc.top = 0;
destRc.right = 1;
destRc.bottom = outputY;
canvas.drawBitmap(scaledBmp, srcRc, destRc, new Paint());
toRet = Bitmap.createBitmap(outputX, outputY, src.getConfig());
canvas = new Canvas(toRet);
srcRc.left = 0;
srcRc.top = 0;
srcRc.right = leftMask;
srcRc.bottom = scaledBmp.getHeight();
destRc.left = 0;
destRc.right = leftMask;
destRc.top = 0;
destRc.bottom = outputY;
canvas.drawBitmap(scaledBmp, srcRc, destRc, new Paint());
srcRc.left = leftMask;
srcRc.right = leftMask + 1;
for(int i = 0; i < outputX - leftMask - rightMask; ++ i){
destRc.left = i + leftMask;
destRc.right = i + leftMask + 1;
canvas.drawBitmap(scaledBmp, srcRc, destRc, new Paint());
}
srcRc.left = scaledBmp.getWidth() - bottomMask;
srcRc.right = scaledBmp.getWidth();
destRc.left = outputX - rightMask;
destRc.right = outputX;
canvas.drawBitmap(scaledBmp, srcRc, destRc, new Paint());
lineBk.recycle();
scaledBmp.recycle();
}
return toRet;
}
//保存数据手机内存
public static void saveToData(Context ctx , String title,String key,String value){
SharedPreferences.Editor se = ctx.getSharedPreferences(title, Context.MODE_WORLD_WRITEABLE).edit();
se.putString(key, value);
se.commit();
}
//获取数据从手机内从
public static String getFromData(Context ctx , String title,String key){
SharedPreferences se = ctx.getSharedPreferences(title, Context.MODE_WORLD_READABLE);
if(se==null){
return null;
}
String value = se.getString(key, "");
if(value.equals("")){
return null;
}else{
return value;
}
}
/**
* recycle all the bitmaps in the list
* @param listBm
*/
public static void recycle(List<Bitmap> listBm){
for(int i=0;i<listBm.size();i++){
if(listBm!=null&&listBm.get(i)!=null&&!listBm.get(i).isRecycled()){
listBm.get(i).recycle();
}
}
}
//根据经纬度获取地址
public static String GetAddr(double latitude, double longitude) {
String addr = "";
String url = String.format(
"http://ditu.google.cn/maps/geo?output=csv&key=abcdef&q=%s,%s",
latitude, longitude);
URL myURL = null;
URLConnection httpsConn = null;
try {
myURL = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
return null;
}
try {
httpsConn = (URLConnection) myURL.openConnection();
if (httpsConn != null) {
InputStreamReader insr = new InputStreamReader(
httpsConn.getInputStream(), "UTF-8");
BufferedReader br = new BufferedReader(insr);
String data = null;
if ((data = br.readLine()) != null) {
String[] retList = data.split(",");
if (retList.length > 2 && ("200".equals(retList[0]))) {
addr = retList[2];
addr = addr.replace("/", "");
} else {
addr = "";
}
}
insr.close();
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
return addr;
}
static public boolean JadgeConnection (Context context)throws Exception
{
boolean a = false;
ConnectivityManager connManager = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
State mobile = connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState();
State wifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState();
if(mobile.toString().equals("CONNECTED") || wifi.toString().equals("CONNECTED"))
{
a = true;
}
else
{
a = false;
}
return a;
}
//GSM和CDMA手机定位
// private boolean goGsm = true;
// private boolean running = true;
// public class NewThread extends Thread{
// private long time = 0;
// public void run(){
// time = System.currentTimeMillis();
// while(running){
// if(System.currentTimeMillis() - time >= 10000){
// break;
// }
// }
// if(running){
// goGsm = false;
// geoLat = 31.1984;
// geoLon = 121.436475;
// myHandler.sendEmptyMessage(1);
// }
// }
// }
// public void ddd(){
// Thread thread = new Thread(){
// public void run(){
// try {
// DefaultHttpClient client = new DefaultHttpClient();
// HttpPost post = new HttpPost("http://www.google.com/loc/json");//http://www.google.com/glm/mmap");//
//
// JSONObject holder = new JSONObject();
// holder.put("version", "1.1.0");
// holder.put("request_address", true);
// holder.put("address_language", "en-us");
//
// JSONObject data ;
// JSONArray array = new JSONArray();
// data = new JSONObject();
// data.put("cell_id", c.getCid()); // 9457, 8321,8243
// data.put("location_area_code", c.getLac());// 28602
// data.put("mobile_country_code", ss.substring(0, 3));// 208
// data.put("mobile_network_code", ss.substring(3, 5));// 0
// data.put("age", 0);
////
// array.put(data);
// for(int i =0;i<(count<2?count:2);i++){
// data = new JSONObject();
// data.put("cell_id", ci[i]); // 9457, 8321,8243
// data.put("location_area_code", lac[i]);// 28602
// data.put("mobile_country_code", ss.substring(0, 3));// 208
// data.put("mobile_network_code", ss.substring(3, 5));// 0
// data.put("age", 0);
// array.put(data);
// }
// holder.put("cell_towers", array);
////
// StringEntity se = new StringEntity(holder.toString());
// Log.e("Location send",holder.toString());
// post.setEntity(se);
// HttpResponse resp = client.execute(post);
//
// HttpEntity entity = resp.getEntity();
//
// BufferedReader br = new BufferedReader(new InputStreamReader(entity
// .getContent()));
// StringBuffer sb = new StringBuffer();
// String result = br.readLine();
// while (result != null) {
// Log.e("Locaiton reseive", result);
// sb.append(result);
// result = br.readLine();
// }
// result_location = sb.toString();
//
//
// data = new JSONObject(sb.toString());
// data = (JSONObject) data.get("location");
// geoLat = (Double) data.get("latitude");
// geoLon = (Double) data.get("longitude");
// if(geoLat != 0.0 && geoLon != 0.0 && geoLat != 0 && geoLon != 0)
// {
// running = false;
// if(goGsm == true)
// {
// myHandler.sendEmptyMessage(0);
// }
// }
// else
// {
// running = false;
// geoLat = 31.1984;
// geoLon = 121.436475;
// if(goGsm == true)
// {
// myHandler.sendEmptyMessage(1);
// }
// }
// }
// catch (ClientProtocolException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
// catch (JSONException e) {
// e.printStackTrace();
//// loc.setText("");
// }
// }
// };
// thread.start();
// }
}
| false | true | public static Bitmap scaleBitmap(Bitmap src, int outputX, int outputY, int leftMask, int topMask, int rightMask, int bottomMask){
Bitmap toRet = null;
BitmapFactory.Options o = new BitmapFactory.Options();
o.inPurgeable = true;
if(src.getWidth() > outputX){
Bitmap scaledBmp = newBitmap(src, outputX, (int)((((float)outputX) / src.getWidth()) * src.getHeight()));
if(outputY <= scaledBmp.getHeight()) return scaledBmp;
Bitmap lineBk = Bitmap.createBitmap(outputX, 1, src.getConfig());
Canvas canvas = new Canvas(lineBk);
Rect srcRc = new Rect();
srcRc.left = 0;
srcRc.top = topMask;
srcRc.right = outputX;
srcRc.bottom = topMask + 1;
Rect destRc = new Rect();
destRc.left = 0;
destRc.top = 0;
destRc.right = outputX;
destRc.bottom = 1;
canvas.drawBitmap(scaledBmp, srcRc, destRc, new Paint());
toRet = Bitmap.createBitmap(outputX, outputY, src.getConfig());
canvas = new Canvas(toRet);
srcRc.left = 0;
srcRc.top = 0;
srcRc.right = outputX;
srcRc.bottom = topMask;
destRc.left = srcRc.left;
destRc.right = srcRc.right;
destRc.top = srcRc.top;
destRc.bottom = srcRc.bottom;
canvas.drawBitmap(scaledBmp, srcRc, destRc, new Paint());
srcRc.top = topMask;
srcRc.bottom = topMask + 1;
for(int i = 0; i < outputY - topMask - bottomMask; ++ i){
destRc.top = i + topMask;
destRc.bottom = i + topMask + 1;
canvas.drawBitmap(scaledBmp, srcRc, destRc, new Paint());
}
srcRc.top = scaledBmp.getHeight() - bottomMask;
srcRc.bottom = scaledBmp.getHeight();
destRc.top = outputY - bottomMask;
destRc.bottom = outputY;
canvas.drawBitmap(scaledBmp, srcRc, destRc, new Paint());
lineBk.recycle();
scaledBmp.recycle();
}
else
{
Bitmap scaledBmp = newBitmap(src, (int)((((float)outputY) / src.getHeight()) * src.getWidth()), outputY);
Bitmap lineBk = Bitmap.createBitmap(1, outputY, src.getConfig());
Canvas canvas = new Canvas(lineBk);
Rect srcRc = new Rect();
srcRc.left = leftMask;
srcRc.top = 0;
srcRc.right = leftMask + 1;
srcRc.bottom = scaledBmp.getHeight();
Rect destRc = new Rect();
destRc.left = 0;
destRc.top = 0;
destRc.right = 1;
destRc.bottom = outputY;
canvas.drawBitmap(scaledBmp, srcRc, destRc, new Paint());
toRet = Bitmap.createBitmap(outputX, outputY, src.getConfig());
canvas = new Canvas(toRet);
srcRc.left = 0;
srcRc.top = 0;
srcRc.right = leftMask;
srcRc.bottom = scaledBmp.getHeight();
destRc.left = 0;
destRc.right = leftMask;
destRc.top = 0;
destRc.bottom = outputY;
canvas.drawBitmap(scaledBmp, srcRc, destRc, new Paint());
srcRc.left = leftMask;
srcRc.right = leftMask + 1;
for(int i = 0; i < outputX - leftMask - rightMask; ++ i){
destRc.left = i + leftMask;
destRc.right = i + leftMask + 1;
canvas.drawBitmap(scaledBmp, srcRc, destRc, new Paint());
}
srcRc.left = scaledBmp.getWidth() - bottomMask;
srcRc.right = scaledBmp.getWidth();
destRc.left = outputX - rightMask;
destRc.right = outputX;
canvas.drawBitmap(scaledBmp, srcRc, destRc, new Paint());
lineBk.recycle();
scaledBmp.recycle();
}
return toRet;
}
| public static Bitmap scaleBitmap(Bitmap src, int outputX, int outputY, int leftMask, int topMask, int rightMask, int bottomMask){
Bitmap toRet = null;
BitmapFactory.Options o = new BitmapFactory.Options();
o.inPurgeable = true;
if(src.getWidth() > outputX){
Bitmap scaledBmp = newBitmap(src, outputX, (int)((((float)outputX) / src.getWidth()) * src.getHeight()));
if(outputY <= scaledBmp.getHeight()) return scaledBmp;
Bitmap lineBk = Bitmap.createBitmap(outputX, 1, Config.ARGB_4444);
Canvas canvas = new Canvas(lineBk);
Rect srcRc = new Rect();
srcRc.left = 0;
srcRc.top = topMask;
srcRc.right = outputX;
srcRc.bottom = topMask + 1;
Rect destRc = new Rect();
destRc.left = 0;
destRc.top = 0;
destRc.right = outputX;
destRc.bottom = 1;
canvas.drawBitmap(scaledBmp, srcRc, destRc, new Paint());
toRet = Bitmap.createBitmap(outputX, outputY, Config.ARGB_4444);
canvas = new Canvas(toRet);
srcRc.left = 0;
srcRc.top = 0;
srcRc.right = outputX;
srcRc.bottom = topMask;
destRc.left = srcRc.left;
destRc.right = srcRc.right;
destRc.top = srcRc.top;
destRc.bottom = srcRc.bottom;
canvas.drawBitmap(scaledBmp, srcRc, destRc, new Paint());
srcRc.top = topMask;
srcRc.bottom = topMask + 1;
for(int i = 0; i < outputY - topMask - bottomMask; ++ i){
destRc.top = i + topMask;
destRc.bottom = i + topMask + 1;
canvas.drawBitmap(scaledBmp, srcRc, destRc, new Paint());
}
srcRc.top = scaledBmp.getHeight() - bottomMask;
srcRc.bottom = scaledBmp.getHeight();
destRc.top = outputY - bottomMask;
destRc.bottom = outputY;
canvas.drawBitmap(scaledBmp, srcRc, destRc, new Paint());
lineBk.recycle();
scaledBmp.recycle();
}
else
{
Bitmap scaledBmp = newBitmap(src, (int)((((float)outputY) / src.getHeight()) * src.getWidth()), outputY);
Bitmap lineBk = Bitmap.createBitmap(1, outputY, src.getConfig());
Canvas canvas = new Canvas(lineBk);
Rect srcRc = new Rect();
srcRc.left = leftMask;
srcRc.top = 0;
srcRc.right = leftMask + 1;
srcRc.bottom = scaledBmp.getHeight();
Rect destRc = new Rect();
destRc.left = 0;
destRc.top = 0;
destRc.right = 1;
destRc.bottom = outputY;
canvas.drawBitmap(scaledBmp, srcRc, destRc, new Paint());
toRet = Bitmap.createBitmap(outputX, outputY, src.getConfig());
canvas = new Canvas(toRet);
srcRc.left = 0;
srcRc.top = 0;
srcRc.right = leftMask;
srcRc.bottom = scaledBmp.getHeight();
destRc.left = 0;
destRc.right = leftMask;
destRc.top = 0;
destRc.bottom = outputY;
canvas.drawBitmap(scaledBmp, srcRc, destRc, new Paint());
srcRc.left = leftMask;
srcRc.right = leftMask + 1;
for(int i = 0; i < outputX - leftMask - rightMask; ++ i){
destRc.left = i + leftMask;
destRc.right = i + leftMask + 1;
canvas.drawBitmap(scaledBmp, srcRc, destRc, new Paint());
}
srcRc.left = scaledBmp.getWidth() - bottomMask;
srcRc.right = scaledBmp.getWidth();
destRc.left = outputX - rightMask;
destRc.right = outputX;
canvas.drawBitmap(scaledBmp, srcRc, destRc, new Paint());
lineBk.recycle();
scaledBmp.recycle();
}
return toRet;
}
|
diff --git a/src/uk/org/smithfamily/utils/normaliser/Process.java b/src/uk/org/smithfamily/utils/normaliser/Process.java
index dcd9224..144abf4 100644
--- a/src/uk/org/smithfamily/utils/normaliser/Process.java
+++ b/src/uk/org/smithfamily/utils/normaliser/Process.java
@@ -1,916 +1,916 @@
package uk.org.smithfamily.utils.normaliser;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import org.apache.commons.lang3.StringUtils;
import uk.org.smithfamily.mslogger.ecuDef.Constant;
import uk.org.smithfamily.utils.normaliser.curveeditor.ColumnLabel;
import uk.org.smithfamily.utils.normaliser.curveeditor.CurveDefinition;
import uk.org.smithfamily.utils.normaliser.curveeditor.CurveTracker;
import uk.org.smithfamily.utils.normaliser.curveeditor.LineLabel;
import uk.org.smithfamily.utils.normaliser.curveeditor.XAxis;
import uk.org.smithfamily.utils.normaliser.tableeditor.GridHeight;
import uk.org.smithfamily.utils.normaliser.tableeditor.GridOrient;
import uk.org.smithfamily.utils.normaliser.tableeditor.PreProcessor;
import uk.org.smithfamily.utils.normaliser.tableeditor.TableDefinition;
import uk.org.smithfamily.utils.normaliser.tableeditor.TableTracker;
import uk.org.smithfamily.utils.normaliser.tableeditor.UpDownLabel;
import uk.org.smithfamily.utils.normaliser.tableeditor.XBins;
import uk.org.smithfamily.utils.normaliser.tableeditor.YBins;
import uk.org.smithfamily.utils.normaliser.tableeditor.ZBins;
public class Process
{
private static String deBinary(String group)
{
Matcher binNumber = Patterns.binary.matcher(group);
if (!binNumber.matches())
{
return group;
}
else
{
String binNum = binNumber.group(2);
int num = Integer.parseInt(binNum, 2);
String expr = binNumber.group(1) + num + binNumber.group(3);
return deBinary(expr);
}
}
private static String removeComments(String line)
{
line += "; junk";
line = StringUtils.trim(line).split(";")[0];
line = line.trim();
return line;
}
private static String convertC2JavaBoolean(String expression)
{
Matcher matcher = Patterns.booleanConvert.matcher(expression);
StringBuffer result = new StringBuffer(expression.length());
while (matcher.find())
{
matcher.appendReplacement(result, "");
result.append(matcher.group(1) + " ? 1 : 0)");
}
matcher.appendTail(result);
expression = result.toString();
return expression;
}
private static boolean isFloatingExpression(ECUData ecuData,
String expression)
{
boolean result = expression.contains(".");
if (result)
{
return result;
}
for (String var : ecuData.getRuntimeVars().keySet())
{
if (expression.contains(var)
&& ecuData.getRuntimeVars().get(var).equals("double"))
{
result = true;
}
}
for (String var : ecuData.getEvalVars().keySet())
{
if (expression.contains(var)
&& ecuData.getEvalVars().get(var).equals("double"))
{
result = true;
}
}
return result;
}
static void processExpr(ECUData ecuData, String line)
{
String definition = null;
line = removeComments(line);
line = StringUtils.replace(line, "timeNow", "timeNow()");
Matcher bitsM = Patterns.bits.matcher(line);
Matcher scalarM = Patterns.scalar.matcher(line);
Matcher exprM = Patterns.expr.matcher(line);
Matcher ochGetCommandM = Patterns.ochGetCommand.matcher(line);
Matcher ochBlockSizeM = Patterns.ochBlockSize.matcher(line);
if (bitsM.matches())
{
String name = bitsM.group(1);
String offset = bitsM.group(3);
String start = bitsM.group(4);
String end = bitsM.group(5);
String ofs = "0";
if (end.contains("+"))
{
String[] parts = end.split("\\+");
end = parts[0];
ofs = parts[1];
}
definition = (name + " = MSUtils.getBits(ochBuffer," + offset + ","
+ start + "," + end + "," + ofs + ");");
ecuData.getRuntime().add(definition);
ecuData.getRuntimeVars().put(name, "int");
}
else if (scalarM.matches())
{
String name = scalarM.group(1);
if (constantDefined(ecuData, name))
{
name += "RT";
}
String dataType = scalarM.group(2);
String offset = scalarM.group(3);
String scalingRaw = scalarM.group(4);
String[] scaling = scalingRaw.split(",");
String scale = scaling[1].trim();
String numOffset = scaling[2].trim();
if (Double.parseDouble(scale) != 1)
{
ecuData.getRuntimeVars().put(name, "double");
} else
{
ecuData.getRuntimeVars().put(name, "int");
}
definition = Output.getScalar("ochBuffer", ecuData.getRuntimeVars()
.get(name), name, dataType, offset, scale, numOffset);
ecuData.setFingerprintSource(ecuData.getFingerprintSource()
+ definition);
ecuData.getRuntime().add(definition);
}
else if (exprM.matches())
{
String name = exprM.group(1);
if ("pwma_load".equals(name))
{
// Hook to hang a break point on
@SuppressWarnings("unused")
int x = 1;
}
String expression = deBinary(exprM.group(2).trim());
Matcher ternaryM = Patterns.ternary.matcher(expression);
if (ternaryM.matches())
{
// System.out.println("BEFORE : " + expression);
String test = ternaryM.group(1);
String values = ternaryM.group(2);
if (StringUtils.containsAny(test, "<>!="))
{
expression = "(" + test + ") ? " + values;
} else
{
expression = "((" + test + ") != 0 ) ? " + values;
}
// System.out.println("AFTER : " + expression + "\n");
}
if (expression.contains("*") && expression.contains("=="))
{
expression = convertC2JavaBoolean(expression);
}
definition = name + " = (" + expression + ");";
// If the expression contains a division, wrap it in a try/catch to
// avoid division by zero
if (expression.contains("/"))
{
definition = "try\n" + Output.TAB + Output.TAB + "{\n"
+ Output.TAB + Output.TAB + Output.TAB + definition
+ "\n" + Output.TAB + Output.TAB + "}\n" + Output.TAB
+ Output.TAB + "catch (ArithmeticException e) {\n"
+ Output.TAB + Output.TAB + Output.TAB + name
+ " = 0;\n" + Output.TAB + Output.TAB + "}";
}
ecuData.getRuntime().add(definition);
if (isFloatingExpression(ecuData, expression))
{
ecuData.getEvalVars().put(name, "double");
}
else
{
ecuData.getEvalVars().put(name, "int");
}
}
else if (ochGetCommandM.matches())
{
String och = ochGetCommandM.group(1);
if (och.length() > 1)
{
och = Output.HexStringToBytes(ecuData, och, 0, 0, 0);
} else
{
och = "'" + och + "'";
}
ecuData.setOchGetCommandStr("byte [] ochGetCommand = new byte[]{"
+ och + "};");
}
else if (ochBlockSizeM.matches())
{
ecuData.setOchBlockSizeStr("int ochBlockSize = "
+ ochBlockSizeM.group(1) + ";");
}
else if (line.startsWith("#"))
{
ecuData.getRuntime().add(processPreprocessor(ecuData, line));
}
else if (!StringUtils.isEmpty(line))
{
System.out.println(line);
}
}
/**
* Occasionally we get a collision between the name of a constant and an
* expression. Test for that here.
*
* @param ecuData
* @param name
* @return
*/
private static boolean constantDefined(ECUData ecuData, String name)
{
for (Constant c : ecuData.getConstants())
{
if (c.getName().equals(name))
{
return true;
}
}
return false;
}
static void processLogEntry(ECUData ecuData, String line)
{
line = removeComments(line);
Matcher logM = Patterns.log.matcher(line);
if (logM.matches())
{
String header = logM.group(2);
String variable = logM.group(1);
if ("double".equals(ecuData.getRuntimeVars().get(variable)))
{
variable = "round(" + variable + ")";
}
ecuData.getLogHeader().add(
"b.append(\"" + header + "\").append(\"\\t\");");
ecuData.getLogRecord().add(
"b.append(" + variable + ").append(\"\\t\");");
}
else if (line.startsWith("#"))
{
String directive = processPreprocessor(ecuData, line);
ecuData.getLogHeader().add(directive);
ecuData.getLogRecord().add(directive);
}
}
static String processPreprocessor(ECUData ecuData, String line)
{
String filtered;
boolean stripped = false;
filtered = line.replace(" ", " ");
stripped = filtered.equals(line);
while (!stripped)
{
line = filtered;
filtered = line.replace(" ", " ");
stripped = filtered.equals(line);
}
String[] components = line.split(" ");
String flagName = components.length > 1 ? sanitize(components[1]) : "";
if (components[0].equals("#if"))
{
ecuData.getFlags().add(flagName);
return ("if (" + flagName + ")\n {");
}
if (components[0].equals("#elif"))
{
ecuData.getFlags().add(flagName);
return ("}\n else if (" + flagName + ")\n {");
}
if (components[0].equals("#else"))
{
return ("}\n else\n {");
}
if (components[0].equals("#endif"))
{
return ("}");
}
return "";
}
private static String sanitize(String flagName)
{
return StringUtils.replace(flagName, "!", "n");
}
static void processFrontPage(ECUData ecuData, String line)
{
line = removeComments(line);
Matcher dgM = Patterns.defaultGauge.matcher(line);
if (dgM.matches())
{
ecuData.getDefaultGauges().add(dgM.group(1));
}
}
static void processHeader(ECUData ecuData, String line)
{
Matcher queryM = Patterns.queryCommand.matcher(line);
if (queryM.matches())
{
ecuData.setQueryCommandStr("byte[] queryCommand = new byte[]{'"
+ queryM.group(1) + "'};");
return;
}
Matcher sigM = Patterns.signature.matcher(line);
Matcher sigByteM = Patterns.byteSignature.matcher(line);
if (sigM.matches())
{
String tmpsig = sigM.group(1);
if (line.contains("null"))
{
tmpsig += "\\0";
}
ecuData.setClassSignature("\"" + tmpsig + "\"");
ecuData.setSignatureDeclaration("String signature = \"" + tmpsig
+ "\";");
} else if (sigByteM.matches())
{
String b = sigByteM.group(1).trim();
ecuData.setClassSignature("new String(new byte[]{" + b + "})");
ecuData.setSignatureDeclaration("String signature = \"\"+(byte)"
+ b + ";");
}
}
static void processGaugeEntry(ECUData ecuData, String line)
{
line = removeComments(line);
Matcher m = Patterns.gauge.matcher(line);
if (m.matches())
{
String name = m.group(1);
String channel = m.group(2);
String title = m.group(3);
String units = m.group(4);
String lo = m.group(5);
String hi = m.group(6);
String loD = m.group(7);
String loW = m.group(8);
String hiW = m.group(9);
String hiD = m.group(10);
String vd = m.group(11);
String ld = m.group(12);
String g = String
.format("GaugeRegister.INSTANCE.addGauge(new GaugeDetails(\"Gauge\",\"\",\"%s\",\"%s\",%s,\"%s\",\"%s\",%s,%s,%s,%s,%s,%s,%s,%s,45));",
name, channel, channel, title, units, lo, hi, loD,
loW, hiW, hiD, vd, ld);
g = g.replace("{", "").replace("}", "");
String gd = String
.format("<tr><td>Gauge</td><td></td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>",
name, channel, title, units, lo, hi, loD, loW, hiW,
hiD, vd, ld);
ecuData.getGaugeDoc().add(gd);
ecuData.getGaugeDef().add(g);
} else if (line.startsWith("#"))
{
ecuData.getGaugeDef().add(processPreprocessor(ecuData, line));
ecuData.getGaugeDoc()
.add(String
.format("<tr><td colspan=\"12\" id=\"preprocessor\">%s</td></tr>",
line));
}
}
/**
* Process the [Constants] section of the ini file
*
* @param line
*/
static void processConstants(ECUData ecuData, String line)
{
line = removeComments(line);
if (StringUtils.isEmpty(line))
{
return;
}
- if (line.contains("idleadvance_rpmsdelta"))
+ if (line.contains("DI_rpm"))
{
int x=1;
}
if (line.contains("messageEnvelopeFormat"))
{
ecuData.setCRC32Protocol(line.contains("msEnvelope_1.0"));
}
Matcher pageM = Patterns.page.matcher(line);
if (pageM.matches())
{
ecuData.setCurrentPage(Integer.parseInt(pageM.group(1).trim()));
return;
}
Matcher pageSizesM = Patterns.pageSize.matcher(line);
if (pageSizesM.matches())
{
String values = StringUtils.remove(pageSizesM.group(1), ' ');
String[] list = values.split(",");
ecuData.setPageSizes(new ArrayList<String>(Arrays.asList(list)));
}
Matcher pageIdentifersM = Patterns.pageIdentifier.matcher(line);
if (pageIdentifersM.matches())
{
String values = StringUtils.remove(pageIdentifersM.group(1), ' ');
values = StringUtils.remove(values, '"');
String[] list = values.split(",");
ecuData.setPageIdentifiers(new ArrayList<String>(Arrays
.asList(list)));
}
Matcher pageActivateM = Patterns.pageActivate.matcher(line);
if (pageActivateM.matches())
{
String values = StringUtils.remove(pageActivateM.group(1), ' ');
values = StringUtils.remove(values, '"');
String[] list = values.split(",");
ecuData.setPageActivateCommands(new ArrayList<String>(Arrays
.asList(list)));
}
Matcher pageReadCommandM = Patterns.pageReadCommand.matcher(line);
if (pageReadCommandM.matches())
{
String values = StringUtils.remove(pageReadCommandM.group(1), ' ');
values = StringUtils.remove(values, '"');
String[] list = values.split(",");
ecuData.setPageReadCommands(new ArrayList<String>(Arrays.asList(list)));
}
Matcher interWriteDelayM = Patterns.interWriteDelay.matcher(line);
if (interWriteDelayM.matches())
{
ecuData.setInterWriteDelay(Integer.parseInt(interWriteDelayM.group(1).trim()));
return;
}
Matcher pageActivationDelayM = Patterns.pageActivationDelay
.matcher(line);
if (pageActivationDelayM.matches())
{
ecuData.setPageActivationDelayVal(Integer
.parseInt(pageActivationDelayM.group(1).trim()));
return;
}
//To allow for MS2GS27
line=removeCurlyBrackets(line);
Matcher bitsM = Patterns.bits.matcher(line);
Matcher constantM = Patterns.constantScalar.matcher(line);
Matcher constantSimpleM = Patterns.constantSimple.matcher(line);
Matcher constantArrayM = Patterns.constantArray.matcher(line);
if (constantM.matches())
{
String name = constantM.group(1);
String classtype = constantM.group(2);
String type = constantM.group(3);
int offset = Integer.parseInt(constantM.group(4).trim());
String units = constantM.group(5);
String scaleText = constantM.group(6);
String translateText = constantM.group(7);
String lowText = constantM.group(8);
String highText = constantM.group(9);
String digitsText = constantM.group(10);
double scale = !StringUtils.isEmpty(scaleText) ? Double
.parseDouble(scaleText) : 0;
double translate = !StringUtils.isEmpty(translateText) ? Double
.parseDouble(translateText) : 0;
int digits = !StringUtils.isEmpty(digitsText) ? (int) Double
.parseDouble(digitsText) : 0;
if (!ecuData.getConstants().contains(name))
{
Constant c = new Constant(ecuData.getCurrentPage(), name,
classtype, type, offset, "", units, scale, translate,
lowText, highText, digits);
if (scale == 1.0)
{
ecuData.getConstantVars().put(name, "int");
}
else
{
ecuData.getConstantVars().put(name, "double");
}
ecuData.getConstants().add(c);
}
}
else if (constantArrayM.matches())
{
String name = constantArrayM.group(1);
String classtype = constantArrayM.group(2);
String type = constantArrayM.group(3);
int offset = Integer.parseInt(constantArrayM.group(4).trim());
String shape = constantArrayM.group(5);
String units = constantArrayM.group(6);
String scaleText = constantArrayM.group(7);
String translateText = constantArrayM.group(8);
String lowText = constantArrayM.group(9);
String highText = constantArrayM.group(10);
String digitsText = constantArrayM.group(11);
highText = highText.replace("{", "").replace("}", "");
double scale = !StringUtils.isEmpty(scaleText) ? Double
.parseDouble(scaleText) : 0;
double translate = !StringUtils.isEmpty(translateText) ? Double
.parseDouble(translateText) : 0;
int digits = !StringUtils.isEmpty(digitsText) ? (int) Double
.parseDouble(digitsText) : 0;
if (!ecuData.getConstants().contains(name))
{
Constant c = new Constant(ecuData.getCurrentPage(), name,
classtype, type, offset, shape, units, scale,
translate, lowText, highText, digits);
if (shape.contains("x"))
{
ecuData.getConstantVars().put(name, "double[][]");
}
else
{
ecuData.getConstantVars().put(name, "double[]");
}
ecuData.getConstants().add(c);
}
}
else if (constantSimpleM.matches())
{
String name = constantSimpleM.group(1);
String classtype = constantSimpleM.group(2);
String type = constantSimpleM.group(3);
int offset = Integer.parseInt(constantSimpleM.group(4).trim());
String units = constantSimpleM.group(5);
double scale = Double.parseDouble(constantSimpleM.group(6));
double translate = Double.parseDouble(constantSimpleM.group(7));
Constant c = new Constant(ecuData.getCurrentPage(), name,
classtype, type, offset, "", units, scale, translate, "0", "0",
0);
if (scale == 1.0)
{
ecuData.getConstantVars().put(name, "int");
} else
{
ecuData.getConstantVars().put(name, "double");
}
ecuData.getConstants().add(c);
}
else if (bitsM.matches())
{
String name = bitsM.group(1);
String offset = bitsM.group(3);
String start = bitsM.group(4);
String end = bitsM.group(5);
Constant c = new Constant(ecuData.getCurrentPage(), name, "bits",
"", Integer.parseInt(offset.trim()), "[" + start + ":"
+ end + "]", "", 1, 0, "0", "0", 0);
ecuData.getConstantVars().put(name, "int");
ecuData.getConstants().add(c);
}
else if (line.startsWith("#"))
{
String preproc = (processPreprocessor(ecuData, line));
Constant c = new Constant(ecuData.getCurrentPage(), preproc, "",
"PREPROC", 0, "", "", 0, 0, "0", "0", 0);
ecuData.getConstants().add(c);
}
}
private static String removeCurlyBrackets(String line)
{
return line.replaceAll("\\{", "").replaceAll("\\}", "");
}
/**
* Process the [Menu] section of the ini file
*
* @param line
*/
static void processMenu(ECUData ecuData, String line)
{
line = removeComments(line);
if (StringUtils.isEmpty(line))
{
return;
}
Matcher menuDialog = Patterns.menuDialog.matcher(line);
Matcher menu = Patterns.menu.matcher(line);
Matcher subMenu = Patterns.subMenu.matcher(line);
if (menuDialog.matches())
{
// System.out.println("menuDialog Name: " + menuDialog.group(1));
}
else if (menu.matches())
{
// System.out.println("menu Label: " + menu.group(1));
}
else if (subMenu.matches())
{
// System.out.println("subMenu Name: " + subMenu.group(1));
// System.out.println("subMenu Label: " + subMenu.group(3));
// System.out.println("subMenu RandomNumber: " + subMenu.group(5));
// System.out.println("subMenu Expression: " + subMenu.group(7));
}
}
/**
* Process the [TablEditor] section of the ini file
*
* @param line
*/
static void processTableEditor(ECUData ecuData, String line)
{
line = removeComments(line);
if (StringUtils.isEmpty(line))
{
return;
}
Matcher table = Patterns.tablEditorTable.matcher(line);
Matcher xBins = Patterns.tablEditorXBins.matcher(line);
Matcher yBins = Patterns.tablEditorYBins.matcher(line);
Matcher zBins = Patterns.tablEditorZBins.matcher(line);
Matcher upDownLabel = Patterns.tablEditorUpDownLabel.matcher(line);
Matcher gridHeight = Patterns.tablEditorGridHeight.matcher(line);
Matcher gridOrient = Patterns.tablEditorGridOrient.matcher(line);
final List<TableTracker> tableDefs = ecuData.getTableDefs();
TableTracker t = null;
if (tableDefs.size() > 0)
{
t = tableDefs.get(tableDefs.size() - 1);
}
if (t == null)
{
t = new TableTracker();
tableDefs.add(t);
}
if (table.matches())
{
if (t.isDefinitionCompleted())
{
t = new TableTracker();
tableDefs.add(t);
}
TableDefinition td = new TableDefinition(t, table.group(1), table.group(2), table.group(3), table.group(4));
t.addItem(td);
}
else if (xBins.matches())
{
XBins x = new XBins(xBins.group(1), xBins.group(2), xBins.group(4));
t.addItem(x);
}
else if (yBins.matches())
{
YBins y = new YBins(yBins.group(1), yBins.group(2), yBins.group(4));
t.addItem(y);
}
else if (zBins.matches())
{
ZBins z = new ZBins(zBins.group(1));
t.addItem(z);
}
else if (upDownLabel.matches())
{
UpDownLabel l = new UpDownLabel(upDownLabel.group(1), upDownLabel.group(2));
t.addItem(l);
}
else if (gridHeight.matches())
{
GridHeight g = new GridHeight(gridHeight.group(1));
t.addItem(g);
}
else if (gridOrient.matches())
{
GridOrient g = new GridOrient(gridOrient.group(1), gridOrient.group(2), gridOrient.group(3));
t.addItem(g);
}
else
{
PreProcessor p = new PreProcessor(processPreprocessor(ecuData, line));
if (t != null && !t.isDefinitionCompleted())
{
t.addItem(p);
}
else
{
t = new TableTracker();
tableDefs.add(t);
t.addItem(p);
}
}
}
/**
* Process the [CurveEditor] section of the ini file
*
* @param line
*/
static void processCurveEditor(ECUData ecuData, String line)
{
line = removeComments(line);
if (StringUtils.isEmpty(line))
{
return;
}
line=removeCurlyBrackets(line);
Matcher curve = Patterns.curve.matcher(line);
Matcher columnLabel = Patterns.curveColumnLabel.matcher(line);
Matcher xAxis = Patterns.curveXAxis.matcher(line);
Matcher yAxis = Patterns.curveYAxis.matcher(line);
Matcher xBins = Patterns.curveXBins.matcher(line);
Matcher yBins = Patterns.curveYBins.matcher(line);
Matcher gauge = Patterns.curveGauge.matcher(line);
Matcher lineLabel = Patterns.curveLineLabel.matcher(line);
final List<CurveTracker> curveDefs = ecuData.getCurveDefs();
CurveTracker c = null;
if(line.contains("cltlowlim"))
{
int x =1;
}
if (curveDefs.size() > 0)
{
c = curveDefs.get(curveDefs.size() - 1);
}
if (c == null)
{
c = new CurveTracker();
curveDefs.add(c);
}
if (curve.matches())
{
if (c.isDefinitionCompleted())
{
c = new CurveTracker();
curveDefs.add(c);
}
CurveDefinition cd = new CurveDefinition(c, curve.group(1), curve.group(2));
c.addItem(cd);
}
else if (columnLabel.matches())
{
ColumnLabel x = new ColumnLabel(columnLabel.group(1), columnLabel.group(2));
c.addItem(x);
}
else if (xAxis.matches())
{
XAxis x = new XAxis(xAxis.group(1), xAxis.group(2), xAxis.group(3));
c.addItem(x);
}
else if (yAxis.matches())
{
// System.out.println("curve yAxis 1: " + curveYAxis.group(1));
// System.out.println("curve yAxis 2: " + curveYAxis.group(2));
// System.out.println("curve yAxis 3: " + curveYAxis.group(3));
}
else if (xBins.matches())
{
uk.org.smithfamily.utils.normaliser.curveeditor.XBins x = new uk.org.smithfamily.utils.normaliser.curveeditor.XBins(xBins.group(1), xBins.group(3),xBins.group(5));
c.addItem(x);
}
else if (yBins.matches())
{
uk.org.smithfamily.utils.normaliser.curveeditor.YBins x = new uk.org.smithfamily.utils.normaliser.curveeditor.YBins(yBins.group(1));
c.addItem(x);
}
else if (gauge.matches())
{
LineLabel x = new LineLabel(gauge.group(1));
c.addItem(x);
}
else if (lineLabel.matches())
{
LineLabel x = new LineLabel(lineLabel.group(1));
c.addItem(x);
}
else
{
uk.org.smithfamily.utils.normaliser.curveeditor.PreProcessor p = new uk.org.smithfamily.utils.normaliser.curveeditor.PreProcessor(processPreprocessor(ecuData, line));
if (c != null && !c.isDefinitionCompleted())
{
c.addItem(p);
}
else
{
c = new CurveTracker();
curveDefs.add(c);
c.addItem(p);
}
}
}
/**
* Process the [UserDefined] section of the ini file
*
* @param line
*/
static void processUserDefined(ECUData ecuData, String line)
{
line = removeComments(line);
if (StringUtils.isEmpty(line))
{
return;
}
Matcher dialog = Patterns.dialog.matcher(line);
Matcher dialogField = Patterns.dialogField.matcher(line);
Matcher dialogDisplayOnlyField = Patterns.dialogDisplayOnlyField
.matcher(line);
Matcher dialogPanel = Patterns.dialogPanel.matcher(line);
if (dialog.matches())
{
// System.out.println("dialog Name: " + dialog.group(1));
// System.out.println("dialog Label: " + dialog.group(2));
}
else if (dialogField.matches())
{
// System.out.println("dialogField Label: " + dialogField.group(1));
// System.out.println("dialogField Name: " + dialogField.group(3));
// System.out.println("dialogField Expression: " +
// dialogField.group(5));
}
else if (dialogDisplayOnlyField.matches())
{
// System.out.println("dialogDisplayOnlyField Label: " +
// dialogDisplayOnlyField.group(1));
// System.out.println("dialogDisplayOnlyField Name: " +
// dialogDisplayOnlyField.group(3));
// System.out.println("dialogDisplayOnlyField Expression: " +
// dialogDisplayOnlyField.group(5));
}
else if (dialogPanel.matches())
{
// System.out.println("dialogPanel Name: " + dialogPanel.group(1));
// System.out.println("dialogPanel Orientation: " +
// dialogPanel.group(2));
// System.out.println("dialogPanel Expression: " +
// dialogPanel.group(4));
}
}
static void processConstantsExtensions(ECUData ecuData, String line)
{
line = removeComments(line);
if (line.contains("defaultValue"))
{
String statement = "";
String[] definition = line.split("=")[1].split(",");
if (definition[1].contains("\""))
{
statement = "String ";
}
else
{
statement = "int ";
}
statement += definition[0] + " = " + definition[1] + ";";
ecuData.getDefaults().add(statement);
}
}
static void processPcVariables(ECUData ecuData, String line)
{
}
}
| true | true | static void processConstants(ECUData ecuData, String line)
{
line = removeComments(line);
if (StringUtils.isEmpty(line))
{
return;
}
if (line.contains("idleadvance_rpmsdelta"))
{
int x=1;
}
if (line.contains("messageEnvelopeFormat"))
{
ecuData.setCRC32Protocol(line.contains("msEnvelope_1.0"));
}
Matcher pageM = Patterns.page.matcher(line);
if (pageM.matches())
{
ecuData.setCurrentPage(Integer.parseInt(pageM.group(1).trim()));
return;
}
Matcher pageSizesM = Patterns.pageSize.matcher(line);
if (pageSizesM.matches())
{
String values = StringUtils.remove(pageSizesM.group(1), ' ');
String[] list = values.split(",");
ecuData.setPageSizes(new ArrayList<String>(Arrays.asList(list)));
}
Matcher pageIdentifersM = Patterns.pageIdentifier.matcher(line);
if (pageIdentifersM.matches())
{
String values = StringUtils.remove(pageIdentifersM.group(1), ' ');
values = StringUtils.remove(values, '"');
String[] list = values.split(",");
ecuData.setPageIdentifiers(new ArrayList<String>(Arrays
.asList(list)));
}
Matcher pageActivateM = Patterns.pageActivate.matcher(line);
if (pageActivateM.matches())
{
String values = StringUtils.remove(pageActivateM.group(1), ' ');
values = StringUtils.remove(values, '"');
String[] list = values.split(",");
ecuData.setPageActivateCommands(new ArrayList<String>(Arrays
.asList(list)));
}
Matcher pageReadCommandM = Patterns.pageReadCommand.matcher(line);
if (pageReadCommandM.matches())
{
String values = StringUtils.remove(pageReadCommandM.group(1), ' ');
values = StringUtils.remove(values, '"');
String[] list = values.split(",");
ecuData.setPageReadCommands(new ArrayList<String>(Arrays.asList(list)));
}
Matcher interWriteDelayM = Patterns.interWriteDelay.matcher(line);
if (interWriteDelayM.matches())
{
ecuData.setInterWriteDelay(Integer.parseInt(interWriteDelayM.group(1).trim()));
return;
}
Matcher pageActivationDelayM = Patterns.pageActivationDelay
.matcher(line);
if (pageActivationDelayM.matches())
{
ecuData.setPageActivationDelayVal(Integer
.parseInt(pageActivationDelayM.group(1).trim()));
return;
}
//To allow for MS2GS27
line=removeCurlyBrackets(line);
Matcher bitsM = Patterns.bits.matcher(line);
Matcher constantM = Patterns.constantScalar.matcher(line);
Matcher constantSimpleM = Patterns.constantSimple.matcher(line);
Matcher constantArrayM = Patterns.constantArray.matcher(line);
if (constantM.matches())
{
String name = constantM.group(1);
String classtype = constantM.group(2);
String type = constantM.group(3);
int offset = Integer.parseInt(constantM.group(4).trim());
String units = constantM.group(5);
String scaleText = constantM.group(6);
String translateText = constantM.group(7);
String lowText = constantM.group(8);
String highText = constantM.group(9);
String digitsText = constantM.group(10);
double scale = !StringUtils.isEmpty(scaleText) ? Double
.parseDouble(scaleText) : 0;
double translate = !StringUtils.isEmpty(translateText) ? Double
.parseDouble(translateText) : 0;
int digits = !StringUtils.isEmpty(digitsText) ? (int) Double
.parseDouble(digitsText) : 0;
if (!ecuData.getConstants().contains(name))
{
Constant c = new Constant(ecuData.getCurrentPage(), name,
classtype, type, offset, "", units, scale, translate,
lowText, highText, digits);
if (scale == 1.0)
{
ecuData.getConstantVars().put(name, "int");
}
else
{
ecuData.getConstantVars().put(name, "double");
}
ecuData.getConstants().add(c);
}
}
else if (constantArrayM.matches())
{
String name = constantArrayM.group(1);
String classtype = constantArrayM.group(2);
String type = constantArrayM.group(3);
int offset = Integer.parseInt(constantArrayM.group(4).trim());
String shape = constantArrayM.group(5);
String units = constantArrayM.group(6);
String scaleText = constantArrayM.group(7);
String translateText = constantArrayM.group(8);
String lowText = constantArrayM.group(9);
String highText = constantArrayM.group(10);
String digitsText = constantArrayM.group(11);
highText = highText.replace("{", "").replace("}", "");
double scale = !StringUtils.isEmpty(scaleText) ? Double
.parseDouble(scaleText) : 0;
double translate = !StringUtils.isEmpty(translateText) ? Double
.parseDouble(translateText) : 0;
int digits = !StringUtils.isEmpty(digitsText) ? (int) Double
.parseDouble(digitsText) : 0;
if (!ecuData.getConstants().contains(name))
{
Constant c = new Constant(ecuData.getCurrentPage(), name,
classtype, type, offset, shape, units, scale,
translate, lowText, highText, digits);
if (shape.contains("x"))
{
ecuData.getConstantVars().put(name, "double[][]");
}
else
{
ecuData.getConstantVars().put(name, "double[]");
}
ecuData.getConstants().add(c);
}
}
else if (constantSimpleM.matches())
{
String name = constantSimpleM.group(1);
String classtype = constantSimpleM.group(2);
String type = constantSimpleM.group(3);
int offset = Integer.parseInt(constantSimpleM.group(4).trim());
String units = constantSimpleM.group(5);
double scale = Double.parseDouble(constantSimpleM.group(6));
double translate = Double.parseDouble(constantSimpleM.group(7));
Constant c = new Constant(ecuData.getCurrentPage(), name,
classtype, type, offset, "", units, scale, translate, "0", "0",
0);
if (scale == 1.0)
{
ecuData.getConstantVars().put(name, "int");
} else
{
ecuData.getConstantVars().put(name, "double");
}
ecuData.getConstants().add(c);
}
else if (bitsM.matches())
{
String name = bitsM.group(1);
String offset = bitsM.group(3);
String start = bitsM.group(4);
String end = bitsM.group(5);
Constant c = new Constant(ecuData.getCurrentPage(), name, "bits",
"", Integer.parseInt(offset.trim()), "[" + start + ":"
+ end + "]", "", 1, 0, "0", "0", 0);
ecuData.getConstantVars().put(name, "int");
ecuData.getConstants().add(c);
}
else if (line.startsWith("#"))
{
String preproc = (processPreprocessor(ecuData, line));
Constant c = new Constant(ecuData.getCurrentPage(), preproc, "",
"PREPROC", 0, "", "", 0, 0, "0", "0", 0);
ecuData.getConstants().add(c);
}
}
| static void processConstants(ECUData ecuData, String line)
{
line = removeComments(line);
if (StringUtils.isEmpty(line))
{
return;
}
if (line.contains("DI_rpm"))
{
int x=1;
}
if (line.contains("messageEnvelopeFormat"))
{
ecuData.setCRC32Protocol(line.contains("msEnvelope_1.0"));
}
Matcher pageM = Patterns.page.matcher(line);
if (pageM.matches())
{
ecuData.setCurrentPage(Integer.parseInt(pageM.group(1).trim()));
return;
}
Matcher pageSizesM = Patterns.pageSize.matcher(line);
if (pageSizesM.matches())
{
String values = StringUtils.remove(pageSizesM.group(1), ' ');
String[] list = values.split(",");
ecuData.setPageSizes(new ArrayList<String>(Arrays.asList(list)));
}
Matcher pageIdentifersM = Patterns.pageIdentifier.matcher(line);
if (pageIdentifersM.matches())
{
String values = StringUtils.remove(pageIdentifersM.group(1), ' ');
values = StringUtils.remove(values, '"');
String[] list = values.split(",");
ecuData.setPageIdentifiers(new ArrayList<String>(Arrays
.asList(list)));
}
Matcher pageActivateM = Patterns.pageActivate.matcher(line);
if (pageActivateM.matches())
{
String values = StringUtils.remove(pageActivateM.group(1), ' ');
values = StringUtils.remove(values, '"');
String[] list = values.split(",");
ecuData.setPageActivateCommands(new ArrayList<String>(Arrays
.asList(list)));
}
Matcher pageReadCommandM = Patterns.pageReadCommand.matcher(line);
if (pageReadCommandM.matches())
{
String values = StringUtils.remove(pageReadCommandM.group(1), ' ');
values = StringUtils.remove(values, '"');
String[] list = values.split(",");
ecuData.setPageReadCommands(new ArrayList<String>(Arrays.asList(list)));
}
Matcher interWriteDelayM = Patterns.interWriteDelay.matcher(line);
if (interWriteDelayM.matches())
{
ecuData.setInterWriteDelay(Integer.parseInt(interWriteDelayM.group(1).trim()));
return;
}
Matcher pageActivationDelayM = Patterns.pageActivationDelay
.matcher(line);
if (pageActivationDelayM.matches())
{
ecuData.setPageActivationDelayVal(Integer
.parseInt(pageActivationDelayM.group(1).trim()));
return;
}
//To allow for MS2GS27
line=removeCurlyBrackets(line);
Matcher bitsM = Patterns.bits.matcher(line);
Matcher constantM = Patterns.constantScalar.matcher(line);
Matcher constantSimpleM = Patterns.constantSimple.matcher(line);
Matcher constantArrayM = Patterns.constantArray.matcher(line);
if (constantM.matches())
{
String name = constantM.group(1);
String classtype = constantM.group(2);
String type = constantM.group(3);
int offset = Integer.parseInt(constantM.group(4).trim());
String units = constantM.group(5);
String scaleText = constantM.group(6);
String translateText = constantM.group(7);
String lowText = constantM.group(8);
String highText = constantM.group(9);
String digitsText = constantM.group(10);
double scale = !StringUtils.isEmpty(scaleText) ? Double
.parseDouble(scaleText) : 0;
double translate = !StringUtils.isEmpty(translateText) ? Double
.parseDouble(translateText) : 0;
int digits = !StringUtils.isEmpty(digitsText) ? (int) Double
.parseDouble(digitsText) : 0;
if (!ecuData.getConstants().contains(name))
{
Constant c = new Constant(ecuData.getCurrentPage(), name,
classtype, type, offset, "", units, scale, translate,
lowText, highText, digits);
if (scale == 1.0)
{
ecuData.getConstantVars().put(name, "int");
}
else
{
ecuData.getConstantVars().put(name, "double");
}
ecuData.getConstants().add(c);
}
}
else if (constantArrayM.matches())
{
String name = constantArrayM.group(1);
String classtype = constantArrayM.group(2);
String type = constantArrayM.group(3);
int offset = Integer.parseInt(constantArrayM.group(4).trim());
String shape = constantArrayM.group(5);
String units = constantArrayM.group(6);
String scaleText = constantArrayM.group(7);
String translateText = constantArrayM.group(8);
String lowText = constantArrayM.group(9);
String highText = constantArrayM.group(10);
String digitsText = constantArrayM.group(11);
highText = highText.replace("{", "").replace("}", "");
double scale = !StringUtils.isEmpty(scaleText) ? Double
.parseDouble(scaleText) : 0;
double translate = !StringUtils.isEmpty(translateText) ? Double
.parseDouble(translateText) : 0;
int digits = !StringUtils.isEmpty(digitsText) ? (int) Double
.parseDouble(digitsText) : 0;
if (!ecuData.getConstants().contains(name))
{
Constant c = new Constant(ecuData.getCurrentPage(), name,
classtype, type, offset, shape, units, scale,
translate, lowText, highText, digits);
if (shape.contains("x"))
{
ecuData.getConstantVars().put(name, "double[][]");
}
else
{
ecuData.getConstantVars().put(name, "double[]");
}
ecuData.getConstants().add(c);
}
}
else if (constantSimpleM.matches())
{
String name = constantSimpleM.group(1);
String classtype = constantSimpleM.group(2);
String type = constantSimpleM.group(3);
int offset = Integer.parseInt(constantSimpleM.group(4).trim());
String units = constantSimpleM.group(5);
double scale = Double.parseDouble(constantSimpleM.group(6));
double translate = Double.parseDouble(constantSimpleM.group(7));
Constant c = new Constant(ecuData.getCurrentPage(), name,
classtype, type, offset, "", units, scale, translate, "0", "0",
0);
if (scale == 1.0)
{
ecuData.getConstantVars().put(name, "int");
} else
{
ecuData.getConstantVars().put(name, "double");
}
ecuData.getConstants().add(c);
}
else if (bitsM.matches())
{
String name = bitsM.group(1);
String offset = bitsM.group(3);
String start = bitsM.group(4);
String end = bitsM.group(5);
Constant c = new Constant(ecuData.getCurrentPage(), name, "bits",
"", Integer.parseInt(offset.trim()), "[" + start + ":"
+ end + "]", "", 1, 0, "0", "0", 0);
ecuData.getConstantVars().put(name, "int");
ecuData.getConstants().add(c);
}
else if (line.startsWith("#"))
{
String preproc = (processPreprocessor(ecuData, line));
Constant c = new Constant(ecuData.getCurrentPage(), preproc, "",
"PREPROC", 0, "", "", 0, 0, "0", "0", 0);
ecuData.getConstants().add(c);
}
}
|
diff --git a/src/alignment/AlignmentCalculator.java b/src/alignment/AlignmentCalculator.java
index 4eb8ef9..e34bcc3 100644
--- a/src/alignment/AlignmentCalculator.java
+++ b/src/alignment/AlignmentCalculator.java
@@ -1,340 +1,352 @@
package alignment;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class AlignmentCalculator
{
final static String ENTRY_SEPARATOR = ",";
final static String SCORE_DIRECTION_SEPARATOR = ";";
final static String NEWLINE = System.getProperty("line.separator");
public final static String NEEDLEMAN_WUNCH = "Needleman-Wunch";
public final static String SMITH_WATERMAN = "Smith-Waterman";
private String x;
private String y;
private AlignmentElement[][] a;
private AlignmentElement[][] n;
private AlignmentElement[][] w;
/**
* Used for local alignment printing
*/
private AlignmentElement highest;
private String xalig, align, yalig;
private boolean local;
private AlignmentScoringSystem scoring;
public AlignmentCalculator(String s1, String s2, AlignmentScoringSystem scoring_, boolean local_)
{
x = s1;
y = s2;
a = new AlignmentElement[y.length() + 1][x.length() + 1];
n = new AlignmentElement[y.length() + 1][x.length() + 1];
w = new AlignmentElement[y.length() + 1][x.length() + 1];
for (int j = 0; j <= y.length(); j++)
{
for (int i = 0; i <= x.length(); i++)
{
a[j][i] = new AlignmentElement(j, i, null);
n[j][i] = new AlignmentElement(j, i, null);
w[j][i] = new AlignmentElement(j, i, null);
}
}
highest = a[0][0];
local = local_;
scoring = scoring_;
}
public void fillScoreArray()
{
int col, row;
double northwest;
double west;
double north;
double best;
PointerDirection dir;
a[0][0].score = 0.0;
- for (col = 1; col <= x.length(); col++)
+ if (x.length() >= 2)
{
- a[0][col].score = localScore(scoring.gapContinue * col);
+ a[0][1].score = localScore(scoring.gapStart + scoring.gapContinue);
+ a[0][1].direction = PointerDirection.WEST;
+ n[0][1].score = Double.NEGATIVE_INFINITY;
+ }
+ if (y.length() >= 2)
+ {
+ a[1][0].score = localScore(scoring.gapStart + scoring.gapContinue);
+ a[1][0].direction = PointerDirection.NORTH;
+ w[1][0].score = Double.NEGATIVE_INFINITY;
+ }
+ for (col = 2; col <= x.length(); col++)
+ {
+ a[0][col].score = localScore(scoring.gapContinue * col + scoring.gapStart);
a[0][col].direction = PointerDirection.WEST;
n[0][col].score = Double.NEGATIVE_INFINITY;
}
- for (row = 1; row <= y.length(); row++)
+ for (row = 2; row <= y.length(); row++)
{
- a[row][0].score = localScore(scoring.gapContinue * row);
+ a[row][0].score = localScore(scoring.gapContinue * row + scoring.gapStart);
a[row][0].direction = PointerDirection.NORTH;
w[row][0].score = Double.NEGATIVE_INFINITY;
}
for (row = 1; row <= y.length(); row++)
{
for (col = 1; col <= x.length(); col++)
{
// N
double from_a = localScore(a[row - 1][col].score + scoring.gapStart + scoring.gapContinue);
double from_n = localScore(n[row - 1][col].score + scoring.gapContinue);
north = n[row][col].score = Math.max(from_a, from_n);
// W
from_a = localScore(a[row][col - 1].score + scoring.gapStart + scoring.gapContinue);
double from_w = localScore(w[row][col - 1].score + scoring.gapContinue);
west = w[row][col].score = Math.max(from_a, from_w);
// A
if (x.charAt(col - 1) == y.charAt(row - 1))
{
northwest = localScore(a[row - 1][col - 1].score + scoring.match);
}
else
{
northwest = localScore(a[row - 1][col - 1].score + scoring.mismatch);
}
best = northwest;
dir = PointerDirection.NORTHWEST;
if (north > best)
{
dir = PointerDirection.NORTH;
best = north;
}
if (west > best)
{
dir = PointerDirection.WEST;
best = west;
}
a[row][col].score = best;
a[row][col].direction = dir;
if (a[row][col].score >= highest.score)
{
highest = a[row][col];
}
}
}
}
public void print3(Double score)
{
String string = String.format("%03.0f, ", score);
if (string.length() <= 8)
{
System.out.print(string);
}
else
{
System.out.print("***");
}
}
public void printArray()
{
System.out.print(" ");
for (int col = 0; col < x.length(); col++)
{
System.out.printf("%5s", x.charAt(col));
}
System.out.println();
System.out.print(" ");
for (int col = 0; col < a[0].length; col++)
{
System.out.printf("%4.0f,", a[0][col].score);
}
System.out.println();
for (int row = 1; row < a.length; row++)
{
System.out.printf("%5s", y.charAt(row - 1));
for (int col = 0; col < a[row - 1].length; col++)
{
System.out.printf("%4.0f,", a[row][col].score);
}
System.out.println();
}
}
public void setAlignment()
{
int row = local ? highest.row : y.length();
int col = local ? highest.col : x.length();
StringBuilder xb = new StringBuilder();
xb.append(x.substring(col).toLowerCase());
StringBuilder ab = new StringBuilder();
StringBuilder yb = new StringBuilder();
yb.append(y.substring(row).toLowerCase());
char gapChar;
char matchChar;
char mismatchChar;
boolean passedZero = false;
while ((col > 0) || (row > 0))
{
PointerDirection dir = a[row][col].direction;
if (a[row][col].score <= 0.0 && local)
{
passedZero = true;
}
a[row][col].isPartOfAlignment = isPartOfAlignment(passedZero, row, col);
gapChar = passedZero ? ' ' : '-';
matchChar = passedZero ? ' ' : '|';
mismatchChar = passedZero ? ' ' : 'X';
switch (dir)
{
case NORTH:
xb.insert(0, gapChar);
ab.insert(0, gapChar);
yb.insert(0, localChar(y.charAt(row - 1), passedZero, row, col));
row--;
break;
case WEST:
xb.insert(0, localChar(x.charAt(col - 1), passedZero, row, col));
ab.insert(0, gapChar);
yb.insert(0, gapChar);
col--;
break;
case NORTHWEST:
char xc = localChar(x.charAt(col - 1), passedZero, row, col);
char yc = localChar(y.charAt(row - 1), passedZero, row, col);
xb.insert(0, xc);
ab.insert(0, (xc == yc) ? matchChar : mismatchChar);
yb.insert(0, yc);
col--;
row--;
break;
}
}
if (!local)
{
a[0][0].isPartOfAlignment = true;
}
xalig = xb.toString();
align = ab.toString();
yalig = yb.toString();
}
public void printAlignment()
{
System.out.println(xalig);
System.out.println(align);
System.out.println(yalig);
System.out.println();
}
public String getAlignment()
{
StringBuilder sb = new StringBuilder();
String newline = System.getProperty("line.separator");
sb.append(xalig);
sb.append(newline);
sb.append(align);
sb.append(newline);
sb.append(yalig);
return sb.toString();
}
/**
* @param column
* Column index
* @param row
* Row index
* @return
*/
public double getValue(int row, int column)
{
return a[row][column].score;
}
public boolean isPartOfAlignment(int row, int column)
{
return a[row][column].isPartOfAlignment;
}
private double localScore(double i)
{
return (local && i < 0) ? 0 : i;
}
private char localChar(char c, boolean passedZero, int row, int col)
{
return isPartOfAlignment(passedZero, row, col) ? c : Character.toLowerCase(c);
}
private boolean isPartOfAlignment(boolean passedZero, int row, int col)
{
return !(local && (row > highest.row || col > highest.col || passedZero));
}
public void exportToFile(File file) throws IOException
{
BufferedWriter w = new BufferedWriter(new FileWriter(file));
w.write("# Data format:");
w.write(NEWLINE);
w.write("# entry = score");
w.write(SCORE_DIRECTION_SEPARATOR);
w.write("direction");
w.write(NEWLINE);
w.write("# entry_list = entry_list[");
w.write(ENTRY_SEPARATOR);
w.write("entry]");
w.write(NEWLINE);
w.write("# Horizontal string: ");
w.write(x);
w.write(NEWLINE);
w.write("# Vertical string: ");
w.write(y);
w.write(NEWLINE);
w.write("# Scoring:");
w.write(NEWLINE);
w.write("# Match: ");
w.write(Integer.toString(scoring.match));
w.write(NEWLINE);
w.write("# Mismatch: ");
w.write(Integer.toString(scoring.mismatch));
w.write(NEWLINE);
w.write("# Gap start: ");
w.write(Integer.toString(scoring.gapStart));
w.write(NEWLINE);
w.write("# Gap continue: ");
w.write(Integer.toString(scoring.gapContinue));
w.write(NEWLINE);
w.write("# ");
w.write(local ? SMITH_WATERMAN : NEEDLEMAN_WUNCH);
w.write(" alignment:");
w.write(NEWLINE);
w.write("# ");
w.write(xalig);
w.write(NEWLINE);
w.write("# ");
w.write(align);
w.write(NEWLINE);
w.write("# ");
w.write(yalig);
w.write(NEWLINE);
for (int row = 0; row <= y.length(); row++)
{
for (int col = 0; col <= x.length(); col++)
{
w.write(String.format("%.0f", a[row][col].score));
w.write(SCORE_DIRECTION_SEPARATOR);
String dir = a[row][col].direction == null ? "?" : a[row][col].direction.getShortDescription();
w.write(dir);
w.write(ENTRY_SEPARATOR);
}
w.write(NEWLINE);
}
w.close();
}
/**
* @param args
*/
public static void main(String[] args)
{
AlignmentScoringSystem scoring = new AlignmentScoringSystem(0, -1, 2, -1);
AlignmentCalculator ac = new AlignmentCalculator(args[0], args[1], scoring, false);
ac.local = true;
ac.fillScoreArray();
ac.printArray();
System.out.println();
ac.setAlignment();
ac.printAlignment();
}
}
| false | true | public void fillScoreArray()
{
int col, row;
double northwest;
double west;
double north;
double best;
PointerDirection dir;
a[0][0].score = 0.0;
for (col = 1; col <= x.length(); col++)
{
a[0][col].score = localScore(scoring.gapContinue * col);
a[0][col].direction = PointerDirection.WEST;
n[0][col].score = Double.NEGATIVE_INFINITY;
}
for (row = 1; row <= y.length(); row++)
{
a[row][0].score = localScore(scoring.gapContinue * row);
a[row][0].direction = PointerDirection.NORTH;
w[row][0].score = Double.NEGATIVE_INFINITY;
}
for (row = 1; row <= y.length(); row++)
{
for (col = 1; col <= x.length(); col++)
{
// N
double from_a = localScore(a[row - 1][col].score + scoring.gapStart + scoring.gapContinue);
double from_n = localScore(n[row - 1][col].score + scoring.gapContinue);
north = n[row][col].score = Math.max(from_a, from_n);
// W
from_a = localScore(a[row][col - 1].score + scoring.gapStart + scoring.gapContinue);
double from_w = localScore(w[row][col - 1].score + scoring.gapContinue);
west = w[row][col].score = Math.max(from_a, from_w);
// A
if (x.charAt(col - 1) == y.charAt(row - 1))
{
northwest = localScore(a[row - 1][col - 1].score + scoring.match);
}
else
{
northwest = localScore(a[row - 1][col - 1].score + scoring.mismatch);
}
best = northwest;
dir = PointerDirection.NORTHWEST;
if (north > best)
{
dir = PointerDirection.NORTH;
best = north;
}
if (west > best)
{
dir = PointerDirection.WEST;
best = west;
}
a[row][col].score = best;
a[row][col].direction = dir;
if (a[row][col].score >= highest.score)
{
highest = a[row][col];
}
}
}
}
| public void fillScoreArray()
{
int col, row;
double northwest;
double west;
double north;
double best;
PointerDirection dir;
a[0][0].score = 0.0;
if (x.length() >= 2)
{
a[0][1].score = localScore(scoring.gapStart + scoring.gapContinue);
a[0][1].direction = PointerDirection.WEST;
n[0][1].score = Double.NEGATIVE_INFINITY;
}
if (y.length() >= 2)
{
a[1][0].score = localScore(scoring.gapStart + scoring.gapContinue);
a[1][0].direction = PointerDirection.NORTH;
w[1][0].score = Double.NEGATIVE_INFINITY;
}
for (col = 2; col <= x.length(); col++)
{
a[0][col].score = localScore(scoring.gapContinue * col + scoring.gapStart);
a[0][col].direction = PointerDirection.WEST;
n[0][col].score = Double.NEGATIVE_INFINITY;
}
for (row = 2; row <= y.length(); row++)
{
a[row][0].score = localScore(scoring.gapContinue * row + scoring.gapStart);
a[row][0].direction = PointerDirection.NORTH;
w[row][0].score = Double.NEGATIVE_INFINITY;
}
for (row = 1; row <= y.length(); row++)
{
for (col = 1; col <= x.length(); col++)
{
// N
double from_a = localScore(a[row - 1][col].score + scoring.gapStart + scoring.gapContinue);
double from_n = localScore(n[row - 1][col].score + scoring.gapContinue);
north = n[row][col].score = Math.max(from_a, from_n);
// W
from_a = localScore(a[row][col - 1].score + scoring.gapStart + scoring.gapContinue);
double from_w = localScore(w[row][col - 1].score + scoring.gapContinue);
west = w[row][col].score = Math.max(from_a, from_w);
// A
if (x.charAt(col - 1) == y.charAt(row - 1))
{
northwest = localScore(a[row - 1][col - 1].score + scoring.match);
}
else
{
northwest = localScore(a[row - 1][col - 1].score + scoring.mismatch);
}
best = northwest;
dir = PointerDirection.NORTHWEST;
if (north > best)
{
dir = PointerDirection.NORTH;
best = north;
}
if (west > best)
{
dir = PointerDirection.WEST;
best = west;
}
a[row][col].score = best;
a[row][col].direction = dir;
if (a[row][col].score >= highest.score)
{
highest = a[row][col];
}
}
}
}
|
diff --git a/DatabaseProyecto/src/ar/proyecto/gui/MiddlePanelSelect.java b/DatabaseProyecto/src/ar/proyecto/gui/MiddlePanelSelect.java
index 3b47846..68aa8a4 100644
--- a/DatabaseProyecto/src/ar/proyecto/gui/MiddlePanelSelect.java
+++ b/DatabaseProyecto/src/ar/proyecto/gui/MiddlePanelSelect.java
@@ -1,80 +1,82 @@
package ar.proyecto.gui;
import java.awt.CardLayout;
import java.awt.FlowLayout;
import java.text.NumberFormat;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFormattedTextField;
import javax.swing.JLabel;
import javax.swing.JPanel;
import ar.proyecto.controller.ActionMiddlePanelSelectCbox;
import ar.proyecto.controller.ActionMiddlePanelSelectOk;
public class MiddlePanelSelect extends MiddlePanel {
private JLabel from;
private JComboBox cbTable;
private JLabel whereNum;
private JFormattedTextField nroMulta;
private JPanel centralPanel;
private JPanel centralPanelEmpty;
private JPanel centralPanelFilled;
private final static String sPaneEmpty = new String("Empty Pannel");
private final static String sPaneFilled = new String("Filled Pannel");
private int widthpc = 400;
private JButton ok;
//constructor
public MiddlePanelSelect(MainWindow gui) {
super(gui);
this.setLayout(new FlowLayout(FlowLayout.LEFT));
from = new JLabel("FROM TABLE :");
centralPanel = new JPanel();
centralPanel.setLayout(new CardLayout());
whereNum = new JLabel("WHERE nro_multa =");
- nroMulta = new JFormattedTextField(NumberFormat.getIntegerInstance());
+ NumberFormat nroMultaFormat = NumberFormat.getIntegerInstance();
+ nroMultaFormat.setGroupingUsed(false);
+ nroMulta = new JFormattedTextField(nroMultaFormat);
nroMulta.setColumns(5);
initCentralPanelEmpty();
initCentralPanelFilled();
//Adding both centralPanel one on the top of the other
centralPanel.add(centralPanelEmpty,sPaneEmpty);
centralPanel.add(centralPanelFilled,sPaneFilled);
String[] cb = {"Infraccion","Multa"};
cbTable = new JComboBox(cb);
cbTable.setAction(new ActionMiddlePanelSelectCbox(this,centralPanel));
ok = new JButton(new ActionMiddlePanelSelectOk(gui,nroMulta,cbTable,"OK"));
this.add(from);
this.add(cbTable);
this.add(centralPanel);
this.add(ok);
}
private void initCentralPanelEmpty() {
centralPanelEmpty = new JPanel();
centralPanelEmpty.setBackground(this.getBackground());
}
private void initCentralPanelFilled() {
centralPanelFilled = new JPanel();
centralPanelFilled.setBackground(this.getBackground());
centralPanelFilled.add(whereNum);
centralPanelFilled.add(nroMulta);
}
public String getSPaneEmpty() {
return sPaneEmpty;
}
public String getSPaneFilled() {
return sPaneFilled;
}
}
| true | true | public MiddlePanelSelect(MainWindow gui) {
super(gui);
this.setLayout(new FlowLayout(FlowLayout.LEFT));
from = new JLabel("FROM TABLE :");
centralPanel = new JPanel();
centralPanel.setLayout(new CardLayout());
whereNum = new JLabel("WHERE nro_multa =");
nroMulta = new JFormattedTextField(NumberFormat.getIntegerInstance());
nroMulta.setColumns(5);
initCentralPanelEmpty();
initCentralPanelFilled();
//Adding both centralPanel one on the top of the other
centralPanel.add(centralPanelEmpty,sPaneEmpty);
centralPanel.add(centralPanelFilled,sPaneFilled);
String[] cb = {"Infraccion","Multa"};
cbTable = new JComboBox(cb);
cbTable.setAction(new ActionMiddlePanelSelectCbox(this,centralPanel));
ok = new JButton(new ActionMiddlePanelSelectOk(gui,nroMulta,cbTable,"OK"));
this.add(from);
this.add(cbTable);
this.add(centralPanel);
this.add(ok);
}
| public MiddlePanelSelect(MainWindow gui) {
super(gui);
this.setLayout(new FlowLayout(FlowLayout.LEFT));
from = new JLabel("FROM TABLE :");
centralPanel = new JPanel();
centralPanel.setLayout(new CardLayout());
whereNum = new JLabel("WHERE nro_multa =");
NumberFormat nroMultaFormat = NumberFormat.getIntegerInstance();
nroMultaFormat.setGroupingUsed(false);
nroMulta = new JFormattedTextField(nroMultaFormat);
nroMulta.setColumns(5);
initCentralPanelEmpty();
initCentralPanelFilled();
//Adding both centralPanel one on the top of the other
centralPanel.add(centralPanelEmpty,sPaneEmpty);
centralPanel.add(centralPanelFilled,sPaneFilled);
String[] cb = {"Infraccion","Multa"};
cbTable = new JComboBox(cb);
cbTable.setAction(new ActionMiddlePanelSelectCbox(this,centralPanel));
ok = new JButton(new ActionMiddlePanelSelectOk(gui,nroMulta,cbTable,"OK"));
this.add(from);
this.add(cbTable);
this.add(centralPanel);
this.add(ok);
}
|
diff --git a/doxia-core/src/main/java/org/apache/maven/doxia/macro/snippet/SnippetMacro.java b/doxia-core/src/main/java/org/apache/maven/doxia/macro/snippet/SnippetMacro.java
index c00a0323..f2d2208e 100644
--- a/doxia-core/src/main/java/org/apache/maven/doxia/macro/snippet/SnippetMacro.java
+++ b/doxia-core/src/main/java/org/apache/maven/doxia/macro/snippet/SnippetMacro.java
@@ -1,298 +1,298 @@
package org.apache.maven.doxia.macro.snippet;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.doxia.macro.AbstractMacro;
import org.apache.maven.doxia.macro.MacroExecutionException;
import org.apache.maven.doxia.macro.MacroRequest;
import org.apache.maven.doxia.sink.Sink;
import org.codehaus.plexus.util.StringUtils;
import java.io.IOException;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
/**
* A macro that prints out the content of a file or a URL.
*
* @plexus.component role-hint="snippet"
*/
public class SnippetMacro
extends AbstractMacro
{
/** System-dependent EOL. */
static final String EOL = System.getProperty( "line.separator" );
/** Holds the cache. */
private Map cache = new HashMap();
/** One hour default cache. */
private long timeout = 60 * 60 * 1000;
/** Holds the time cache. */
private Map timeCached = new HashMap();
/** Debug. */
private boolean debug = false;
/** {@inheritDoc} */
public void execute( Sink sink, MacroRequest request )
throws MacroExecutionException
{
String id = (String) request.getParameter( "id" );
required( id, "id" );
String urlParam = (String) request.getParameter( "url" );
String fileParam = (String) request.getParameter( "file" );
boolean verbatim = true;
String verbatimParam = (String) request.getParameter( "verbatim" );
if ( verbatimParam != null && !"".equals( verbatimParam ) )
{
verbatim = Boolean.valueOf( verbatimParam ).booleanValue();
}
URL url;
if ( !StringUtils.isEmpty( urlParam ) )
{
try
{
url = new URL( urlParam );
}
catch ( MalformedURLException e )
{
throw new IllegalArgumentException( urlParam + " is a malformed URL" );
}
}
else if ( !StringUtils.isEmpty( fileParam ) )
{
File f = new File( fileParam );
if ( !f.isAbsolute() )
{
f = new File( request.getBasedir(), fileParam );
}
try
{
url = f.toURL();
}
catch ( MalformedURLException e )
{
- throw new IllegalArgumentException( urlParam + " is a malformed URL" );
+ throw new IllegalArgumentException( fileParam + " is a malformed URL" );
}
}
else
{
throw new IllegalArgumentException( "Either the 'url' or the 'file' param has to be given." );
}
StringBuffer snippet;
try
{
snippet = getSnippet( url, id );
}
catch ( IOException e )
{
throw new MacroExecutionException( "Error reading snippet", e );
}
if ( verbatim )
{
sink.verbatim( true );
sink.text( snippet.toString() );
sink.verbatim_();
}
else {
sink.rawText( snippet.toString() );
}
}
/**
* Return a snippet of the given url.
*
* @param url The URL to parse.
* @param id The id of the snippet.
* @return The snippet.
* @throws IOException if something goes wrong.
*/
private StringBuffer getSnippet( URL url, String id )
throws IOException
{
StringBuffer result;
String cachedSnippet = (String) getCachedSnippet( url, id );
if ( cachedSnippet != null )
{
result = new StringBuffer( cachedSnippet );
if ( debug )
{
result.append( "(Served from cache)" );
}
}
else
{
result = new SnippetReader( url ).readSnippet( id );
cacheSnippet( url, id, result.toString() );
if ( debug )
{
result.append( "(Fetched from url, cache content " ).append( cache ).append( ")" );
}
}
return result;
}
/**
* Return a snippet from the cache.
*
* @param url The URL to parse.
* @param id The id of the snippet.
* @return The snippet.
*/
private Object getCachedSnippet( URL url, String id )
{
if ( isCacheTimedout( url, id ) )
{
removeFromCache( url, id );
}
return cache.get( globalSnippetId( url, id ) );
}
/**
* Return true if the snippet has been cached longer than
* the current timeout.
*
* @param url The URL to parse.
* @param id The id of the snippet.
* @return True if timeout exceeded.
*/
boolean isCacheTimedout( URL url, String id )
{
return timeInCache( url, id ) >= timeout;
}
/**
* Return the time the snippet has been cached.
*
* @param url The URL to parse.
* @param id The id of the snippet.
* @return The cache time.
*/
long timeInCache( URL url, String id )
{
return System.currentTimeMillis() - getTimeCached( url, id );
}
/**
* Return the absolute value of when the snippet has been cached.
*
* @param url The URL to parse.
* @param id The id of the snippet.
* @return The cache time.
*/
long getTimeCached( URL url, String id )
{
String globalId = globalSnippetId( url, id );
return timeCached.containsKey( globalId ) ? ( (Long) timeCached.get( globalId ) ).longValue() : 0;
}
/**
* Removes the snippet from the cache.
*
* @param url The URL to parse.
* @param id The id of the snippet.
*/
private void removeFromCache( URL url, String id )
{
String globalId = globalSnippetId( url, id );
timeCached.remove( globalId );
cache.remove( globalId );
}
/**
* Return a global identifier for the snippet.
*
* @param url The URL to parse.
* @param id The id of the snippet.
* @return An identifier, concatenated url and id.
*/
private String globalSnippetId( URL url, String id )
{
return url + " " + id;
}
/**
* Check if the given parameter is required. Throws an
* IllegalArgumentException if id is null or empty.
*
* @param id The id of the snippet.
* @param param The parameter to check.
*/
private void required( String id, String param )
{
if ( id == null || "".equals( id ) )
{
throw new IllegalArgumentException( param + " is a required parameter" );
}
}
/**
*Puts the given snippet into the cache.
*
* @param url The URL to parse.
* @param id The id of the snippet.
* @param content The content of the snippet.
*/
public void cacheSnippet( URL url, String id, String content )
{
cache.put( globalSnippetId( url, id ), content );
timeCached.put( globalSnippetId( url, id ), new Long( System.currentTimeMillis() ) );
}
/**
* Set the cache timeout.
*
* @param time The timeout to set.
*/
public void setCacheTimeout( int time )
{
this.timeout = time;
}
}
| true | true | public void execute( Sink sink, MacroRequest request )
throws MacroExecutionException
{
String id = (String) request.getParameter( "id" );
required( id, "id" );
String urlParam = (String) request.getParameter( "url" );
String fileParam = (String) request.getParameter( "file" );
boolean verbatim = true;
String verbatimParam = (String) request.getParameter( "verbatim" );
if ( verbatimParam != null && !"".equals( verbatimParam ) )
{
verbatim = Boolean.valueOf( verbatimParam ).booleanValue();
}
URL url;
if ( !StringUtils.isEmpty( urlParam ) )
{
try
{
url = new URL( urlParam );
}
catch ( MalformedURLException e )
{
throw new IllegalArgumentException( urlParam + " is a malformed URL" );
}
}
else if ( !StringUtils.isEmpty( fileParam ) )
{
File f = new File( fileParam );
if ( !f.isAbsolute() )
{
f = new File( request.getBasedir(), fileParam );
}
try
{
url = f.toURL();
}
catch ( MalformedURLException e )
{
throw new IllegalArgumentException( urlParam + " is a malformed URL" );
}
}
else
{
throw new IllegalArgumentException( "Either the 'url' or the 'file' param has to be given." );
}
StringBuffer snippet;
try
{
snippet = getSnippet( url, id );
}
catch ( IOException e )
{
throw new MacroExecutionException( "Error reading snippet", e );
}
if ( verbatim )
{
sink.verbatim( true );
sink.text( snippet.toString() );
sink.verbatim_();
}
else {
sink.rawText( snippet.toString() );
}
}
| public void execute( Sink sink, MacroRequest request )
throws MacroExecutionException
{
String id = (String) request.getParameter( "id" );
required( id, "id" );
String urlParam = (String) request.getParameter( "url" );
String fileParam = (String) request.getParameter( "file" );
boolean verbatim = true;
String verbatimParam = (String) request.getParameter( "verbatim" );
if ( verbatimParam != null && !"".equals( verbatimParam ) )
{
verbatim = Boolean.valueOf( verbatimParam ).booleanValue();
}
URL url;
if ( !StringUtils.isEmpty( urlParam ) )
{
try
{
url = new URL( urlParam );
}
catch ( MalformedURLException e )
{
throw new IllegalArgumentException( urlParam + " is a malformed URL" );
}
}
else if ( !StringUtils.isEmpty( fileParam ) )
{
File f = new File( fileParam );
if ( !f.isAbsolute() )
{
f = new File( request.getBasedir(), fileParam );
}
try
{
url = f.toURL();
}
catch ( MalformedURLException e )
{
throw new IllegalArgumentException( fileParam + " is a malformed URL" );
}
}
else
{
throw new IllegalArgumentException( "Either the 'url' or the 'file' param has to be given." );
}
StringBuffer snippet;
try
{
snippet = getSnippet( url, id );
}
catch ( IOException e )
{
throw new MacroExecutionException( "Error reading snippet", e );
}
if ( verbatim )
{
sink.verbatim( true );
sink.text( snippet.toString() );
sink.verbatim_();
}
else {
sink.rawText( snippet.toString() );
}
}
|
diff --git a/syncronizer/src/org/ossnoize/git/fastimport/Done.java b/syncronizer/src/org/ossnoize/git/fastimport/Done.java
index c091dd8..f5468cf 100644
--- a/syncronizer/src/org/ossnoize/git/fastimport/Done.java
+++ b/syncronizer/src/org/ossnoize/git/fastimport/Done.java
@@ -1,30 +1,30 @@
/*****************************************************************************
This file is part of Git-Starteam.
Git-Starteam 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.
Git-Starteam 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 Git-Starteam. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package org.ossnoize.git.fastimport;
import java.io.IOException;
import java.io.OutputStream;
public class Done implements FastImportObject {
@Override
public void writeTo(OutputStream out) throws IOException {
- out.write("done".getBytes());
+ out.write("done\n".getBytes());
out.flush();
}
}
| true | true | public void writeTo(OutputStream out) throws IOException {
out.write("done".getBytes());
out.flush();
}
| public void writeTo(OutputStream out) throws IOException {
out.write("done\n".getBytes());
out.flush();
}
|
diff --git a/jumble/src/com/reeltwo/jumble/mutation/MutatingClassLoader.java b/jumble/src/com/reeltwo/jumble/mutation/MutatingClassLoader.java
index 6850255..c68dfc2 100644
--- a/jumble/src/com/reeltwo/jumble/mutation/MutatingClassLoader.java
+++ b/jumble/src/com/reeltwo/jumble/mutation/MutatingClassLoader.java
@@ -1,185 +1,185 @@
package com.reeltwo.jumble.mutation;
//import org.apache.bcel.util.ClassPath;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Enumeration;
import java.util.Hashtable;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.util.ClassPath;
import org.apache.bcel.util.Repository;
import org.apache.bcel.util.SyntheticRepository;
/**
* A <code>ClassLoader</code> which embeds a <code>Mutater</code> so
* that applications can be run with a single class undergoing
* mutation.
*
* @author Tin Pavlinic
* @version $Revision$
*/
public class MutatingClassLoader extends ClassLoader {
/** Used to perform the actual mutation */
private final Mutater mMutater;
/** The name of the class being mutated */
private final String mTarget;
private final String[] mIgnoredPackages = new String[] {
"java.",
//"javax.",
"sun.reflect",
"junit.",
//"org.apache",
//"org.xml",
//"org.w3c"
};
private final Hashtable<String, Class> mClasses = new Hashtable<String, Class>();
private final ClassLoader mDeferTo = ClassLoader.getSystemClassLoader();
private final Repository mRepository;
private final ClassPath mClassPath;
/** Textual description of the modification made. */
private String mModification;
/**
* Creates a new <code>MutatingClassLoader</code> instance.
*
* @param target the class name to be mutated. Other classes will
* not be mutated.
* @param mutater a <code>Mutater</code> value that will carry out
* mutations.
* @param classpath a <code>String</code> value supplying the
* classes visible to the classloader.
*/
public MutatingClassLoader(final String target, final Mutater mutater, final String classpath) {
// Add these ignored classes to work around jakarta commons logging stupidity with class loaders.
mTarget = target;
mMutater = mutater;
mClassPath = new ClassPath(classpath);
//mRepository = SyntheticRepository.getInstance();
mRepository = SyntheticRepository.getInstance(mClassPath);
mMutater.setRepository(mRepository);
}
/**
* Gets a string description of the modification produced.
*
* @return the modification
*/
public String getModification() {
return mModification;
}
public int countMutationPoints(String className) throws ClassNotFoundException {
loadClass(className);
return mMutater.countMutationPoints(className);
}
protected Class loadClass(String className, boolean resolve) throws ClassNotFoundException {
Class cl = null;
- if ((cl = (Class) mClasses.get(className)) == null) {
+ if ((cl = mClasses.get(className)) == null) {
// Classes we're forcing to be loaded by mDeferTo
for (int i = 0; i < mIgnoredPackages.length; i++) {
if (className.startsWith(mIgnoredPackages[i])) {
//System.err.println("Parent forced loading of class: " + className);
cl = mDeferTo.loadClass(className);
break;
}
}
if (cl == null) {
JavaClass clazz = null;
// Try loading from our repository
try {
if ((clazz = mRepository.loadClass(className)) != null) {
clazz = modifyClass(clazz);
}
} catch (ClassNotFoundException e) {
; // OK, because we'll let Class.forName handle it
}
if (clazz != null) {
//System.err.println("MCL loading class: " + className);
byte[] bytes = clazz.getBytes();
cl = defineClass(className, bytes, 0, bytes.length);
} else {
//cl = Class.forName(className);
//System.err.println("Parent loading of class: " + className);
cl = mDeferTo.loadClass(className);
}
}
if (resolve) {
resolveClass(cl);
}
}
mClasses.put(className, cl);
return cl;
}
/**
* If the class matches the target then it is mutated, otherwise the class if
* returned unmodified. Overrides the corresponding method in the superclass.
* Classes are cached so that we always load a fresh version.
*
* This method is public so we can test it
*
* @param clazz modification target
* @return possibly modified class
*/
public JavaClass modifyClass(JavaClass clazz) {
if (clazz.getClassName().equals(mTarget)) {
synchronized (mMutater) {
clazz = mMutater.jumbler(clazz);
mModification = mMutater.getModification();
}
}
return clazz;
}
@SuppressWarnings("unchecked")
public Enumeration<URL> getResources(String name) throws IOException {
Enumeration<URL> resources = mClassPath.getResources(name);
if (!resources.hasMoreElements()) {
resources = mDeferTo.getResources(name);
//System.err.println("Parent getting resources: " + name + " " + resources);
//} else {
//System.err.println("MCL getting resources: " + name + " " + resources);
}
return resources;
}
public URL getResource(String name) {
URL resource = mClassPath.getResource(name);
if (resource == null) {
resource = mDeferTo.getResource(name);
//System.err.println("Parent getting resource: " + name + " " + resource);
//} else {
//System.err.println("MCL getting resource: " + name + " " + resource);
}
return resource;
}
public InputStream getResourceAsStream(String name) {
InputStream resource = mClassPath.getResourceAsStream(name);
if (resource == null) {
resource = mDeferTo.getResourceAsStream(name);
//System.err.println("Parent getting resource as stream: " + name + " " + resource);
//} else {
//System.err.println("MCL getting resource as stream: " + name + " " + resource);
}
return resource;
}
}
| true | true | protected Class loadClass(String className, boolean resolve) throws ClassNotFoundException {
Class cl = null;
if ((cl = (Class) mClasses.get(className)) == null) {
// Classes we're forcing to be loaded by mDeferTo
for (int i = 0; i < mIgnoredPackages.length; i++) {
if (className.startsWith(mIgnoredPackages[i])) {
//System.err.println("Parent forced loading of class: " + className);
cl = mDeferTo.loadClass(className);
break;
}
}
if (cl == null) {
JavaClass clazz = null;
// Try loading from our repository
try {
if ((clazz = mRepository.loadClass(className)) != null) {
clazz = modifyClass(clazz);
}
} catch (ClassNotFoundException e) {
; // OK, because we'll let Class.forName handle it
}
if (clazz != null) {
//System.err.println("MCL loading class: " + className);
byte[] bytes = clazz.getBytes();
cl = defineClass(className, bytes, 0, bytes.length);
} else {
//cl = Class.forName(className);
//System.err.println("Parent loading of class: " + className);
cl = mDeferTo.loadClass(className);
}
}
if (resolve) {
resolveClass(cl);
}
}
mClasses.put(className, cl);
return cl;
}
| protected Class loadClass(String className, boolean resolve) throws ClassNotFoundException {
Class cl = null;
if ((cl = mClasses.get(className)) == null) {
// Classes we're forcing to be loaded by mDeferTo
for (int i = 0; i < mIgnoredPackages.length; i++) {
if (className.startsWith(mIgnoredPackages[i])) {
//System.err.println("Parent forced loading of class: " + className);
cl = mDeferTo.loadClass(className);
break;
}
}
if (cl == null) {
JavaClass clazz = null;
// Try loading from our repository
try {
if ((clazz = mRepository.loadClass(className)) != null) {
clazz = modifyClass(clazz);
}
} catch (ClassNotFoundException e) {
; // OK, because we'll let Class.forName handle it
}
if (clazz != null) {
//System.err.println("MCL loading class: " + className);
byte[] bytes = clazz.getBytes();
cl = defineClass(className, bytes, 0, bytes.length);
} else {
//cl = Class.forName(className);
//System.err.println("Parent loading of class: " + className);
cl = mDeferTo.loadClass(className);
}
}
if (resolve) {
resolveClass(cl);
}
}
mClasses.put(className, cl);
return cl;
}
|
diff --git a/common/src/org/riotfamily/common/io/AbstractTokenFilterReader.java b/common/src/org/riotfamily/common/io/AbstractTokenFilterReader.java
index 159c53994..b3d9adedb 100644
--- a/common/src/org/riotfamily/common/io/AbstractTokenFilterReader.java
+++ b/common/src/org/riotfamily/common/io/AbstractTokenFilterReader.java
@@ -1,102 +1,102 @@
/* 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.riotfamily.common.io;
import java.io.FilterReader;
import java.io.IOException;
import java.io.Reader;
/**
* Abstract base class for FilterReaders that replace <code>${placehoder}</code>
* tokens.
*
* @author Felix Gnass [fgnass at neteye dot de]
*/
public abstract class AbstractTokenFilterReader extends FilterReader {
private String replacement = null;
private int replaceIndex = -1;
public AbstractTokenFilterReader(Reader in) {
super(in);
}
@Override
public int read() throws IOException {
if (replaceIndex != -1) {
// Fill in replacement ...
int i = replacement.charAt(replaceIndex++);
if (replaceIndex == replacement.length()) {
replaceIndex = -1;
}
return i;
}
int i = super.read();
if (i != '$') {
// Normal character - no further processing is required
return i;
}
// Read ahead to check if next character is '{'
int c = super.read();
if (c != '{') {
// Just a single '$' so we set the replacement to the second char
replacement = Character.toString((char) c);
replaceIndex = 0;
return '$';
}
// We encountered a '${' sequence, so we'll read on until '}' or EOF
StringBuffer buffer = new StringBuffer();
boolean endReached = false;
while (!endReached) {
c = super.read();
endReached = c == -1 || c == '}';
if (!endReached) {
- buffer.append(c);
+ buffer.append((char) c);
}
}
if (c == -1) {
throw new IOException("EOF encountered but '}' was expected.");
}
String key = buffer.toString();
replacement = getReplacement(key);
if (replacement != null && replacement.length() > 0) {
replaceIndex = 0;
}
return read();
}
/**
* @see Reader#read(char[], int, int)
*/
@Override
public final int read(char[] cbuf, int off, int len) throws IOException {
for (int i = 0; i < len; i++) {
final int ch = read();
if (ch == -1) {
return i == 0 ? -1 : i;
}
cbuf[off + i] = (char) ch;
}
return len;
}
protected abstract String getReplacement(String key);
}
| true | true | public int read() throws IOException {
if (replaceIndex != -1) {
// Fill in replacement ...
int i = replacement.charAt(replaceIndex++);
if (replaceIndex == replacement.length()) {
replaceIndex = -1;
}
return i;
}
int i = super.read();
if (i != '$') {
// Normal character - no further processing is required
return i;
}
// Read ahead to check if next character is '{'
int c = super.read();
if (c != '{') {
// Just a single '$' so we set the replacement to the second char
replacement = Character.toString((char) c);
replaceIndex = 0;
return '$';
}
// We encountered a '${' sequence, so we'll read on until '}' or EOF
StringBuffer buffer = new StringBuffer();
boolean endReached = false;
while (!endReached) {
c = super.read();
endReached = c == -1 || c == '}';
if (!endReached) {
buffer.append(c);
}
}
if (c == -1) {
throw new IOException("EOF encountered but '}' was expected.");
}
String key = buffer.toString();
replacement = getReplacement(key);
if (replacement != null && replacement.length() > 0) {
replaceIndex = 0;
}
return read();
}
| public int read() throws IOException {
if (replaceIndex != -1) {
// Fill in replacement ...
int i = replacement.charAt(replaceIndex++);
if (replaceIndex == replacement.length()) {
replaceIndex = -1;
}
return i;
}
int i = super.read();
if (i != '$') {
// Normal character - no further processing is required
return i;
}
// Read ahead to check if next character is '{'
int c = super.read();
if (c != '{') {
// Just a single '$' so we set the replacement to the second char
replacement = Character.toString((char) c);
replaceIndex = 0;
return '$';
}
// We encountered a '${' sequence, so we'll read on until '}' or EOF
StringBuffer buffer = new StringBuffer();
boolean endReached = false;
while (!endReached) {
c = super.read();
endReached = c == -1 || c == '}';
if (!endReached) {
buffer.append((char) c);
}
}
if (c == -1) {
throw new IOException("EOF encountered but '}' was expected.");
}
String key = buffer.toString();
replacement = getReplacement(key);
if (replacement != null && replacement.length() > 0) {
replaceIndex = 0;
}
return read();
}
|
diff --git a/org.dawnsci.plotting/src/org/dawnsci/plotting/PlottingActionBarManager.java b/org.dawnsci.plotting/src/org/dawnsci/plotting/PlottingActionBarManager.java
index d5b7e3908..ae873b567 100644
--- a/org.dawnsci.plotting/src/org/dawnsci/plotting/PlottingActionBarManager.java
+++ b/org.dawnsci.plotting/src/org/dawnsci/plotting/PlottingActionBarManager.java
@@ -1,785 +1,791 @@
package org.dawnsci.plotting;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.dawnsci.plotting.actions.ActionBarWrapper;
import org.dawnsci.plotting.actions.EmptyActionBars;
import org.dawnsci.plotting.api.ActionType;
import org.dawnsci.plotting.api.EmptyPageSite;
import org.dawnsci.plotting.api.IPlotActionSystem;
import org.dawnsci.plotting.api.IPlottingSystem;
import org.dawnsci.plotting.api.ITraceActionProvider;
import org.dawnsci.plotting.api.ManagerType;
import org.dawnsci.plotting.api.PlotType;
import org.dawnsci.plotting.api.tool.IToolChangeListener;
import org.dawnsci.plotting.api.tool.IToolPage;
import org.dawnsci.plotting.api.tool.IToolPage.ToolPageRole;
import org.dawnsci.plotting.api.tool.ToolChangeEvent;
import org.dawnsci.plotting.api.trace.ITrace;
import org.dawnsci.plotting.views.EmptyTool;
import org.eclipse.core.runtime.IConfigurationElement;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.action.IContributionManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IViewPart;
import org.eclipse.ui.IViewReference;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.osgi.framework.Bundle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Class to deal with the actions we need in the plotting system.
*
* This class provides generic actions which are read from extension points, such as tool actions.
*
* This class provides switching between actions registered in different roles.
*
* @author fcp94556
*
*/
public class PlottingActionBarManager implements IPlotActionSystem {
private static final Logger logger = LoggerFactory.getLogger(PlottingActionBarManager.class);
// Extrac actions for 1D and image viewing
protected Map<String, IToolPage> toolPages;
protected AbstractPlottingSystem system;
protected Map<ActionType, List<ActionContainer>> actionMap;
protected MenuAction imageMenu;
protected MenuAction xyMenu;
protected ITraceActionProvider traceActionProvider;
public PlottingActionBarManager(AbstractPlottingSystem system) {
this.system = system;
this.actionMap = new HashMap<ActionType, List<ActionContainer>>(ActionType.values().length);
}
private final static String defaultGroupName = "org.dawb.common.ui.plot.groupAll";
/**
*
* @param traceActionProvider may be null
*/
public void init(ITraceActionProvider traceActionProvider) {
system.getActionBars().getToolBarManager().add(new Separator(system.getPlotName()+"/"+defaultGroupName));
system.getActionBars().getMenuManager().add(new Separator(system.getPlotName()+"/"+defaultGroupName));
xyMenu = new MenuAction("X/Y Plot");
if (system.getActionBars()!=null) {
system.getActionBars().getMenuManager().add(xyMenu);
system.getActionBars().getMenuManager().add(new Separator());
}
imageMenu = new MenuAction("Image");
if (system.getActionBars()!=null) {
system.getActionBars().getMenuManager().add(imageMenu);
system.getActionBars().getMenuManager().add(new Separator());
}
this.traceActionProvider = traceActionProvider;
}
private PlotType lastPlotTypeUpdate = null;
public boolean switchActions(final PlotType type) {
if (type == lastPlotTypeUpdate) return false;
try {
final IActionBars bars = system.getActionBars();
if (bars==null) return false;
imageMenu.setEnabled(type==PlotType.IMAGE);
xyMenu.setEnabled(type.is1D());
for (ActionType actionType : ActionType.values()) {
final List<ActionContainer> actions = actionMap.get(actionType);
if (actions!=null) for (ActionContainer ac : actions) {
if (actionType.isCompatible(type)) {
ac.insert(false);
} else {
ac.remove();
}
}
}
// If we are 1D we must deactivate 2D tools. If we are
// 2D we must deactivate 1D tools.
IAction action = null;
if (type.is1D()) {
clearTool(ToolPageRole.ROLE_2D);
clearTool(ToolPageRole.ROLE_3D);
action = findAction(ToolPageRole.ROLE_1D.getId());
} else if (type.is2D()) {
clearTool(ToolPageRole.ROLE_1D);
clearTool(ToolPageRole.ROLE_3D);
action = findAction(ToolPageRole.ROLE_2D.getId());
} else if (type.is3D()) {
clearTool(ToolPageRole.ROLE_1D);
clearTool(ToolPageRole.ROLE_2D);
action = findAction(ToolPageRole.ROLE_3D.getId());
}
if (action instanceof MenuAction) {
((MenuAction)action).run();
}
firePropertyChangeListeners(new PropertyChangeEvent(this, "PlotType", lastPlotTypeUpdate, type));
if (bars.getToolBarManager()!=null) bars.getToolBarManager().update(true);
if (bars.getMenuManager()!=null) bars.getMenuManager().update(true);
if (bars.getStatusLineManager()!=null) bars.getStatusLineManager().update(true);
bars.updateActionBars();
return true;
} finally {
lastPlotTypeUpdate = type;
}
}
private Collection<IPropertyChangeListener> listeners;
public void addPropertyChangeListener(IPropertyChangeListener listener) {
if (listeners==null) listeners = new ArrayList<IPropertyChangeListener>(7);
listeners.add(listener);
}
public void removePropertyChangeListener(IPropertyChangeListener listener) {
if (listeners==null) return;
listeners.remove(listener);
}
protected void firePropertyChangeListeners(PropertyChangeEvent event) {
if (listeners==null) return;
for (IPropertyChangeListener l : listeners) {
l.propertyChange(event);
}
}
/**
* Set groups of actions visible.
*
* @param visMap groupId to Boolean, visible = true
*/
public void updateGroupVisibility(Map<String, Boolean> visMap) {
final PlotType type = system.getPlotType();
for (ActionType actionType : ActionType.values()) {
final List<ActionContainer> actions = actionMap.get(actionType);
if (actions!=null) for (ActionContainer ac : actions) {
String groupId = ac.getGroupId().substring(ac.getGroupId().indexOf('/')+1);
if (visMap.containsKey(groupId)) {
if (visMap.get(groupId) && actionType.isCompatible(type)) {
ac.insert(false);
} else {
ac.remove();
}
}
}
}
getActionBars().getToolBarManager().update(true);
}
public IActionBars createEmptyActionBars() {
return new EmptyActionBars();
}
public void dispose() {
if (listeners!=null) listeners.clear();
if (toolPages!=null) toolPages.clear();
toolPages = null;
actionMap.clear();
}
private boolean isToolsRequired = true;
public void setToolsRequired(boolean isToolsRequired) {
this.isToolsRequired = isToolsRequired;
}
public void createToolDimensionalActions(final ToolPageRole role,
final String viewId) {
final IActionBars bars = system.getActionBars();
if (bars!=null) {
try {
MenuAction toolSet = createToolActions(role, viewId);
if (toolSet==null) return;
if (role.is1D()&&!role.is2D()) {
final String groupName=role.getId();
registerToolBarGroup(groupName);
registerAction(groupName, toolSet, ActionType.XY);
}
if (role.is2D()&&!role.is1D()) {
final String groupName=role.getId();
registerToolBarGroup(groupName);
registerAction(groupName, toolSet, ActionType.IMAGE);
}
if (role.is3D()) {
final String groupName=role.getId();
registerToolBarGroup(groupName);
registerAction(groupName, toolSet, ActionType.THREED);
}
if (role.is2D()) {
toolSet.addActionsTo(imageMenu);
this.imageMenu.addSeparator();
}
if (role.is1D()) {
toolSet.addActionsTo(xyMenu);
this.xyMenu.addSeparator();
}
} catch (Exception e) {
logger.error("Reading extensions for plotting tools", e);
}
}
}
/**
* Return a MenuAction which can be attached to the part using the plotting system.
*
*
* @return
*/
protected MenuAction createToolActions(final ToolPageRole role, final String viewId) throws Exception {
if (!isToolsRequired) return null;
final IWorkbenchPart part = system.getPart();
if (part==null) return null;
final MenuAction toolActions = new MenuAction(role.getLabel());
toolActions.setToolTipText(role.getTooltip());
toolActions.setImageDescriptor(Activator.getImageDescriptor(role.getImagePath()));
toolActions.setId(role.getId());
// This list will not be large so we loop over it more than once for each ToolPageRole type
final IConfigurationElement[] configs = Platform.getExtensionRegistry().getConfigurationElementsFor("org.dawnsci.plotting.api.toolPage");
boolean foundSomeActions = false;
for (final IConfigurationElement e : configs) {
foundSomeActions = true;
// Check if tool should not have action
if ("false".equals(e.getAttribute("visible"))) continue;
final IToolPage tool = createToolPage(e, role);
if (tool==null) continue;
final Action action= new Action(tool.getTitle()) {
public void run() {
IToolPage registeredTool = toolPages.get(tool.getToolId());
if (registeredTool==null || registeredTool.isDisposed()) registeredTool = createToolPage(e, role);
if (toolComposite!=null) {
createToolOnComposite(registeredTool);
} else {
createToolOnView(registeredTool, viewId);
}
final IToolPage old = system.getCurrentToolPage(role);
system.setCurrentToolPage(registeredTool);
system.clearRegionTool();
system.fireToolChangeListeners(new ToolChangeEvent(this, old, registeredTool, system.getPart()));
toolActions.setSelectedAction(this);
+ // Fix to http://jira.diamond.ac.uk/browse/SCI-600
+ if (!Boolean.getBoolean("org.dawnsci.plotting.no.tool.activation")) {
+ if (system.getPart()!=null) {
+ getPage().activate(system.getPart());
+ }
+ }
}
};
action.setId(e.getAttribute("id"));
final String icon = e.getAttribute("icon");
if (icon!=null) {
final String id = e.getContributor().getName();
final Bundle bundle= Platform.getBundle(id);
final URL entry = bundle.getEntry(icon);
final ImageDescriptor des = ImageDescriptor.createFromURL(entry);
action.setImageDescriptor(des);
tool.setImageDescriptor(des);
}
final String tooltip = e.getAttribute("tooltip");
if (tooltip!=null) action.setToolTipText(tooltip);
toolActions.add(action);
}
if (!foundSomeActions) return null;
if (toolActions.size()<1) return null; // Nothing to show!
final Action clear = new Action("Clear tool") {
public void run() {
clearTool(role);
toolActions.setSelectedAction(this);
}
};
clear.setImageDescriptor(Activator.getImageDescriptor("icons/axis.png"));
clear.setToolTipText("Clear tool previously used if any.");
toolActions.add(clear);
return toolActions;
}
private Composite toolComposite;
private Map<String,Composite> toolPseudoRecs;
protected void createToolOnComposite(IToolPage registeredTool) {
if (toolPseudoRecs==null) {
toolComposite.setLayout(new StackLayout());
toolPseudoRecs = new HashMap<String, Composite>(7);
}
String toolId = registeredTool.getToolId();
if (toolId!=null) {
IToolPage tool = system.getToolPage(toolId);
IToolPage old = system.getCurrentToolPage(tool.getToolPageRole());
if (!toolPseudoRecs.containsKey(tool.getToolId())) {
try {
final Composite toolPseudoRec = new Composite(toolComposite, SWT.NONE);
toolPseudoRec.setLayout(new GridLayout(1, false));
removeMargins(toolPseudoRec);
ActionBarWrapper toolWrapper = ActionBarWrapper.createActionBars(toolPseudoRec, new EmptyActionBars());
tool.init(new EmptyPageSite(toolPseudoRec.getShell(), toolWrapper));
final Composite toolContent = new Composite(toolPseudoRec, SWT.NONE);
toolContent.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
toolContent.setLayout(new FillLayout());
tool.createControl(toolContent);
toolPseudoRecs.put(tool.getToolId(), toolPseudoRec);
toolWrapper.update(true);
} catch (PartInitException e) {
logger.error("Cannot init "+toolId, e);
}
}
StackLayout stack = (StackLayout)toolComposite.getLayout();
stack.topControl = toolPseudoRecs.get(tool.getToolId());
toolComposite.layout();
if (old!=null && old.isActive()) old.deactivate();
tool.activate();
system.fireToolChangeListeners(new ToolChangeEvent(this, old, tool, system.getPart()));
}
}
private static void removeMargins(Composite area) {
final GridLayout layout = (GridLayout)area.getLayout();
if (layout==null) return;
layout.horizontalSpacing=0;
layout.verticalSpacing =0;
layout.marginBottom =0;
layout.marginTop =0;
layout.marginLeft =0;
layout.marginRight =0;
layout.marginHeight =0;
layout.marginWidth =0;
}
protected void createToolOnView(IToolPage registeredTool, String viewId) {
// If we have a dedicated tool for this tool, we do not open another
String toolId = registeredTool.getToolId();
if (toolId!=null) {
IViewReference ref = getPage().findViewReference("org.dawb.workbench.plotting.views.toolPageView.fixed", toolId);
if (ref!=null) {
final IViewPart view = ref.getView(true);
getPage().activate(view);
return;
}
if (registeredTool.isAlwaysSeparateView()) {
try {
final IViewPart view = getPage().showView("org.dawb.workbench.plotting.views.toolPageView.fixed",
toolId,
IWorkbenchPage.VIEW_ACTIVATE);
getPage().activate(view);
return;
} catch (PartInitException e1) {
logger.error("Cannot open fixed view for "+toolId, e1);
}
}
}
IViewPart viewPart=null;
try {
viewPart = getActivePage().showView(viewId);
if (viewPart!=null && viewPart instanceof IToolChangeListener) {
system.addToolChangeListener((IToolChangeListener)viewPart);
}
} catch (PartInitException e) {
logger.error("Cannot find a view with id org.dawb.workbench.plotting.views.ToolPageView", e);
}
}
protected void clearTool(ToolPageRole role) {
final IToolPage old = system.getCurrentToolPage(role);
final EmptyTool empty = system.getEmptyTool(role);
system.setCurrentToolPage(empty);
system.clearRegionTool();
system.fireToolChangeListeners(new ToolChangeEvent(this, old, empty, system.getPart()));
}
/**
*
* @param e
* @param role, may be null
* @return
*/
private IToolPage createToolPage(IConfigurationElement e, ToolPageRole role) {
IToolPage tool = null;
try {
tool = (IToolPage)e.createExecutableExtension("class");
} catch (Throwable ne) {
logger.error("Cannot create tool page "+e.getAttribute("class"), ne);
return null;
}
if (role==null) role = tool.getToolPageRole();
tool.setToolId(e.getAttribute("id"));
if (tool.getToolPageRole()!=role) return null;
tool.setToolSystem(system);
tool.setPlottingSystem(system);
tool.setTitle(e.getAttribute("label"));
tool.setPart(system.getPart());
tool.setCheatSheetId(e.getAttribute("cheat_sheet_id"));
// Save tool page
if (toolPages==null) toolPages = new HashMap<String, IToolPage>(7);
toolPages.put(tool.getToolId(), tool);
return tool;
}
protected IToolPage getToolPage(final String id) {
if (toolPages==null) return null;
if (id==null) return null;
IToolPage page = toolPages.get(id);
if (page==null) {
final IConfigurationElement[] configs = Platform.getExtensionRegistry().getConfigurationElementsFor("org.dawnsci.plotting.api.toolPage");
for (final IConfigurationElement e : configs) {
if (id.equals(e.getAttribute("id"))) {
page = createToolPage(e, null);
break;
}
}
}
return page;
}
public void disposeToolPage(String id) throws Exception {
if (toolPages==null) return;
if (id==null) return;
IToolPage page = toolPages.get(id);
if (page==null) return;
if (page.getControl()==null) return; // Already is a stub
IToolPage clone = page.cloneTool();
page.dispose();
toolPages.put(clone.getToolId(), clone);
}
/**
* returns false if no tool was shown
* @param toolId
* @return
* @throws Exception
*/
public boolean setToolVisible(final String toolId, final ToolPageRole role, final String viewId) throws Exception {
final IConfigurationElement[] configs = Platform.getExtensionRegistry().getConfigurationElementsFor("org.dawnsci.plotting.api.toolPage");
for (IConfigurationElement e : configs) {
if (!toolId.equals(e.getAttribute("id"))) continue;
final IToolPage page = (IToolPage)e.createExecutableExtension("class");
if (page.getToolPageRole()!=role) continue;
final String label = e.getAttribute("label");
page.setToolSystem(system);
page.setPlottingSystem(system);
page.setTitle(label);
page.setPart(system.getPart());
page.setToolId(toolId);
if (toolComposite!=null) {
createToolOnComposite(page);
} else {
createToolOnView(page, viewId);
}
final IToolPage old = system.getCurrentToolPage(role);
system.setCurrentToolPage(page);
system.clearRegionTool();
system.fireToolChangeListeners(new ToolChangeEvent(this, old, page, system.getPart()));
return true;
}
return false;
}
public void addXYAction(IAction a) {
xyMenu.add(a);
}
public void addXYSeparator() {
xyMenu.addSeparator();
}
public void addImageAction(IAction a) {
imageMenu.add(a);
}
public void addImageSeparator() {
imageMenu.addSeparator();
}
public void registerToolBarGroup(final String groupName) {
registerGroup(groupName, ManagerType.TOOLBAR);
}
public void registerMenuBarGroup(final String groupName) {
registerGroup(groupName, ManagerType.MENUBAR);
}
public void registerGroup(String groupName, ManagerType type) {
groupName = system.getPlotName()+"/"+groupName;
if (getActionBars()!=null) {
IContributionManager man=null;
if (type==ManagerType.TOOLBAR) {
man = getActionBars().getToolBarManager();
} else {
man = getActionBars().getMenuManager();
}
if (man.find(groupName)!=null) {
man.remove(groupName);
}
final Separator group = new Separator(groupName);
man.add(group);
}
}
public void registerAction(IAction action, ActionType actionType) {
registerAction(defaultGroupName, action, actionType);
}
public void registerAction(IAction action, ActionType actionType, ManagerType manType) {
registerAction(defaultGroupName, action, actionType, manType);
}
/**
* Registers with the toolbar
* @param groupName
* @param action
* @return
*/
public void registerAction(String groupName, IAction action, ActionType actionType) {
registerAction(groupName, action, actionType, ManagerType.TOOLBAR);
}
public void registerAction(String groupName, IAction action, ActionType actionType, ManagerType manType) {
groupName = system.getPlotName()+"/"+groupName;
// We generate an id!
if (action.getId()==null) {
action.setId(groupName+action.getText());
}
final IContributionManager man = manType==ManagerType.MENUBAR
? getActionBars().getMenuManager()
: getActionBars().getToolBarManager();
final ActionContainer ac = new ActionContainer(groupName, action, man);
List<ActionContainer> actions = actionMap.get(actionType);
if (actions==null) {
actions = new ArrayList<ActionContainer>(7);
actionMap.put(actionType, actions);
}
actions.add(ac);
ac.insert(true);
}
private IActionBars getActionBars() {
return system.getActionBars();
}
@Override
public void fillZoomActions(IContributionManager man) {
// TODO Auto-generated method stub
}
@Override
public void fillRegionActions(IContributionManager man) {
// TODO Auto-generated method stub
}
@Override
public void fillUndoActions(IContributionManager man) {
// TODO Auto-generated method stub
}
@Override
public void fillPrintActions(IContributionManager man) {
// TODO Auto-generated method stub
}
@Override
public void fillAnnotationActions(IContributionManager man) {
// TODO Auto-generated method stub
}
@Override
public void fillToolActions(IContributionManager man, ToolPageRole role) {
// TODO Auto-generated method stub
}
@Override
public void fillTraceActions(IContributionManager toolBarManager, ITrace trace, IPlottingSystem system) {
if (traceActionProvider!=null) traceActionProvider.fillTraceActions(toolBarManager, trace, system);
}
@Override
public void remove(String id) {
//super.remove(id);
for (ActionType actionType : ActionType.values()) {
final List<ActionContainer> actions = actionMap.get(actionType);
if (actions!=null) {
for (Iterator<ActionContainer> it= actions.iterator(); it.hasNext(); ) {
ActionContainer ac = it.next();
if (ac.isId(id)) it.remove();
}
}
}
if (system.getActionBars()!=null) {
system.getActionBars().getToolBarManager().remove(id);
system.getActionBars().getMenuManager().remove(id);
system.getActionBars().getStatusLineManager().remove(id);
}
}
/**
* Returns the first action with the id
* @param string
* @return
*/
public IAction findAction(String id) {
for (ActionType actionType : ActionType.values()) {
final List<ActionContainer> actions = actionMap.get(actionType);
if (actions!=null) {
for (Iterator<ActionContainer> it= actions.iterator(); it.hasNext(); ) {
ActionContainer ac = it.next();
if (ac.isId(id)) return ac.getAction();
}
}
}
return null;
}
/**
* Sets specific widget for using to show tools on rather than pages.
* @param toolComposite
*/
public void setToolComposite(Composite toolComposite) {
this.toolComposite = toolComposite;
}
public static IWorkbenchPage getPage() {
IWorkbenchPage activePage = getActivePage();
if (activePage!=null) return activePage;
return getDefaultPage();
}
/**
* @return IWorkbenchPage
*/
public static IWorkbenchPage getActivePage() {
final IWorkbench bench = PlatformUI.getWorkbench();
if (bench==null) return null;
final IWorkbenchWindow window = bench.getActiveWorkbenchWindow();
if (window==null) return null;
return window.getActivePage();
}
/**
* @return IWorkbenchPage
*/
public static IWorkbenchPage getDefaultPage() {
final IWorkbench bench = PlatformUI.getWorkbench();
if (bench==null) return null;
final IWorkbenchWindow[] windows = bench.getWorkbenchWindows();
if (windows==null) return null;
return windows[0].getActivePage();
}
}
| true | true | protected MenuAction createToolActions(final ToolPageRole role, final String viewId) throws Exception {
if (!isToolsRequired) return null;
final IWorkbenchPart part = system.getPart();
if (part==null) return null;
final MenuAction toolActions = new MenuAction(role.getLabel());
toolActions.setToolTipText(role.getTooltip());
toolActions.setImageDescriptor(Activator.getImageDescriptor(role.getImagePath()));
toolActions.setId(role.getId());
// This list will not be large so we loop over it more than once for each ToolPageRole type
final IConfigurationElement[] configs = Platform.getExtensionRegistry().getConfigurationElementsFor("org.dawnsci.plotting.api.toolPage");
boolean foundSomeActions = false;
for (final IConfigurationElement e : configs) {
foundSomeActions = true;
// Check if tool should not have action
if ("false".equals(e.getAttribute("visible"))) continue;
final IToolPage tool = createToolPage(e, role);
if (tool==null) continue;
final Action action= new Action(tool.getTitle()) {
public void run() {
IToolPage registeredTool = toolPages.get(tool.getToolId());
if (registeredTool==null || registeredTool.isDisposed()) registeredTool = createToolPage(e, role);
if (toolComposite!=null) {
createToolOnComposite(registeredTool);
} else {
createToolOnView(registeredTool, viewId);
}
final IToolPage old = system.getCurrentToolPage(role);
system.setCurrentToolPage(registeredTool);
system.clearRegionTool();
system.fireToolChangeListeners(new ToolChangeEvent(this, old, registeredTool, system.getPart()));
toolActions.setSelectedAction(this);
}
};
action.setId(e.getAttribute("id"));
final String icon = e.getAttribute("icon");
if (icon!=null) {
final String id = e.getContributor().getName();
final Bundle bundle= Platform.getBundle(id);
final URL entry = bundle.getEntry(icon);
final ImageDescriptor des = ImageDescriptor.createFromURL(entry);
action.setImageDescriptor(des);
tool.setImageDescriptor(des);
}
final String tooltip = e.getAttribute("tooltip");
if (tooltip!=null) action.setToolTipText(tooltip);
toolActions.add(action);
}
if (!foundSomeActions) return null;
if (toolActions.size()<1) return null; // Nothing to show!
final Action clear = new Action("Clear tool") {
public void run() {
clearTool(role);
toolActions.setSelectedAction(this);
}
};
clear.setImageDescriptor(Activator.getImageDescriptor("icons/axis.png"));
clear.setToolTipText("Clear tool previously used if any.");
toolActions.add(clear);
return toolActions;
}
| protected MenuAction createToolActions(final ToolPageRole role, final String viewId) throws Exception {
if (!isToolsRequired) return null;
final IWorkbenchPart part = system.getPart();
if (part==null) return null;
final MenuAction toolActions = new MenuAction(role.getLabel());
toolActions.setToolTipText(role.getTooltip());
toolActions.setImageDescriptor(Activator.getImageDescriptor(role.getImagePath()));
toolActions.setId(role.getId());
// This list will not be large so we loop over it more than once for each ToolPageRole type
final IConfigurationElement[] configs = Platform.getExtensionRegistry().getConfigurationElementsFor("org.dawnsci.plotting.api.toolPage");
boolean foundSomeActions = false;
for (final IConfigurationElement e : configs) {
foundSomeActions = true;
// Check if tool should not have action
if ("false".equals(e.getAttribute("visible"))) continue;
final IToolPage tool = createToolPage(e, role);
if (tool==null) continue;
final Action action= new Action(tool.getTitle()) {
public void run() {
IToolPage registeredTool = toolPages.get(tool.getToolId());
if (registeredTool==null || registeredTool.isDisposed()) registeredTool = createToolPage(e, role);
if (toolComposite!=null) {
createToolOnComposite(registeredTool);
} else {
createToolOnView(registeredTool, viewId);
}
final IToolPage old = system.getCurrentToolPage(role);
system.setCurrentToolPage(registeredTool);
system.clearRegionTool();
system.fireToolChangeListeners(new ToolChangeEvent(this, old, registeredTool, system.getPart()));
toolActions.setSelectedAction(this);
// Fix to http://jira.diamond.ac.uk/browse/SCI-600
if (!Boolean.getBoolean("org.dawnsci.plotting.no.tool.activation")) {
if (system.getPart()!=null) {
getPage().activate(system.getPart());
}
}
}
};
action.setId(e.getAttribute("id"));
final String icon = e.getAttribute("icon");
if (icon!=null) {
final String id = e.getContributor().getName();
final Bundle bundle= Platform.getBundle(id);
final URL entry = bundle.getEntry(icon);
final ImageDescriptor des = ImageDescriptor.createFromURL(entry);
action.setImageDescriptor(des);
tool.setImageDescriptor(des);
}
final String tooltip = e.getAttribute("tooltip");
if (tooltip!=null) action.setToolTipText(tooltip);
toolActions.add(action);
}
if (!foundSomeActions) return null;
if (toolActions.size()<1) return null; // Nothing to show!
final Action clear = new Action("Clear tool") {
public void run() {
clearTool(role);
toolActions.setSelectedAction(this);
}
};
clear.setImageDescriptor(Activator.getImageDescriptor("icons/axis.png"));
clear.setToolTipText("Clear tool previously used if any.");
toolActions.add(clear);
return toolActions;
}
|
diff --git a/org.eclipse.jgit/src/org/eclipse/jgit/storage/file/PackFile.java b/org.eclipse.jgit/src/org/eclipse/jgit/storage/file/PackFile.java
index 99637ee6..ed159ef3 100644
--- a/org.eclipse.jgit/src/org/eclipse/jgit/storage/file/PackFile.java
+++ b/org.eclipse.jgit/src/org/eclipse/jgit/storage/file/PackFile.java
@@ -1,927 +1,927 @@
/*
* Copyright (C) 2008-2009, Google Inc.
* Copyright (C) 2007, Robin Rosenberg <[email protected]>
* Copyright (C) 2006-2008, Shawn O. Pearce <[email protected]>
* and other copyright owners as documented in the project's IP log.
*
* This program and the accompanying materials are made available
* under the terms of the Eclipse Distribution License v1.0 which
* accompanies this distribution, is reproduced below, and is
* available at http://www.eclipse.org/org/documents/edl-v10.php
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* - Neither the name of the Eclipse Foundation, Inc. nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
* CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.eclipse.jgit.storage.file;
import java.io.EOFException;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel.MapMode;
import java.text.MessageFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.zip.CRC32;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;
import org.eclipse.jgit.JGitText;
import org.eclipse.jgit.errors.CorruptObjectException;
import org.eclipse.jgit.errors.MissingObjectException;
import org.eclipse.jgit.errors.PackInvalidException;
import org.eclipse.jgit.errors.PackMismatchException;
import org.eclipse.jgit.errors.StoredObjectRepresentationNotAvailableException;
import org.eclipse.jgit.lib.AbbreviatedObjectId;
import org.eclipse.jgit.lib.AnyObjectId;
import org.eclipse.jgit.lib.Constants;
import org.eclipse.jgit.lib.ObjectId;
import org.eclipse.jgit.lib.ObjectLoader;
import org.eclipse.jgit.storage.pack.BinaryDelta;
import org.eclipse.jgit.storage.pack.ObjectToPack;
import org.eclipse.jgit.storage.pack.PackOutputStream;
import org.eclipse.jgit.util.LongList;
import org.eclipse.jgit.util.NB;
import org.eclipse.jgit.util.RawParseUtils;
/**
* A Git version 2 pack file representation. A pack file contains Git objects in
* delta packed format yielding high compression of lots of object where some
* objects are similar.
*/
public class PackFile implements Iterable<PackIndex.MutableEntry> {
/** Sorts PackFiles to be most recently created to least recently created. */
public static Comparator<PackFile> SORT = new Comparator<PackFile>() {
public int compare(final PackFile a, final PackFile b) {
return b.packLastModified - a.packLastModified;
}
};
private final File idxFile;
private final File packFile;
final int hash;
private RandomAccessFile fd;
/** Serializes reads performed against {@link #fd}. */
private final Object readLock = new Object();
long length;
private int activeWindows;
private int activeCopyRawData;
private int packLastModified;
private volatile boolean invalid;
private byte[] packChecksum;
private PackIndex loadedIdx;
private PackReverseIndex reverseIdx;
/**
* Objects we have tried to read, and discovered to be corrupt.
* <p>
* The list is allocated after the first corruption is found, and filled in
* as more entries are discovered. Typically this list is never used, as
* pack files do not usually contain corrupt objects.
*/
private volatile LongList corruptObjects;
/**
* Construct a reader for an existing, pre-indexed packfile.
*
* @param idxFile
* path of the <code>.idx</code> file listing the contents.
* @param packFile
* path of the <code>.pack</code> file holding the data.
*/
public PackFile(final File idxFile, final File packFile) {
this.idxFile = idxFile;
this.packFile = packFile;
this.packLastModified = (int) (packFile.lastModified() >> 10);
// Multiply by 31 here so we can more directly combine with another
// value in WindowCache.hash(), without doing the multiply there.
//
hash = System.identityHashCode(this) * 31;
length = Long.MAX_VALUE;
}
private synchronized PackIndex idx() throws IOException {
if (loadedIdx == null) {
if (invalid)
throw new PackInvalidException(packFile);
try {
final PackIndex idx = PackIndex.open(idxFile);
if (packChecksum == null)
packChecksum = idx.packChecksum;
else if (!Arrays.equals(packChecksum, idx.packChecksum))
throw new PackMismatchException(JGitText.get().packChecksumMismatch);
loadedIdx = idx;
} catch (IOException e) {
invalid = true;
throw e;
}
}
return loadedIdx;
}
/** @return the File object which locates this pack on disk. */
public File getPackFile() {
return packFile;
}
/**
* Determine if an object is contained within the pack file.
* <p>
* For performance reasons only the index file is searched; the main pack
* content is ignored entirely.
* </p>
*
* @param id
* the object to look for. Must not be null.
* @return true if the object is in this pack; false otherwise.
* @throws IOException
* the index file cannot be loaded into memory.
*/
public boolean hasObject(final AnyObjectId id) throws IOException {
final long offset = idx().findOffset(id);
return 0 < offset && !isCorrupt(offset);
}
/**
* Get an object from this pack.
*
* @param curs
* temporary working space associated with the calling thread.
* @param id
* the object to obtain from the pack. Must not be null.
* @return the object loader for the requested object if it is contained in
* this pack; null if the object was not found.
* @throws IOException
* the pack file or the index could not be read.
*/
ObjectLoader get(final WindowCursor curs, final AnyObjectId id)
throws IOException {
final long offset = idx().findOffset(id);
return 0 < offset && !isCorrupt(offset) ? load(curs, offset) : null;
}
void resolve(Set<ObjectId> matches, AbbreviatedObjectId id, int matchLimit)
throws IOException {
idx().resolve(matches, id, matchLimit);
}
/**
* Close the resources utilized by this repository
*/
public void close() {
UnpackedObjectCache.purge(this);
WindowCache.purge(this);
synchronized (this) {
loadedIdx = null;
reverseIdx = null;
}
}
/**
* Provide iterator over entries in associated pack index, that should also
* exist in this pack file. Objects returned by such iterator are mutable
* during iteration.
* <p>
* Iterator returns objects in SHA-1 lexicographical order.
* </p>
*
* @return iterator over entries of associated pack index
*
* @see PackIndex#iterator()
*/
public Iterator<PackIndex.MutableEntry> iterator() {
try {
return idx().iterator();
} catch (IOException e) {
return Collections.<PackIndex.MutableEntry> emptyList().iterator();
}
}
/**
* Obtain the total number of objects available in this pack. This method
* relies on pack index, giving number of effectively available objects.
*
* @return number of objects in index of this pack, likewise in this pack
* @throws IOException
* the index file cannot be loaded into memory.
*/
long getObjectCount() throws IOException {
return idx().getObjectCount();
}
/**
* Search for object id with the specified start offset in associated pack
* (reverse) index.
*
* @param offset
* start offset of object to find
* @return object id for this offset, or null if no object was found
* @throws IOException
* the index file cannot be loaded into memory.
*/
ObjectId findObjectForOffset(final long offset) throws IOException {
return getReverseIdx().findObject(offset);
}
private final UnpackedObjectCache.Entry readCache(final long position) {
return UnpackedObjectCache.get(this, position);
}
private final void saveCache(final long position, final byte[] data, final int type) {
UnpackedObjectCache.store(this, position, data, type);
}
private final byte[] decompress(final long position, final long totalSize,
final WindowCursor curs) throws IOException, DataFormatException {
final byte[] dstbuf = new byte[(int) totalSize];
if (curs.inflate(this, position, dstbuf, 0) != totalSize)
throw new EOFException(MessageFormat.format(JGitText.get().shortCompressedStreamAt, position));
return dstbuf;
}
final void copyAsIs(PackOutputStream out, LocalObjectToPack src,
WindowCursor curs) throws IOException,
StoredObjectRepresentationNotAvailableException {
beginCopyAsIs(src);
try {
copyAsIs2(out, src, curs);
} finally {
endCopyAsIs();
}
}
private void copyAsIs2(PackOutputStream out, LocalObjectToPack src,
WindowCursor curs) throws IOException,
StoredObjectRepresentationNotAvailableException {
final CRC32 crc1 = new CRC32();
final CRC32 crc2 = new CRC32();
final byte[] buf = out.getCopyBuffer();
// Rip apart the header so we can discover the size.
//
readFully(src.offset, buf, 0, 20, curs);
int c = buf[0] & 0xff;
final int typeCode = (c >> 4) & 7;
long inflatedLength = c & 15;
int shift = 4;
int headerCnt = 1;
while ((c & 0x80) != 0) {
c = buf[headerCnt++] & 0xff;
inflatedLength += (c & 0x7f) << shift;
shift += 7;
}
if (typeCode == Constants.OBJ_OFS_DELTA) {
do {
c = buf[headerCnt++] & 0xff;
} while ((c & 128) != 0);
crc1.update(buf, 0, headerCnt);
crc2.update(buf, 0, headerCnt);
} else if (typeCode == Constants.OBJ_REF_DELTA) {
crc1.update(buf, 0, headerCnt);
crc2.update(buf, 0, headerCnt);
readFully(src.offset + headerCnt, buf, 0, 20, curs);
crc1.update(buf, 0, 20);
- crc2.update(buf, 0, headerCnt);
+ crc2.update(buf, 0, 20);
headerCnt += 20;
} else {
crc1.update(buf, 0, headerCnt);
crc2.update(buf, 0, headerCnt);
}
final long dataOffset = src.offset + headerCnt;
final long dataLength = src.length;
final long expectedCRC;
final ByteArrayWindow quickCopy;
// Verify the object isn't corrupt before sending. If it is,
// we report it missing instead.
//
try {
quickCopy = curs.quickCopy(this, dataOffset, dataLength);
if (idx().hasCRC32Support()) {
// Index has the CRC32 code cached, validate the object.
//
expectedCRC = idx().findCRC32(src);
if (quickCopy != null) {
quickCopy.crc32(crc1, dataOffset, (int) dataLength);
} else {
long pos = dataOffset;
long cnt = dataLength;
while (cnt > 0) {
final int n = (int) Math.min(cnt, buf.length);
readFully(pos, buf, 0, n, curs);
crc1.update(buf, 0, n);
pos += n;
cnt -= n;
}
}
if (crc1.getValue() != expectedCRC) {
setCorrupt(src.offset);
throw new CorruptObjectException(MessageFormat.format(
JGitText.get().objectAtHasBadZlibStream,
src.offset, getPackFile()));
}
} else {
// We don't have a CRC32 code in the index, so compute it
// now while inflating the raw data to get zlib to tell us
// whether or not the data is safe.
//
Inflater inf = curs.inflater();
byte[] tmp = new byte[1024];
if (quickCopy != null) {
quickCopy.check(inf, tmp, dataOffset, (int) dataLength);
} else {
long pos = dataOffset;
long cnt = dataLength;
while (cnt > 0) {
final int n = (int) Math.min(cnt, buf.length);
readFully(pos, buf, 0, n, curs);
crc1.update(buf, 0, n);
inf.setInput(buf, 0, n);
while (inf.inflate(tmp, 0, tmp.length) > 0)
continue;
pos += n;
cnt -= n;
}
}
if (!inf.finished() || inf.getBytesRead() != dataLength) {
setCorrupt(src.offset);
throw new EOFException(MessageFormat.format(
JGitText.get().shortCompressedStreamAt,
src.offset));
}
expectedCRC = crc1.getValue();
}
} catch (DataFormatException dataFormat) {
setCorrupt(src.offset);
CorruptObjectException corruptObject = new CorruptObjectException(
MessageFormat.format(
JGitText.get().objectAtHasBadZlibStream,
src.offset, getPackFile()));
corruptObject.initCause(dataFormat);
StoredObjectRepresentationNotAvailableException gone;
gone = new StoredObjectRepresentationNotAvailableException(src);
gone.initCause(corruptObject);
throw gone;
} catch (IOException ioError) {
StoredObjectRepresentationNotAvailableException gone;
gone = new StoredObjectRepresentationNotAvailableException(src);
gone.initCause(ioError);
throw gone;
}
if (quickCopy != null) {
// The entire object fits into a single byte array window slice,
// and we have it pinned. Write this out without copying.
//
out.writeHeader(src, inflatedLength);
quickCopy.write(out, dataOffset, (int) dataLength);
} else if (dataLength <= buf.length) {
// Tiny optimization: Lots of objects are very small deltas or
// deflated commits that are likely to fit in the copy buffer.
//
out.writeHeader(src, inflatedLength);
out.write(buf, 0, (int) dataLength);
} else {
// Now we are committed to sending the object. As we spool it out,
// check its CRC32 code to make sure there wasn't corruption between
// the verification we did above, and us actually outputting it.
//
out.writeHeader(src, inflatedLength);
long pos = dataOffset;
long cnt = dataLength;
while (cnt > 0) {
final int n = (int) Math.min(cnt, buf.length);
readFully(pos, buf, 0, n, curs);
crc2.update(buf, 0, n);
out.write(buf, 0, n);
pos += n;
cnt -= n;
}
if (crc2.getValue() != expectedCRC) {
throw new CorruptObjectException(MessageFormat.format(JGitText
.get().objectAtHasBadZlibStream, src.offset,
getPackFile()));
}
}
}
boolean invalid() {
return invalid;
}
private void readFully(final long position, final byte[] dstbuf,
int dstoff, final int cnt, final WindowCursor curs)
throws IOException {
if (curs.copy(this, position, dstbuf, dstoff, cnt) != cnt)
throw new EOFException();
}
private synchronized void beginCopyAsIs(ObjectToPack otp)
throws StoredObjectRepresentationNotAvailableException {
if (++activeCopyRawData == 1 && activeWindows == 0) {
try {
doOpen();
} catch (IOException thisPackNotValid) {
StoredObjectRepresentationNotAvailableException gone;
gone = new StoredObjectRepresentationNotAvailableException(otp);
gone.initCause(thisPackNotValid);
throw gone;
}
}
}
private synchronized void endCopyAsIs() {
if (--activeCopyRawData == 0 && activeWindows == 0)
doClose();
}
synchronized boolean beginWindowCache() throws IOException {
if (++activeWindows == 1) {
if (activeCopyRawData == 0)
doOpen();
return true;
}
return false;
}
synchronized boolean endWindowCache() {
final boolean r = --activeWindows == 0;
if (r && activeCopyRawData == 0)
doClose();
return r;
}
private void doOpen() throws IOException {
try {
if (invalid)
throw new PackInvalidException(packFile);
synchronized (readLock) {
fd = new RandomAccessFile(packFile, "r");
length = fd.length();
onOpenPack();
}
} catch (IOException ioe) {
openFail();
throw ioe;
} catch (RuntimeException re) {
openFail();
throw re;
} catch (Error re) {
openFail();
throw re;
}
}
private void openFail() {
activeWindows = 0;
activeCopyRawData = 0;
invalid = true;
doClose();
}
private void doClose() {
synchronized (readLock) {
if (fd != null) {
try {
fd.close();
} catch (IOException err) {
// Ignore a close event. We had it open only for reading.
// There should not be errors related to network buffers
// not flushed, etc.
}
fd = null;
}
}
}
ByteArrayWindow read(final long pos, int size) throws IOException {
synchronized (readLock) {
if (length < pos + size)
size = (int) (length - pos);
final byte[] buf = new byte[size];
fd.seek(pos);
fd.readFully(buf, 0, size);
return new ByteArrayWindow(this, pos, buf);
}
}
ByteWindow mmap(final long pos, int size) throws IOException {
synchronized (readLock) {
if (length < pos + size)
size = (int) (length - pos);
MappedByteBuffer map;
try {
map = fd.getChannel().map(MapMode.READ_ONLY, pos, size);
} catch (IOException ioe1) {
// The most likely reason this failed is the JVM has run out
// of virtual memory. We need to discard quickly, and try to
// force the GC to finalize and release any existing mappings.
//
System.gc();
System.runFinalization();
map = fd.getChannel().map(MapMode.READ_ONLY, pos, size);
}
if (map.hasArray())
return new ByteArrayWindow(this, pos, map.array());
return new ByteBufferWindow(this, pos, map);
}
}
private void onOpenPack() throws IOException {
final PackIndex idx = idx();
final byte[] buf = new byte[20];
fd.seek(0);
fd.readFully(buf, 0, 12);
if (RawParseUtils.match(buf, 0, Constants.PACK_SIGNATURE) != 4)
throw new IOException(JGitText.get().notAPACKFile);
final long vers = NB.decodeUInt32(buf, 4);
final long packCnt = NB.decodeUInt32(buf, 8);
if (vers != 2 && vers != 3)
throw new IOException(MessageFormat.format(JGitText.get().unsupportedPackVersion, vers));
if (packCnt != idx.getObjectCount())
throw new PackMismatchException(MessageFormat.format(
JGitText.get().packObjectCountMismatch, packCnt, idx.getObjectCount(), getPackFile()));
fd.seek(length - 20);
fd.read(buf, 0, 20);
if (!Arrays.equals(buf, packChecksum))
throw new PackMismatchException(MessageFormat.format(
JGitText.get().packObjectCountMismatch
, ObjectId.fromRaw(buf).name()
, ObjectId.fromRaw(idx.packChecksum).name()
, getPackFile()));
}
ObjectLoader load(final WindowCursor curs, final long pos)
throws IOException {
final byte[] ib = curs.tempId;
readFully(pos, ib, 0, 20, curs);
int c = ib[0] & 0xff;
final int type = (c >> 4) & 7;
long sz = c & 15;
int shift = 4;
int p = 1;
while ((c & 0x80) != 0) {
c = ib[p++] & 0xff;
sz += (c & 0x7f) << shift;
shift += 7;
}
try {
switch (type) {
case Constants.OBJ_COMMIT:
case Constants.OBJ_TREE:
case Constants.OBJ_BLOB:
case Constants.OBJ_TAG: {
if (sz < curs.getStreamFileThreshold()) {
byte[] data = decompress(pos + p, sz, curs);
return new ObjectLoader.SmallObject(type, data);
}
return new LargePackedWholeObject(type, sz, pos, p, this, curs.db);
}
case Constants.OBJ_OFS_DELTA: {
c = ib[p++] & 0xff;
long ofs = c & 127;
while ((c & 128) != 0) {
ofs += 1;
c = ib[p++] & 0xff;
ofs <<= 7;
ofs += (c & 127);
}
return loadDelta(pos, p, sz, pos - ofs, curs);
}
case Constants.OBJ_REF_DELTA: {
readFully(pos + p, ib, 0, 20, curs);
long ofs = findDeltaBase(ObjectId.fromRaw(ib));
return loadDelta(pos, p + 20, sz, ofs, curs);
}
default:
throw new IOException(MessageFormat.format(
JGitText.get().unknownObjectType, type));
}
} catch (DataFormatException dfe) {
CorruptObjectException coe = new CorruptObjectException(
MessageFormat.format(
JGitText.get().objectAtHasBadZlibStream, pos,
getPackFile()));
coe.initCause(dfe);
throw coe;
}
}
private long findDeltaBase(ObjectId baseId) throws IOException,
MissingObjectException {
long ofs = idx().findOffset(baseId);
if (ofs < 0)
throw new MissingObjectException(baseId,
JGitText.get().missingDeltaBase);
return ofs;
}
private ObjectLoader loadDelta(long posSelf, int hdrLen, long sz,
long posBase, WindowCursor curs) throws IOException,
DataFormatException {
if (curs.getStreamFileThreshold() <= sz) {
// The delta instruction stream itself is pretty big, and
// that implies the resulting object is going to be massive.
// Use only the large delta format here.
//
return new LargePackedDeltaObject(posSelf, posBase, hdrLen, //
this, curs.db);
}
byte[] data;
int type;
UnpackedObjectCache.Entry e = readCache(posBase);
if (e != null) {
data = e.data;
type = e.type;
} else {
ObjectLoader p = load(curs, posBase);
if (p.isLarge()) {
// The base itself is large. We have to produce a large
// delta stream as we don't want to build the whole base.
//
return new LargePackedDeltaObject(posSelf, posBase, hdrLen,
this, curs.db);
}
data = p.getCachedBytes();
type = p.getType();
saveCache(posBase, data, type);
}
// At this point we have the base, and its small, and the delta
// stream also is small, so the result object cannot be more than
// 2x our small size. This occurs if the delta instructions were
// "copy entire base, literal insert entire delta". Go with the
// faster small object style at this point.
//
data = BinaryDelta.apply(data, decompress(posSelf + hdrLen, sz, curs));
return new ObjectLoader.SmallObject(type, data);
}
byte[] getDeltaHeader(WindowCursor wc, long pos)
throws IOException, DataFormatException {
// The delta stream starts as two variable length integers. If we
// assume they are 64 bits each, we need 16 bytes to encode them,
// plus 2 extra bytes for the variable length overhead. So 18 is
// the longest delta instruction header.
//
final byte[] hdr = new byte[18];
wc.inflate(this, pos, hdr, 0);
return hdr;
}
int getObjectType(final WindowCursor curs, long pos) throws IOException {
final byte[] ib = curs.tempId;
for (;;) {
readFully(pos, ib, 0, 20, curs);
int c = ib[0] & 0xff;
final int type = (c >> 4) & 7;
int shift = 4;
int p = 1;
while ((c & 0x80) != 0) {
c = ib[p++] & 0xff;
shift += 7;
}
switch (type) {
case Constants.OBJ_COMMIT:
case Constants.OBJ_TREE:
case Constants.OBJ_BLOB:
case Constants.OBJ_TAG:
return type;
case Constants.OBJ_OFS_DELTA: {
c = ib[p++] & 0xff;
long ofs = c & 127;
while ((c & 128) != 0) {
ofs += 1;
c = ib[p++] & 0xff;
ofs <<= 7;
ofs += (c & 127);
}
pos = pos - ofs;
continue;
}
case Constants.OBJ_REF_DELTA: {
readFully(pos + p, ib, 0, 20, curs);
pos = findDeltaBase(ObjectId.fromRaw(ib));
continue;
}
default:
throw new IOException(MessageFormat.format(
JGitText.get().unknownObjectType, type));
}
}
}
long getObjectSize(final WindowCursor curs, final AnyObjectId id)
throws IOException {
final long offset = idx().findOffset(id);
return 0 < offset ? getObjectSize(curs, offset) : -1;
}
long getObjectSize(final WindowCursor curs, final long pos)
throws IOException {
final byte[] ib = curs.tempId;
readFully(pos, ib, 0, 20, curs);
int c = ib[0] & 0xff;
final int type = (c >> 4) & 7;
long sz = c & 15;
int shift = 4;
int p = 1;
while ((c & 0x80) != 0) {
c = ib[p++] & 0xff;
sz += (c & 0x7f) << shift;
shift += 7;
}
long deltaAt;
switch (type) {
case Constants.OBJ_COMMIT:
case Constants.OBJ_TREE:
case Constants.OBJ_BLOB:
case Constants.OBJ_TAG:
return sz;
case Constants.OBJ_OFS_DELTA:
c = ib[p++] & 0xff;
while ((c & 128) != 0)
c = ib[p++] & 0xff;
deltaAt = pos + p;
break;
case Constants.OBJ_REF_DELTA:
deltaAt = pos + p + 20;
break;
default:
throw new IOException(MessageFormat.format(
JGitText.get().unknownObjectType, type));
}
try {
return BinaryDelta.getResultSize(getDeltaHeader(curs, deltaAt));
} catch (DataFormatException e) {
throw new CorruptObjectException(MessageFormat.format(JGitText
.get().objectAtHasBadZlibStream, pos, getPackFile()));
}
}
LocalObjectRepresentation representation(final WindowCursor curs,
final AnyObjectId objectId) throws IOException {
final long pos = idx().findOffset(objectId);
if (pos < 0)
return null;
final byte[] ib = curs.tempId;
readFully(pos, ib, 0, 20, curs);
int c = ib[0] & 0xff;
int p = 1;
final int typeCode = (c >> 4) & 7;
while ((c & 0x80) != 0)
c = ib[p++] & 0xff;
long len = (findEndOffset(pos) - pos);
switch (typeCode) {
case Constants.OBJ_COMMIT:
case Constants.OBJ_TREE:
case Constants.OBJ_BLOB:
case Constants.OBJ_TAG:
return LocalObjectRepresentation.newWhole(this, pos, len - p);
case Constants.OBJ_OFS_DELTA: {
c = ib[p++] & 0xff;
long ofs = c & 127;
while ((c & 128) != 0) {
ofs += 1;
c = ib[p++] & 0xff;
ofs <<= 7;
ofs += (c & 127);
}
ofs = pos - ofs;
return LocalObjectRepresentation.newDelta(this, pos, len - p, ofs);
}
case Constants.OBJ_REF_DELTA: {
len -= p;
len -= Constants.OBJECT_ID_LENGTH;
readFully(pos + p, ib, 0, 20, curs);
ObjectId id = ObjectId.fromRaw(ib);
return LocalObjectRepresentation.newDelta(this, pos, len, id);
}
default:
throw new IOException(MessageFormat.format(
JGitText.get().unknownObjectType, typeCode));
}
}
private long findEndOffset(final long startOffset)
throws IOException, CorruptObjectException {
final long maxOffset = length - 20;
return getReverseIdx().findNextOffset(startOffset, maxOffset);
}
private synchronized PackReverseIndex getReverseIdx() throws IOException {
if (reverseIdx == null)
reverseIdx = new PackReverseIndex(idx());
return reverseIdx;
}
private boolean isCorrupt(long offset) {
LongList list = corruptObjects;
if (list == null)
return false;
synchronized (list) {
return list.contains(offset);
}
}
private void setCorrupt(long offset) {
LongList list = corruptObjects;
if (list == null) {
synchronized (readLock) {
list = corruptObjects;
if (list == null) {
list = new LongList();
corruptObjects = list;
}
}
}
synchronized (list) {
list.add(offset);
}
}
}
| true | true | private void copyAsIs2(PackOutputStream out, LocalObjectToPack src,
WindowCursor curs) throws IOException,
StoredObjectRepresentationNotAvailableException {
final CRC32 crc1 = new CRC32();
final CRC32 crc2 = new CRC32();
final byte[] buf = out.getCopyBuffer();
// Rip apart the header so we can discover the size.
//
readFully(src.offset, buf, 0, 20, curs);
int c = buf[0] & 0xff;
final int typeCode = (c >> 4) & 7;
long inflatedLength = c & 15;
int shift = 4;
int headerCnt = 1;
while ((c & 0x80) != 0) {
c = buf[headerCnt++] & 0xff;
inflatedLength += (c & 0x7f) << shift;
shift += 7;
}
if (typeCode == Constants.OBJ_OFS_DELTA) {
do {
c = buf[headerCnt++] & 0xff;
} while ((c & 128) != 0);
crc1.update(buf, 0, headerCnt);
crc2.update(buf, 0, headerCnt);
} else if (typeCode == Constants.OBJ_REF_DELTA) {
crc1.update(buf, 0, headerCnt);
crc2.update(buf, 0, headerCnt);
readFully(src.offset + headerCnt, buf, 0, 20, curs);
crc1.update(buf, 0, 20);
crc2.update(buf, 0, headerCnt);
headerCnt += 20;
} else {
crc1.update(buf, 0, headerCnt);
crc2.update(buf, 0, headerCnt);
}
final long dataOffset = src.offset + headerCnt;
final long dataLength = src.length;
final long expectedCRC;
final ByteArrayWindow quickCopy;
// Verify the object isn't corrupt before sending. If it is,
// we report it missing instead.
//
try {
quickCopy = curs.quickCopy(this, dataOffset, dataLength);
if (idx().hasCRC32Support()) {
// Index has the CRC32 code cached, validate the object.
//
expectedCRC = idx().findCRC32(src);
if (quickCopy != null) {
quickCopy.crc32(crc1, dataOffset, (int) dataLength);
} else {
long pos = dataOffset;
long cnt = dataLength;
while (cnt > 0) {
final int n = (int) Math.min(cnt, buf.length);
readFully(pos, buf, 0, n, curs);
crc1.update(buf, 0, n);
pos += n;
cnt -= n;
}
}
if (crc1.getValue() != expectedCRC) {
setCorrupt(src.offset);
throw new CorruptObjectException(MessageFormat.format(
JGitText.get().objectAtHasBadZlibStream,
src.offset, getPackFile()));
}
} else {
// We don't have a CRC32 code in the index, so compute it
// now while inflating the raw data to get zlib to tell us
// whether or not the data is safe.
//
Inflater inf = curs.inflater();
byte[] tmp = new byte[1024];
if (quickCopy != null) {
quickCopy.check(inf, tmp, dataOffset, (int) dataLength);
} else {
long pos = dataOffset;
long cnt = dataLength;
while (cnt > 0) {
final int n = (int) Math.min(cnt, buf.length);
readFully(pos, buf, 0, n, curs);
crc1.update(buf, 0, n);
inf.setInput(buf, 0, n);
while (inf.inflate(tmp, 0, tmp.length) > 0)
continue;
pos += n;
cnt -= n;
}
}
if (!inf.finished() || inf.getBytesRead() != dataLength) {
setCorrupt(src.offset);
throw new EOFException(MessageFormat.format(
JGitText.get().shortCompressedStreamAt,
src.offset));
}
expectedCRC = crc1.getValue();
}
} catch (DataFormatException dataFormat) {
setCorrupt(src.offset);
CorruptObjectException corruptObject = new CorruptObjectException(
MessageFormat.format(
JGitText.get().objectAtHasBadZlibStream,
src.offset, getPackFile()));
corruptObject.initCause(dataFormat);
StoredObjectRepresentationNotAvailableException gone;
gone = new StoredObjectRepresentationNotAvailableException(src);
gone.initCause(corruptObject);
throw gone;
} catch (IOException ioError) {
StoredObjectRepresentationNotAvailableException gone;
gone = new StoredObjectRepresentationNotAvailableException(src);
gone.initCause(ioError);
throw gone;
}
if (quickCopy != null) {
// The entire object fits into a single byte array window slice,
// and we have it pinned. Write this out without copying.
//
out.writeHeader(src, inflatedLength);
quickCopy.write(out, dataOffset, (int) dataLength);
} else if (dataLength <= buf.length) {
// Tiny optimization: Lots of objects are very small deltas or
// deflated commits that are likely to fit in the copy buffer.
//
out.writeHeader(src, inflatedLength);
out.write(buf, 0, (int) dataLength);
} else {
// Now we are committed to sending the object. As we spool it out,
// check its CRC32 code to make sure there wasn't corruption between
// the verification we did above, and us actually outputting it.
//
out.writeHeader(src, inflatedLength);
long pos = dataOffset;
long cnt = dataLength;
while (cnt > 0) {
final int n = (int) Math.min(cnt, buf.length);
readFully(pos, buf, 0, n, curs);
crc2.update(buf, 0, n);
out.write(buf, 0, n);
pos += n;
cnt -= n;
}
if (crc2.getValue() != expectedCRC) {
throw new CorruptObjectException(MessageFormat.format(JGitText
.get().objectAtHasBadZlibStream, src.offset,
getPackFile()));
}
}
}
| private void copyAsIs2(PackOutputStream out, LocalObjectToPack src,
WindowCursor curs) throws IOException,
StoredObjectRepresentationNotAvailableException {
final CRC32 crc1 = new CRC32();
final CRC32 crc2 = new CRC32();
final byte[] buf = out.getCopyBuffer();
// Rip apart the header so we can discover the size.
//
readFully(src.offset, buf, 0, 20, curs);
int c = buf[0] & 0xff;
final int typeCode = (c >> 4) & 7;
long inflatedLength = c & 15;
int shift = 4;
int headerCnt = 1;
while ((c & 0x80) != 0) {
c = buf[headerCnt++] & 0xff;
inflatedLength += (c & 0x7f) << shift;
shift += 7;
}
if (typeCode == Constants.OBJ_OFS_DELTA) {
do {
c = buf[headerCnt++] & 0xff;
} while ((c & 128) != 0);
crc1.update(buf, 0, headerCnt);
crc2.update(buf, 0, headerCnt);
} else if (typeCode == Constants.OBJ_REF_DELTA) {
crc1.update(buf, 0, headerCnt);
crc2.update(buf, 0, headerCnt);
readFully(src.offset + headerCnt, buf, 0, 20, curs);
crc1.update(buf, 0, 20);
crc2.update(buf, 0, 20);
headerCnt += 20;
} else {
crc1.update(buf, 0, headerCnt);
crc2.update(buf, 0, headerCnt);
}
final long dataOffset = src.offset + headerCnt;
final long dataLength = src.length;
final long expectedCRC;
final ByteArrayWindow quickCopy;
// Verify the object isn't corrupt before sending. If it is,
// we report it missing instead.
//
try {
quickCopy = curs.quickCopy(this, dataOffset, dataLength);
if (idx().hasCRC32Support()) {
// Index has the CRC32 code cached, validate the object.
//
expectedCRC = idx().findCRC32(src);
if (quickCopy != null) {
quickCopy.crc32(crc1, dataOffset, (int) dataLength);
} else {
long pos = dataOffset;
long cnt = dataLength;
while (cnt > 0) {
final int n = (int) Math.min(cnt, buf.length);
readFully(pos, buf, 0, n, curs);
crc1.update(buf, 0, n);
pos += n;
cnt -= n;
}
}
if (crc1.getValue() != expectedCRC) {
setCorrupt(src.offset);
throw new CorruptObjectException(MessageFormat.format(
JGitText.get().objectAtHasBadZlibStream,
src.offset, getPackFile()));
}
} else {
// We don't have a CRC32 code in the index, so compute it
// now while inflating the raw data to get zlib to tell us
// whether or not the data is safe.
//
Inflater inf = curs.inflater();
byte[] tmp = new byte[1024];
if (quickCopy != null) {
quickCopy.check(inf, tmp, dataOffset, (int) dataLength);
} else {
long pos = dataOffset;
long cnt = dataLength;
while (cnt > 0) {
final int n = (int) Math.min(cnt, buf.length);
readFully(pos, buf, 0, n, curs);
crc1.update(buf, 0, n);
inf.setInput(buf, 0, n);
while (inf.inflate(tmp, 0, tmp.length) > 0)
continue;
pos += n;
cnt -= n;
}
}
if (!inf.finished() || inf.getBytesRead() != dataLength) {
setCorrupt(src.offset);
throw new EOFException(MessageFormat.format(
JGitText.get().shortCompressedStreamAt,
src.offset));
}
expectedCRC = crc1.getValue();
}
} catch (DataFormatException dataFormat) {
setCorrupt(src.offset);
CorruptObjectException corruptObject = new CorruptObjectException(
MessageFormat.format(
JGitText.get().objectAtHasBadZlibStream,
src.offset, getPackFile()));
corruptObject.initCause(dataFormat);
StoredObjectRepresentationNotAvailableException gone;
gone = new StoredObjectRepresentationNotAvailableException(src);
gone.initCause(corruptObject);
throw gone;
} catch (IOException ioError) {
StoredObjectRepresentationNotAvailableException gone;
gone = new StoredObjectRepresentationNotAvailableException(src);
gone.initCause(ioError);
throw gone;
}
if (quickCopy != null) {
// The entire object fits into a single byte array window slice,
// and we have it pinned. Write this out without copying.
//
out.writeHeader(src, inflatedLength);
quickCopy.write(out, dataOffset, (int) dataLength);
} else if (dataLength <= buf.length) {
// Tiny optimization: Lots of objects are very small deltas or
// deflated commits that are likely to fit in the copy buffer.
//
out.writeHeader(src, inflatedLength);
out.write(buf, 0, (int) dataLength);
} else {
// Now we are committed to sending the object. As we spool it out,
// check its CRC32 code to make sure there wasn't corruption between
// the verification we did above, and us actually outputting it.
//
out.writeHeader(src, inflatedLength);
long pos = dataOffset;
long cnt = dataLength;
while (cnt > 0) {
final int n = (int) Math.min(cnt, buf.length);
readFully(pos, buf, 0, n, curs);
crc2.update(buf, 0, n);
out.write(buf, 0, n);
pos += n;
cnt -= n;
}
if (crc2.getValue() != expectedCRC) {
throw new CorruptObjectException(MessageFormat.format(JGitText
.get().objectAtHasBadZlibStream, src.offset,
getPackFile()));
}
}
}
|
diff --git a/src/strategy/game/version/beta/move/BetaMoveRuleSet.java b/src/strategy/game/version/beta/move/BetaMoveRuleSet.java
index 51f6f5a..c613f0d 100644
--- a/src/strategy/game/version/beta/move/BetaMoveRuleSet.java
+++ b/src/strategy/game/version/beta/move/BetaMoveRuleSet.java
@@ -1,255 +1,259 @@
/*******************************************************************************
* This files was developed for CS4233: Object-Oriented Analysis & Design.
* The course was taken at Worcester Polytechnic Institute.
*
* 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
*******************************************************************************/
package strategy.game.version.beta.move;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import strategy.common.PlayerColor;
import strategy.common.StrategyException;
import strategy.game.common.Coordinate;
import strategy.game.common.Location;
import strategy.game.common.Location2D;
import strategy.game.common.MoveResult;
import strategy.game.common.MoveResultStatus;
import strategy.game.common.Piece;
import strategy.game.common.PieceLocationDescriptor;
import strategy.game.common.PieceType;
import strategy.game.version.board.BoardRuleSet;
import strategy.game.version.combat.CombatResult;
import strategy.game.version.combat.CombatRuleSet;
import strategy.game.version.move.FinishedMove;
import strategy.game.version.move.MoveRuleSet;
/**
* Constructor for BetaMoveRuleSet
* @author rjsmieja, jrspicola
* @version Sept 21, 2013
*/
public class BetaMoveRuleSet implements MoveRuleSet {
private static final int MAX_TOTAL_MOVES = 12;
private static final int MAX_MOVE_DISTANCE = 1;
final private Collection<PieceType> unmovablePieces;
final private Collection<PieceType> validPieceTypes;
final private CombatRuleSet combatRules;
final private BoardRuleSet boardRules;
private int moveCount;
private PlayerColor turnPlayer;
/**
* Constructor for BetaMoveRuleSet
* @param combatRules ComatRuleSet to follow
* @param boardRules BoardRuleSet to follow
*/
public BetaMoveRuleSet(CombatRuleSet combatRules, BoardRuleSet boardRules){
unmovablePieces = new ArrayList<PieceType>();
unmovablePieces.add(PieceType.FLAG);
validPieceTypes = new ArrayList<PieceType>();
validPieceTypes.add(PieceType.MARSHAL);
validPieceTypes.add(PieceType.COLONEL);
validPieceTypes.add(PieceType.CAPTAIN);
validPieceTypes.add(PieceType.LIEUTENANT);
validPieceTypes.add(PieceType.SERGEANT);
validPieceTypes.add(PieceType.FLAG);
this.combatRules = combatRules;
this.boardRules = boardRules;
moveCount = 0;
turnPlayer = PlayerColor.RED;
}
@Override
public void reset(){
moveCount = 0;
turnPlayer = PlayerColor.RED;
}
@Override
public FinishedMove doMove(PieceType movingType, PieceLocationDescriptor movingPiece, PieceLocationDescriptor targetPiece, Collection<PieceLocationDescriptor> redConfiguration, Collection<PieceLocationDescriptor> blueConfiguration) throws StrategyException
{
MoveResult moveResult = null;
//Checks
if (!boardRules.validateLocation(movingPiece)){
throw new StrategyException("Error validating the location the piece is moving from");
}
if (!boardRules.validateLocation(targetPiece)){
throw new StrategyException("Error validating the location the piece is moving to");
}
if(movingPiece.getPiece() == null){
throw new StrategyException("No piece at location");
}
if(unmovablePieces.contains(movingPiece.getPiece().getType())){
throw new StrategyException("Specified piece type of <" + movingPiece.getPiece().getType() + "> is not allowed to move");
}
if (movingPiece.getPiece().getType() != movingType){
throw new StrategyException("Piece type does not match!");
}
final Location from = movingPiece.getLocation();
final Location to = targetPiece.getLocation();
final int distanceToMove = to.distanceTo(from);
final PlayerColor pieceOwner = movingPiece.getPiece().getOwner();
if (pieceOwner != turnPlayer){
throw new StrategyException("Piece does not belong to the current player's turn!");
}
if (distanceToMove > MAX_MOVE_DISTANCE){
throw new StrategyException("Moving too many spaces");
}
if (distanceToMove == 0){
throw new StrategyException("Not moving");
}
moveCount++;
//check 'to' spot. if no piece there, make move. else, check piece color.
if (targetPiece.getPiece() != null){
if (movingPiece.getPiece().getOwner() == targetPiece.getPiece().getOwner()){
throw new StrategyException("Attempting to do combat on friendly piece!");
}
//if color is friend, throw exception. if color is enemy, battle
if(movingPiece.getPiece().getType().equals(targetPiece.getPiece().getType())) {
//remove both pieces
redConfiguration.remove(movingPiece);
redConfiguration.remove(targetPiece);
blueConfiguration.remove(movingPiece);
blueConfiguration.remove(targetPiece);
} else {
final PieceLocationDescriptor movedPiece = new PieceLocationDescriptor(movingPiece.getPiece(), targetPiece.getLocation());
- final CombatResult combatResult = combatRules.doCombat(movedPiece, targetPiece);
+ final PieceLocationDescriptor movedTargetPiece = new PieceLocationDescriptor(targetPiece.getPiece(), movingPiece.getLocation());
+ final CombatResult combatResult;
+ if (unmovablePieces.contains(targetPiece.getPiece().getType())){
+ combatResult = combatRules.doCombat(movedPiece, targetPiece);
+ } else {
+ combatResult = combatRules.doCombat(movedPiece, movedTargetPiece);
+ }
//remove both pieces
redConfiguration.remove(movingPiece);
- redConfiguration.remove(movedPiece);
redConfiguration.remove(targetPiece);
blueConfiguration.remove(movingPiece);
- blueConfiguration.remove(movedPiece);
blueConfiguration.remove(targetPiece);
//Add the winner
if (combatResult.getWinningPiece().getPiece().getOwner() == PlayerColor.RED){
redConfiguration.add(combatResult.getWinningPiece());
} else if (combatResult.getWinningPiece().getPiece().getOwner() == PlayerColor.BLUE){
blueConfiguration.add(combatResult.getWinningPiece());
}
//If we defeated a flag, we win the game
if (combatResult.getLosingPiece().getPiece().getType() == PieceType.FLAG){
moveResult = new MoveResult(MoveResultStatus.valueOf(combatResult.getWinningPiece().getPiece().getOwner() + "_WINS"), combatResult.getWinningPiece());
//If we didn't defeat a flag and we didn't go over the move limit a normal victory
} else if (moveCount < MAX_TOTAL_MOVES) {
moveResult = new MoveResult(MoveResultStatus.OK, combatResult.getWinningPiece());
}
}
} else {
movePiece(movingPiece, to, redConfiguration, blueConfiguration);
}
if (moveCount >= MAX_TOTAL_MOVES && moveResult == null){
moveResult = new MoveResult(MoveResultStatus.DRAW, null);
}
//Next player's turn
if (turnPlayer == PlayerColor.RED){
turnPlayer = PlayerColor.BLUE;
} else {
turnPlayer = PlayerColor.RED;
}
if (moveResult == null){
moveResult = new MoveResult(MoveResultStatus.OK, null);
}
return new FinishedMove(redConfiguration, blueConfiguration, moveResult);
}
@Override
public boolean canMove(Collection<PieceLocationDescriptor> redConfiguration, Collection<PieceLocationDescriptor> blueConfiguration){
final Map<Location, Piece> locationPieceMap = new HashMap<Location, Piece>();
for (PieceLocationDescriptor piece : redConfiguration){
locationPieceMap.put(piece.getLocation(), piece.getPiece());
}
for (PieceLocationDescriptor piece : blueConfiguration){
locationPieceMap.put(piece.getLocation(), piece.getPiece());
}
final Map<Location, Piece> moveablePieces = new HashMap<Location, Piece>();
//Get all moveable edge Pieces, aka those that have a space next to them, and that belong to the current turn player
for (Location location : locationPieceMap.keySet()){
Piece piece = locationPieceMap.get(location);
if ((hasAdjacentEmptySpace(locationPieceMap, location)) && (!unmovablePieces.contains(piece.getType())) && (piece.getOwner() == turnPlayer)){
moveablePieces.put(location, piece);
}
}
//TODO: MOVE HISTORY HERE
//Empty means no pieces can move
return !moveablePieces.isEmpty();
}
/**
* Helper to actually move a piece to an empty location
* @param piece Piece to move
* @param from Location to move piece from
* @param to Location to move piece to
*/
private void movePiece(PieceLocationDescriptor oldPiece, Location to, Collection<PieceLocationDescriptor> redConfiguration, Collection<PieceLocationDescriptor> blueConfiguration){
final PieceLocationDescriptor newPiece = new PieceLocationDescriptor(oldPiece.getPiece(), to);
if(oldPiece.getPiece().getOwner() == PlayerColor.RED){
redConfiguration.remove(oldPiece);
redConfiguration.add(newPiece);
}else if (oldPiece.getPiece().getOwner() == PlayerColor.BLUE){
blueConfiguration.remove(oldPiece);
blueConfiguration.add(newPiece);
}
}
/**
* Helper to determine if a piece has an empty space next to it in +/- 1 in the X and Y directions
* @param pieces HashMap of Location and Pieces to check
* @param location Location to determine edge pieces for
* @return true if an edge piece, false otherwise
*/
private boolean hasAdjacentEmptySpace(Map<Location, Piece> pieces, Location location){
final Location xUp = new Location2D(location.getCoordinate(Coordinate.X_COORDINATE) + 1, location.getCoordinate(Coordinate.Y_COORDINATE));
final Location xDown = new Location2D(location.getCoordinate(Coordinate.X_COORDINATE) - 1, location.getCoordinate(Coordinate.Y_COORDINATE));
final Location yUp = new Location2D(location.getCoordinate(Coordinate.X_COORDINATE), location.getCoordinate(Coordinate.Y_COORDINATE) + 1);
final Location yDown= new Location2D(location.getCoordinate(Coordinate.X_COORDINATE), location.getCoordinate(Coordinate.Y_COORDINATE) - 1);
if (pieces.containsKey(xUp) && pieces.containsKey(xDown) && pieces.containsKey(yUp) && pieces.containsKey(yDown)){
return false;
}
return true;
}
}
| false | true | public FinishedMove doMove(PieceType movingType, PieceLocationDescriptor movingPiece, PieceLocationDescriptor targetPiece, Collection<PieceLocationDescriptor> redConfiguration, Collection<PieceLocationDescriptor> blueConfiguration) throws StrategyException
{
MoveResult moveResult = null;
//Checks
if (!boardRules.validateLocation(movingPiece)){
throw new StrategyException("Error validating the location the piece is moving from");
}
if (!boardRules.validateLocation(targetPiece)){
throw new StrategyException("Error validating the location the piece is moving to");
}
if(movingPiece.getPiece() == null){
throw new StrategyException("No piece at location");
}
if(unmovablePieces.contains(movingPiece.getPiece().getType())){
throw new StrategyException("Specified piece type of <" + movingPiece.getPiece().getType() + "> is not allowed to move");
}
if (movingPiece.getPiece().getType() != movingType){
throw new StrategyException("Piece type does not match!");
}
final Location from = movingPiece.getLocation();
final Location to = targetPiece.getLocation();
final int distanceToMove = to.distanceTo(from);
final PlayerColor pieceOwner = movingPiece.getPiece().getOwner();
if (pieceOwner != turnPlayer){
throw new StrategyException("Piece does not belong to the current player's turn!");
}
if (distanceToMove > MAX_MOVE_DISTANCE){
throw new StrategyException("Moving too many spaces");
}
if (distanceToMove == 0){
throw new StrategyException("Not moving");
}
moveCount++;
//check 'to' spot. if no piece there, make move. else, check piece color.
if (targetPiece.getPiece() != null){
if (movingPiece.getPiece().getOwner() == targetPiece.getPiece().getOwner()){
throw new StrategyException("Attempting to do combat on friendly piece!");
}
//if color is friend, throw exception. if color is enemy, battle
if(movingPiece.getPiece().getType().equals(targetPiece.getPiece().getType())) {
//remove both pieces
redConfiguration.remove(movingPiece);
redConfiguration.remove(targetPiece);
blueConfiguration.remove(movingPiece);
blueConfiguration.remove(targetPiece);
} else {
final PieceLocationDescriptor movedPiece = new PieceLocationDescriptor(movingPiece.getPiece(), targetPiece.getLocation());
final CombatResult combatResult = combatRules.doCombat(movedPiece, targetPiece);
//remove both pieces
redConfiguration.remove(movingPiece);
redConfiguration.remove(movedPiece);
redConfiguration.remove(targetPiece);
blueConfiguration.remove(movingPiece);
blueConfiguration.remove(movedPiece);
blueConfiguration.remove(targetPiece);
//Add the winner
if (combatResult.getWinningPiece().getPiece().getOwner() == PlayerColor.RED){
redConfiguration.add(combatResult.getWinningPiece());
} else if (combatResult.getWinningPiece().getPiece().getOwner() == PlayerColor.BLUE){
blueConfiguration.add(combatResult.getWinningPiece());
}
//If we defeated a flag, we win the game
if (combatResult.getLosingPiece().getPiece().getType() == PieceType.FLAG){
moveResult = new MoveResult(MoveResultStatus.valueOf(combatResult.getWinningPiece().getPiece().getOwner() + "_WINS"), combatResult.getWinningPiece());
//If we didn't defeat a flag and we didn't go over the move limit a normal victory
} else if (moveCount < MAX_TOTAL_MOVES) {
moveResult = new MoveResult(MoveResultStatus.OK, combatResult.getWinningPiece());
}
}
} else {
movePiece(movingPiece, to, redConfiguration, blueConfiguration);
}
if (moveCount >= MAX_TOTAL_MOVES && moveResult == null){
moveResult = new MoveResult(MoveResultStatus.DRAW, null);
}
//Next player's turn
if (turnPlayer == PlayerColor.RED){
turnPlayer = PlayerColor.BLUE;
} else {
turnPlayer = PlayerColor.RED;
}
if (moveResult == null){
moveResult = new MoveResult(MoveResultStatus.OK, null);
}
return new FinishedMove(redConfiguration, blueConfiguration, moveResult);
}
| public FinishedMove doMove(PieceType movingType, PieceLocationDescriptor movingPiece, PieceLocationDescriptor targetPiece, Collection<PieceLocationDescriptor> redConfiguration, Collection<PieceLocationDescriptor> blueConfiguration) throws StrategyException
{
MoveResult moveResult = null;
//Checks
if (!boardRules.validateLocation(movingPiece)){
throw new StrategyException("Error validating the location the piece is moving from");
}
if (!boardRules.validateLocation(targetPiece)){
throw new StrategyException("Error validating the location the piece is moving to");
}
if(movingPiece.getPiece() == null){
throw new StrategyException("No piece at location");
}
if(unmovablePieces.contains(movingPiece.getPiece().getType())){
throw new StrategyException("Specified piece type of <" + movingPiece.getPiece().getType() + "> is not allowed to move");
}
if (movingPiece.getPiece().getType() != movingType){
throw new StrategyException("Piece type does not match!");
}
final Location from = movingPiece.getLocation();
final Location to = targetPiece.getLocation();
final int distanceToMove = to.distanceTo(from);
final PlayerColor pieceOwner = movingPiece.getPiece().getOwner();
if (pieceOwner != turnPlayer){
throw new StrategyException("Piece does not belong to the current player's turn!");
}
if (distanceToMove > MAX_MOVE_DISTANCE){
throw new StrategyException("Moving too many spaces");
}
if (distanceToMove == 0){
throw new StrategyException("Not moving");
}
moveCount++;
//check 'to' spot. if no piece there, make move. else, check piece color.
if (targetPiece.getPiece() != null){
if (movingPiece.getPiece().getOwner() == targetPiece.getPiece().getOwner()){
throw new StrategyException("Attempting to do combat on friendly piece!");
}
//if color is friend, throw exception. if color is enemy, battle
if(movingPiece.getPiece().getType().equals(targetPiece.getPiece().getType())) {
//remove both pieces
redConfiguration.remove(movingPiece);
redConfiguration.remove(targetPiece);
blueConfiguration.remove(movingPiece);
blueConfiguration.remove(targetPiece);
} else {
final PieceLocationDescriptor movedPiece = new PieceLocationDescriptor(movingPiece.getPiece(), targetPiece.getLocation());
final PieceLocationDescriptor movedTargetPiece = new PieceLocationDescriptor(targetPiece.getPiece(), movingPiece.getLocation());
final CombatResult combatResult;
if (unmovablePieces.contains(targetPiece.getPiece().getType())){
combatResult = combatRules.doCombat(movedPiece, targetPiece);
} else {
combatResult = combatRules.doCombat(movedPiece, movedTargetPiece);
}
//remove both pieces
redConfiguration.remove(movingPiece);
redConfiguration.remove(targetPiece);
blueConfiguration.remove(movingPiece);
blueConfiguration.remove(targetPiece);
//Add the winner
if (combatResult.getWinningPiece().getPiece().getOwner() == PlayerColor.RED){
redConfiguration.add(combatResult.getWinningPiece());
} else if (combatResult.getWinningPiece().getPiece().getOwner() == PlayerColor.BLUE){
blueConfiguration.add(combatResult.getWinningPiece());
}
//If we defeated a flag, we win the game
if (combatResult.getLosingPiece().getPiece().getType() == PieceType.FLAG){
moveResult = new MoveResult(MoveResultStatus.valueOf(combatResult.getWinningPiece().getPiece().getOwner() + "_WINS"), combatResult.getWinningPiece());
//If we didn't defeat a flag and we didn't go over the move limit a normal victory
} else if (moveCount < MAX_TOTAL_MOVES) {
moveResult = new MoveResult(MoveResultStatus.OK, combatResult.getWinningPiece());
}
}
} else {
movePiece(movingPiece, to, redConfiguration, blueConfiguration);
}
if (moveCount >= MAX_TOTAL_MOVES && moveResult == null){
moveResult = new MoveResult(MoveResultStatus.DRAW, null);
}
//Next player's turn
if (turnPlayer == PlayerColor.RED){
turnPlayer = PlayerColor.BLUE;
} else {
turnPlayer = PlayerColor.RED;
}
if (moveResult == null){
moveResult = new MoveResult(MoveResultStatus.OK, null);
}
return new FinishedMove(redConfiguration, blueConfiguration, moveResult);
}
|
diff --git a/org.osate.xtext.aadl2.errormodel/src/org/osate/xtext/aadl2/errormodel/validation/ErrorModelJavaValidator.java b/org.osate.xtext.aadl2.errormodel/src/org/osate/xtext/aadl2/errormodel/validation/ErrorModelJavaValidator.java
index 7be63f58..20984126 100644
--- a/org.osate.xtext.aadl2.errormodel/src/org/osate/xtext/aadl2/errormodel/validation/ErrorModelJavaValidator.java
+++ b/org.osate.xtext.aadl2.errormodel/src/org/osate/xtext/aadl2/errormodel/validation/ErrorModelJavaValidator.java
@@ -1,665 +1,665 @@
package org.osate.xtext.aadl2.errormodel.validation;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Map;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.xtext.validation.Check;
import org.eclipse.xtext.validation.CheckType;
import org.eclipse.xtext.validation.ValidationMessageAcceptor;
import org.osate.aadl2.Classifier;
import org.osate.aadl2.ComponentClassifier;
import org.osate.aadl2.ComponentImplementation;
import org.osate.aadl2.Connection;
import org.osate.aadl2.ConnectionEnd;
import org.osate.aadl2.ContainedNamedElement;
import org.osate.aadl2.ContainmentPathElement;
import org.osate.aadl2.Context;
import org.osate.aadl2.DirectionType;
import org.osate.aadl2.Feature;
import org.osate.aadl2.NamedElement;
import org.osate.aadl2.Port;
import org.osate.aadl2.PropertyAssociation;
import org.osate.aadl2.Subcomponent;
import org.osate.aadl2.modelsupport.util.AadlUtil;
import org.osate.aadl2.util.Aadl2Util;
import org.osate.xtext.aadl2.errormodel.errorModel.ElementTypeMapping;
import org.osate.xtext.aadl2.errormodel.errorModel.ElementTypeTransformation;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorBehaviorState;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorBehaviorStateMachine;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorEvent;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorModelFactory;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorModelLibrary;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorModelSubclause;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorPath;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorPropagation;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorPropagations;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorSink;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorSource;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorType;
import org.osate.xtext.aadl2.errormodel.errorModel.ErrorTypes;
import org.osate.xtext.aadl2.errormodel.errorModel.ObservablePropagationConnection;
import org.osate.xtext.aadl2.errormodel.errorModel.QualifiedObservableErrorPropagationPoint;
import org.osate.xtext.aadl2.errormodel.errorModel.TypeMapping;
import org.osate.xtext.aadl2.errormodel.errorModel.TypeMappingSet;
import org.osate.xtext.aadl2.errormodel.errorModel.TypeSet;
import org.osate.xtext.aadl2.errormodel.errorModel.TypeToken;
import org.osate.xtext.aadl2.errormodel.errorModel.TypeTransformationSet;
import org.osate.xtext.aadl2.errormodel.errorModel.TypeUseContext;
import org.osate.xtext.aadl2.errormodel.errorModel.impl.ErrorModelPackageImpl;
import org.osate.xtext.aadl2.errormodel.util.EM2TypeSetUtil;
import org.osate.xtext.aadl2.errormodel.util.EM2Util;
public class ErrorModelJavaValidator extends AbstractErrorModelJavaValidator {
@Override
protected boolean isResponsible(Map<Object, Object> context, EObject eObject) {
return (eObject.eClass().getEPackage() == ErrorModelPackageImpl.eINSTANCE
|| eObject instanceof Connection || eObject instanceof PropertyAssociation);
}
@Check(CheckType.FAST)
public void caseErrorPropagation(
ErrorPropagation errorPropagation) {
checkDirectionType(errorPropagation);
checkUniqueObservablePropagationPoint(errorPropagation);
}
@Check(CheckType.FAST)
public void casePropertyAssociation(
PropertyAssociation propertyAssociation) {
// check that error type is contained in type set of target element
EList<ContainedNamedElement> apto = propertyAssociation.getAppliesTos();
for (ContainedNamedElement containedNamedElement : apto) {
EList<ContainmentPathElement> cpe = containedNamedElement.getContainmentPathElements();
if (cpe.size() > 1){
ContainmentPathElement obj = cpe.get(cpe.size()-1);
if (obj.getNamedElement() instanceof ErrorType){
ErrorType et = (ErrorType) obj.getNamedElement();
ContainmentPathElement target = cpe.get(cpe.size()-2);
NamedElement ne = target.getNamedElement();
TypeSet tts = null;
if (ne instanceof ErrorBehaviorState){
tts = ((ErrorBehaviorState)ne).getTypeSet();
} else if (ne instanceof ErrorPropagation){
tts = ((ErrorPropagation)ne).getTypeSet();
} else if (ne instanceof ErrorEvent){
tts = ((ErrorEvent)ne).getTypeSet();
}
TypeToken tt = ErrorModelFactory.eINSTANCE.createTypeToken();
tt.getType().add(et);
if (EM2TypeSetUtil.contains(tts, tt)){
}
}
}
}
}
@Check(CheckType.FAST)
public void caseObservablePropagationConnection(ObservablePropagationConnection opc){
checkObservableConnectionDirection(opc);
}
@Check(CheckType.FAST)
public void caseErrorType(
ErrorType et) {
checkCyclicExtends(et);
}
@Check(CheckType.FAST)
public void caseTypeSet(
TypeSet ts) {
checkTypeSetUniqueTypes(ts);
}
@Check(CheckType.FAST)
public void caseTypeToken(
TypeToken tt) {
checkTypeTokenUniqueTypes(tt);
}
@Check(CheckType.FAST)
public void caseElementTypeMapping(
ElementTypeMapping etMapping) {
checkElementMappingTypeConsistency(etMapping);
}
@Check(CheckType.FAST)
public void caseElementTypeTransformation(
ElementTypeTransformation etXform) {
checkElementTransformTypeConsistency(etXform);
}
@Check(CheckType.NORMAL)
public void caseErrorPropagations(
ErrorPropagations errorPropagations) {
checkOnePropagationAndContainmentPoint(errorPropagations);
}
@Check(CheckType.NORMAL)
public void caseTypeMappingSet(
TypeMappingSet tms) {
checkElementRuleConsistency(tms);
}
@Check(CheckType.NORMAL)
public void caseErrorModelLibrary(ErrorModelLibrary errorModelLibrary) {
if (errorModelLibrary.getName() == null)
errorModelLibrary.setName("emv2");
boolean cyclicextends = checkCyclicExtends(errorModelLibrary);
checkUniqueDefiningIdentifiers(errorModelLibrary,cyclicextends);
}
@Check(CheckType.NORMAL)
public void ErrorBehaviorStateMachine(
ErrorBehaviorStateMachine ebsm) {
checkCyclicExtends(ebsm);
// TODO: checkUniqueIdentifiers(ebsm);
}
@Check(CheckType.NORMAL)
public void caseTypeUseContext(
TypeUseContext typeUseContext) {
checkMultipleUses(typeUseContext);
checkMultipleErrorTypesInUsesTypes(typeUseContext);
}
@Check(CheckType.NORMAL)
public void caseErrorSource(
ErrorSource ef) {
checkErrorSourceTypes(ef);
checkFlowDirection(ef);
}
@Check(CheckType.NORMAL)
public void caseErrorSink(
ErrorSink ef) {
checkErrorSinkTypes(ef);
checkFlowDirection(ef);
}
@Check(CheckType.NORMAL)
public void caseErrorPath(
ErrorPath ef) {
checkErrorPathTypes(ef);
checkFlowDirection(ef);
}
@Check(CheckType.NORMAL)
public void caseConnection(
Connection conn) {
checkConnectionErrorTypes(conn);
}
private void checkDirectionType(ErrorPropagation errorPropagation){
DirectionType pd = errorPropagation.getDirection();
Feature f = errorPropagation.getFeature();
if (!Aadl2Util.isNull(f) && f instanceof Port){
DirectionType portd = ((Port)f).getDirection();
if (!(pd.
getName().equalsIgnoreCase(portd.getName()) || portd == DirectionType.IN_OUT))
error(errorPropagation,
"Propagation direction does not match port direction.");
}
}
private void checkOnePropagationAndContainmentPoint(ErrorPropagations errorPropagations){
EList<ErrorPropagation> eps = errorPropagations.getPropagations();
int epssize = eps.size();
for (int i=0;i<epssize-1;i++){
ErrorPropagation ep1 = eps.get(i);
for (int k=i+1;k<epssize;k++){
ErrorPropagation ep2 = eps.get(k);
if (ep1.getFeature() == ep2.getFeature()){
if (ep1.isNot() && ep2.isNot() || !ep1.isNot() && ! ep2.isNot()){
error(ep2, (ep1.isNot()?"Error containment ":"Error propagation ")+EM2Util.getPrintName(ep2)+" already defined.");
}
}
}
}
}
private void checkFlowDirection(ErrorSource errorSource){
ErrorPropagation ep = errorSource.getOutgoing();
if (!Aadl2Util.isNull(ep)){
DirectionType epd = ep.getDirection();
if (!(epd.equals(DirectionType.OUT))){
error(errorSource,
EM2Util.getPrintName(ep)+" of error source is not an outgoing propagation point.");
}
}
}
private void checkFlowDirection(ErrorSink errorSink){
ErrorPropagation ep = errorSink.getIncoming();
if (!Aadl2Util.isNull(ep)){
DirectionType epd = ep.getDirection();
if (!(epd.equals(DirectionType.IN))){
error(errorSink,
EM2Util.getPrintName(ep)+" of error sink is not an incoming propagation point.");
}
}
}
private void checkFlowDirection(ErrorPath errorPath){
ErrorPropagation ep = errorPath.getIncoming();
if (!Aadl2Util.isNull(ep)){
DirectionType epd = ep.getDirection();
if (!(epd.equals(DirectionType.IN))){
error(errorPath,
"Source "+EM2Util.getPrintName(ep)+" of error path is not an incoming propagation point.");
}
}
ep = errorPath.getOutgoing();
if (!Aadl2Util.isNull(ep)){
DirectionType epd = ep.getDirection();
if (!(epd.equals(DirectionType.OUT))){
error(errorPath,
"Target "+EM2Util.getPrintName(ep)+" of error path is not an outgoing propagation point.");
}
}
}
private void checkElementMappingTypeConsistency(ElementTypeMapping etMapping){
ErrorType srcET = etMapping.getSource();
ErrorType tgtET = etMapping.getTarget();
if (!Aadl2Util.isNull(srcET) && !Aadl2Util.isNull(tgtET)){
if (!EM2TypeSetUtil.inSameTypeHierarchy(srcET, tgtET)){
error(etMapping,
"Source and target error types are not in same type hierarchy");
}
}
}
private void checkElementTransformTypeConsistency(ElementTypeTransformation etXform){
ErrorType srcET = etXform.getSource();
ErrorType conET = etXform.getContributor();
ErrorType tgtET = etXform.getTarget();
if (!Aadl2Util.isNull(srcET) && !Aadl2Util.isNull(tgtET)){
if (!EM2TypeSetUtil.inSameTypeHierarchy(srcET, tgtET)){
error(etXform,
"Source type "+srcET.getName()+" and target type "+tgtET.getName()+" are not in same type hierarchy");
}
}
if (!Aadl2Util.isNull(srcET) && !Aadl2Util.isNull(conET)){
if (!EM2TypeSetUtil.inSameTypeHierarchy(srcET, conET)){
error(etXform,
"Source type "+srcET.getName()+" and contributor type "+conET.getName()+" are not in same type hierarchy");
}
}
}
private void checkElementRuleConsistency(TypeMappingSet tms){
HashSet<ErrorType> sourceTypes = new HashSet<ErrorType>();
for (TypeMapping tm : tms.getMapping()){
if (tm instanceof ElementTypeMapping){
ErrorType et = ((ElementTypeMapping) tm).getSource();
if (sourceTypes.contains(et)){
error(tm,
"Type "+et.getName()+" already being mapped");
} else {
sourceTypes.add(et);
}
}
}
}
private void checkTypeSetUniqueTypes(TypeSet ts){
EList<TypeToken> etlist = ts.getElementType();
int size = etlist.size();
for (int i = 0; i < size-1; i++) {
TypeToken tok = etlist.get(i);
for (int k = i+1; k < size; k++){
TypeToken tok2 = etlist.get(k);
if (EM2TypeSetUtil.contains(tok, tok2)||EM2TypeSetUtil.contains(tok2,tok)){
error(ts,
"Typeset elements "+EM2Util.getPrintName(tok)+" and "+EM2Util.getPrintName(tok2)+" are not disjoint.");
}
}
}
}
private void checkTypeTokenUniqueTypes(TypeToken ts){
HashSet<ErrorType> sourceTypes = new HashSet<ErrorType>();
for (ErrorType et : ts.getType()){
ErrorType root = EM2TypeSetUtil.rootType(et);
if (sourceTypes.contains(root)){
error(et,
"Another element type has same root type "+root.getName()+" as "+et.getName());
} else {
sourceTypes.add(et);
}
}
}
private void checkMultipleUses(TypeUseContext tuc){
HashSet<ErrorModelLibrary> etlset = new HashSet<ErrorModelLibrary>();
for (ErrorModelLibrary etl : EM2Util.getUseTypes(tuc)){
if (etlset.contains(etl)){
error(tuc,
"Error type library "+EM2Util.getPrintName(etl)+" exists more than once in 'uses types' clause");
} else {
etlset.add(etl);
}
}
}
private void checkMultipleErrorTypesInUsesTypes(TypeUseContext tuc){
Hashtable<String, EObject> etlset = new Hashtable<String, EObject>(10,10);
for (ErrorModelLibrary etl : EM2Util.getUseTypes(tuc)){
EList<ErrorTypes> typeslist = etl.getTypes();
for (ErrorTypes errorTypes : typeslist) {
if (etlset.containsKey(errorTypes.getName())){
ErrorModelLibrary eml = EM2Util.getContainingErrorModelLibrary(etlset.get(errorTypes.getName()));
error(tuc,
"Error type or type set "+errorTypes.getName()+" in library "+EM2Util.getPrintName(etl)+" already exists in error type library "+EM2Util.getPrintName(eml));
} else {
etlset.put(errorTypes.getName(),errorTypes);
}
}
}
}
private void checkUniqueObservablePropagationPoint(ErrorPropagation ep){
if (!ep.isObservable()) return;
for (ErrorPropagation oep : EM2Util.getContainingClassifierErrorPropagations(ep).getPropagations()){
if (oep.isObservable() && oep != ep && oep.getName().equalsIgnoreCase(ep.getName())){
error(ep,
"Observable propagation point "+ep.getName()+" defined more than once in error propagations clause.");
}
}
EObject searchResult = null;
Classifier cl = AadlUtil.getContainingClassifier(ep);
if (cl instanceof ComponentImplementation){
searchResult = ((ComponentImplementation)cl).getType().findNamedElement(ep.getName());
} else {
searchResult = AadlUtil.getContainingClassifier(ep).findNamedElement(ep.getName());
}
if (searchResult != null){
error(ep,
"Observable propagation point "+ep.getName()+" conflicts with feature in component type "+cl.getName());
}
}
private void checkObservableConnectionDirection(ObservablePropagationConnection opc){
QualifiedObservableErrorPropagationPoint src = opc.getSource();
QualifiedObservableErrorPropagationPoint dst = opc.getTarget();
ErrorPropagation srcPoint = src.getObservablePoint();
ErrorPropagation dstPoint = dst.getObservablePoint();
if (srcPoint == null || dstPoint == null) return;
if (!Aadl2Util.isNull(src.getSubcomponent()) && !Aadl2Util.isNull(dst.getSubcomponent())){
if (!DirectionType.OUT.equals(srcPoint.getDirection())){
error(opc, "Source "+srcPoint.getName()+" of observable connection must be outgoing");
}
if (!DirectionType.IN.equals(dstPoint.getDirection())){
error(opc, "Destination "+dstPoint.getName()+" of observable connection must be incoming");
}
} else if (!Aadl2Util.isNull(src.getSubcomponent()) && Aadl2Util.isNull(dst.getSubcomponent())){
if (!DirectionType.OUT.equals(srcPoint.getDirection())){
error(opc, "Source "+srcPoint.getName()+" of observable connection must be outgoing");
}
if (!DirectionType.OUT.equals(dstPoint.getDirection())){
error(opc, "Destination "+dstPoint.getName()+" of observable connection must be outgoing");
}
} else if (Aadl2Util.isNull(src.getSubcomponent()) && !Aadl2Util.isNull(dst.getSubcomponent())){
if (!DirectionType.IN.equals(srcPoint.getDirection())){
error(opc, "Source "+srcPoint.getName()+" of observable connection must be incoming");
}
if (!DirectionType.IN.equals(dstPoint.getDirection())){
error(opc, "Destination "+dstPoint.getName()+" of observable connection must be incoming");
}
}
}
private void checkUniqueDefiningIdentifiers(ErrorModelLibrary etl, boolean cyclicextends){
Hashtable<String, EObject> types = new Hashtable<String, EObject>(10,10);
checkUniqueDefiningEBSMMappingsTransformations(etl, types);
if (cyclicextends) return;
for (ErrorModelLibrary xetl : etl.getExtends()){
checkUniqueInheritedDefiningErrorTypes(xetl, types);
}
}
private void checkUniqueDefiningEBSMMappingsTransformations(ErrorModelLibrary etl, Hashtable<String, EObject> types){
for (ErrorBehaviorStateMachine ebsm : etl.getBehaviors()){
if (types.containsKey(ebsm.getName())){
error(ebsm, "Error behavior state machine identifier "+ebsm.getName()+" is not unique in error model library");
}
types.put(ebsm.getName(),ebsm);
}
for (TypeMappingSet tms : etl.getMappings()){
if (types.containsKey(tms.getName())){
error(tms, "Type mapping set identifier "+tms.getName()+" is not unique in error model library");
}
types.put(tms.getName(),tms);
}
for (TypeTransformationSet tts : etl.getTransformations()){
if (types.containsKey(tts.getName())){
error(tts, "Type transformation set identifier "+tts.getName()+" is not unique in error model library");
}
types.put(tts.getName(),tts);
}
for (ErrorTypes ets : etl.getTypes()){
if (types.containsKey(ets.getName())){
error(ets, "Error type or type set (alias) identifier "+ets.getName()+" is not unique in error model library");
}
types.put(ets.getName(),ets);
}
}
private void checkUniqueInheritedDefiningErrorTypes(ErrorModelLibrary etl, Hashtable<String, EObject> types){
for (ErrorTypes et : etl.getTypes()){
if (types.containsKey(et.getName())){
ErrorModelLibrary eml = EM2Util.getContainingErrorModelLibrary(et);
error(et, "Error type or type set (alias) "+et.getName()+" inherited from "+EM2Util.getPrintName(eml)+" conflicts with another defining identifier in error type library");
}
types.put(et.getName(),et);
}
for (ErrorModelLibrary xetl : etl.getExtends()){
checkUniqueInheritedDefiningErrorTypes(xetl, types);
}
}
private boolean checkCyclicExtends(ErrorModelLibrary etl){
if (etl.getExtends() == null) return false;
HashSet<ErrorModelLibrary> result = new HashSet<ErrorModelLibrary>();
return recursiveCheckCyclicExtends(etl,result);
}
private boolean recursiveCheckCyclicExtends(ErrorModelLibrary etl, HashSet<ErrorModelLibrary> shetl){
boolean result = false;
if (etl.getExtends() != null){
shetl.add(etl);
EList<ErrorModelLibrary> etllist = etl.getExtends();
for (ErrorModelLibrary xetl : etllist){
if (shetl.contains(xetl)){
error(xetl, "Cycle in extends of error type library "+etl.getName());
result = true;
} else {
result = result || recursiveCheckCyclicExtends(xetl,shetl);
}
}
shetl.remove(etl);
}
return result;
}
private void checkCyclicExtends(ErrorType origet){
ErrorType et = origet;
if (et.getSuperType() == null) return;
HashSet<ErrorType> result = new HashSet<ErrorType>();
while (et.getSuperType() != null){
result.add(et);
et = et.getSuperType();
if (result.contains(et)){
error(origet, "Cycle in supertype hierarchy of error type "+origet.getName()+" at type "+et.getName());
return;
}
}
}
private void checkCyclicExtends(ErrorBehaviorStateMachine origebsm){
ErrorBehaviorStateMachine ebsm = origebsm;
if (ebsm.getExtends() == null) return;
HashSet<ErrorBehaviorStateMachine> result = new HashSet<ErrorBehaviorStateMachine>();
while (ebsm.getExtends() != null){
result.add(ebsm);
ebsm = ebsm.getExtends();
if (result.contains(ebsm)){
error(origebsm, "Cycle in extends of error behavior state machine "+origebsm.getName());
return;
}
}
}
private void checkErrorSourceTypes(ErrorSource ef){
ErrorPropagation ep = ef.getOutgoing();
if ( !EM2TypeSetUtil.contains(ep.getTypeSet(),ef.getTypeTokenConstraint())){
error(ef,"Type token constraint "+EM2Util.getPrintName(ef.getTypeTokenConstraint())+" is not contained in type set of outgoing propagation "+EM2Util.getPrintName(ep)+EM2Util.getPrintName(ep.getTypeSet()));
}
}
private void checkErrorSinkTypes(ErrorSink ef){
ErrorPropagation ep = ef.getIncoming();
if ( !EM2TypeSetUtil.contains(ep.getTypeSet(),ef.getTypeTokenConstraint())){
error(ef,"Type token constraint is not contained in type set of incoming propagation \""+EM2Util.getPrintName(ep)+"\"");
}
}
private void checkErrorPathTypes(ErrorPath ef){
if (ef.getTypeTokenConstraint() != null){
ErrorPropagation epin = ef.getIncoming();
if ( !EM2TypeSetUtil.contains(epin.getTypeSet(),ef.getTypeTokenConstraint())){
error(ef,"Type token constraint is not contained in type set of incoming propagation \""+EM2Util.getPrintName(epin)+"\"");
}
}
if (ef.getTargetToken() != null){
ErrorPropagation epout = ef.getOutgoing();
if ( !EM2TypeSetUtil.contains(epout.getTypeSet(),ef.getTargetToken())){
error(ef,"Target token is not contained in type set of outgoing propagation "+EM2Util.getPrintName(epout));
}
}
}
private void checkConnectionErrorTypes(Connection conn){
ComponentImplementation cimpl = conn.getContainingComponentImpl();
ConnectionEnd src = conn.getAllSource();
Context srcCxt = conn.getAllSourceContext();
ErrorPropagation srcprop = null;
ErrorPropagation srccontain = null;
ErrorModelSubclause srcems = null;
ErrorPropagations srceps = null;
if (srcCxt instanceof Subcomponent){
ComponentClassifier cl = ((Subcomponent)srcCxt).getClassifier();
srcems = EM2Util.getContainingClassifierEMV2Subclause(cl);
if (srcems != null) srceps = srcems.getPropagation();
} else {
srcems = EM2Util.getContainingClassifierEMV2Subclause(cimpl);
if (srcems != null) srceps = srcems.getPropagation();
}
if (srceps != null) {
srcprop = EM2Util.findOutgoingErrorPropagation(srceps, src.getName());
srccontain = EM2Util.findOutgoingErrorContainment(srceps, src.getName());
}
ConnectionEnd dst = conn.getAllDestination();
Context dstCxt = conn.getAllDestinationContext();
ErrorPropagations dsteps = null;
ErrorModelSubclause dstems = null;
ErrorPropagation dstprop = null;
ErrorPropagation dstcontain = null;
if (dstCxt instanceof Subcomponent){
ComponentClassifier cl = ((Subcomponent)dstCxt).getClassifier();
dstems = EM2Util.getContainingClassifierEMV2Subclause(cl);
if (dstems != null) dsteps = dstems.getPropagation();
} else {
dstems = EM2Util.getContainingClassifierEMV2Subclause(cimpl);
if (dstems != null) dsteps = dstems.getPropagation();
}
if (dsteps != null) {
dstprop = EM2Util.findIncomingErrorPropagation(dsteps, dst.getName());
dstcontain = EM2Util.findIncomingErrorContainment(dsteps, dst.getName());
}
if (srcprop != null && dstprop != null){
if(! EM2TypeSetUtil.contains(dstprop.getTypeSet(),srcprop.getTypeSet())){
error(conn,"Outgoing propagation "+EM2Util.getPrintName(srcprop)+EM2Util.getPrintName(srcprop.getTypeSet()) +" has error types not handled by incoming propagation "+EM2Util.getPrintName(dstprop)+EM2Util.getPrintName(dstprop.getTypeSet()));
}
}
if (srccontain != null && dstcontain != null){
if(! EM2TypeSetUtil.contains(srccontain.getTypeSet(),dstcontain.getTypeSet())){
error(conn,"Outgoing containment "+EM2Util.getPrintName(srcprop)+EM2Util.getPrintName(srcprop.getTypeSet()) +" does not contain error types listed by incoming containment "+EM2Util.getPrintName(dstprop)+EM2Util.getPrintName(dstprop.getTypeSet()));
}
}
if (srcCxt instanceof Subcomponent && srcprop == null&&srccontain == null &&dstCxt instanceof Subcomponent&& (dstprop != null||dstcontain != null)){
if (srcems != null){
// has an EMV2 subclause but no propagation specification for the feature
error(conn,"Connection source has no error propagation/containment but target does: "+(dstprop!=null?EM2Util.getPrintName(dstprop):EM2Util.getPrintName(dstcontain)));
} else {
// TODO check in instance model for connection end point if no error model subclause
- info(conn,"Connection source has no error model subclause but target does: "+(dstprop!=null?EM2Util.getPrintName(dstprop):EM2Util.getPrintName(dstcontain))+". Please validate propagations in instance model");
+ info(conn,"Connection source has no error model subclause but target does: "+(dstprop!=null?EM2Util.getPrintName(dstprop):EM2Util.getPrintName(dstcontain))+". Please add error model to source or validate against error model of source subcomponents in instance model");
}
}
if (dstCxt instanceof Subcomponent && dstprop == null &&dstCxt instanceof Subcomponent&& dstcontain == null && (srcprop != null||srccontain != null)){
if (dstems != null){
// has an EMV2 subclause but no propagation specification for the feature
error(conn,"Connection target has no error propagation/containment but source does: "+(srcprop!=null?EM2Util.getPrintName(srcprop):EM2Util.getPrintName(srccontain)));
} else {
// TODO check in instance model for connection end point if no error model subclause
- error(conn,"Connection target has no error model subclause but source does: "+(srcprop!=null?EM2Util.getPrintName(srcprop):EM2Util.getPrintName(srccontain))+". Please validate propagations in instance model");
+ error(conn,"Connection target has no error model subclause but source does: "+(srcprop!=null?EM2Util.getPrintName(srcprop):EM2Util.getPrintName(srccontain))+". Please add error model to target or validate against error model of target subcomponents in instance model");
}
}
if (conn.isBidirectional()){
// check for error flow in the opposite direction
if (srceps != null) {
dstprop = EM2Util.findIncomingErrorPropagation(srceps, src.getName());
dstcontain = EM2Util.findIncomingErrorContainment(srceps, src.getName());
}
if (dsteps != null) {
srcprop = EM2Util.findOutgoingErrorPropagation(dsteps, dst.getName());
srccontain = EM2Util.findOutgoingErrorContainment(dsteps, dst.getName());
}
if (srcprop != null && dstprop != null){
if(! EM2TypeSetUtil.contains(dstprop.getTypeSet(),srcprop.getTypeSet())){
error(conn,"Outgoing propagation "+EM2Util.getPrintName(srcprop)+EM2Util.getPrintName(srcprop.getTypeSet()) +" has error types not handled by incoming propagation "+EM2Util.getPrintName(dstprop)+EM2Util.getPrintName(dstprop.getTypeSet()));
}
}
if (srccontain != null && dstcontain != null){
if(! EM2TypeSetUtil.contains(srccontain.getTypeSet(),dstcontain.getTypeSet())){
error(conn,"Outgoing containment "+EM2Util.getPrintName(srcprop)+EM2Util.getPrintName(srcprop.getTypeSet()) +" does not contain error types listed by incoming containment "+EM2Util.getPrintName(dstprop)+EM2Util.getPrintName(dstprop.getTypeSet()));
}
}
if (srcCxt instanceof Subcomponent &&dstCxt instanceof Subcomponent&& srcprop == null&&srccontain == null && (dstprop != null||dstcontain != null)){
if (dstems != null){ // we are doing opposite direction
// has an EMV2 subclause but no propagation specification for the feature
error(conn,"Connection source has no error propagation/containment but target does: "+(dstprop!=null?EM2Util.getPrintName(dstprop):EM2Util.getPrintName(dstcontain)));
} else {
// TODO check in instance model for connection end point if no error model subclause
info(conn,"Connection source has no error model subclause but target does: "+(dstprop!=null?EM2Util.getPrintName(dstprop):EM2Util.getPrintName(dstcontain))+". Please validate propagations in instance model");
}
}
if (dstCxt instanceof Subcomponent &&dstCxt instanceof Subcomponent&& dstprop == null && dstcontain == null && (srcprop != null||srccontain != null)){
if (dstems != null){
// has an EMV2 subclause but no propagation specification for the feature
error(conn,"Connection target has no error propagation/containment but source does: "+(srcprop!=null?EM2Util.getPrintName(srcprop):EM2Util.getPrintName(srccontain)));
} else {
// TODO check in instance model for connection end point if no error model subclause
error(conn,"Connection target has no error model subclause but source does: "+(srcprop!=null?EM2Util.getPrintName(srcprop):EM2Util.getPrintName(srccontain))+". Please validate propagations in instance model");
}
}
}
}
}
| false | true | private void checkConnectionErrorTypes(Connection conn){
ComponentImplementation cimpl = conn.getContainingComponentImpl();
ConnectionEnd src = conn.getAllSource();
Context srcCxt = conn.getAllSourceContext();
ErrorPropagation srcprop = null;
ErrorPropagation srccontain = null;
ErrorModelSubclause srcems = null;
ErrorPropagations srceps = null;
if (srcCxt instanceof Subcomponent){
ComponentClassifier cl = ((Subcomponent)srcCxt).getClassifier();
srcems = EM2Util.getContainingClassifierEMV2Subclause(cl);
if (srcems != null) srceps = srcems.getPropagation();
} else {
srcems = EM2Util.getContainingClassifierEMV2Subclause(cimpl);
if (srcems != null) srceps = srcems.getPropagation();
}
if (srceps != null) {
srcprop = EM2Util.findOutgoingErrorPropagation(srceps, src.getName());
srccontain = EM2Util.findOutgoingErrorContainment(srceps, src.getName());
}
ConnectionEnd dst = conn.getAllDestination();
Context dstCxt = conn.getAllDestinationContext();
ErrorPropagations dsteps = null;
ErrorModelSubclause dstems = null;
ErrorPropagation dstprop = null;
ErrorPropagation dstcontain = null;
if (dstCxt instanceof Subcomponent){
ComponentClassifier cl = ((Subcomponent)dstCxt).getClassifier();
dstems = EM2Util.getContainingClassifierEMV2Subclause(cl);
if (dstems != null) dsteps = dstems.getPropagation();
} else {
dstems = EM2Util.getContainingClassifierEMV2Subclause(cimpl);
if (dstems != null) dsteps = dstems.getPropagation();
}
if (dsteps != null) {
dstprop = EM2Util.findIncomingErrorPropagation(dsteps, dst.getName());
dstcontain = EM2Util.findIncomingErrorContainment(dsteps, dst.getName());
}
if (srcprop != null && dstprop != null){
if(! EM2TypeSetUtil.contains(dstprop.getTypeSet(),srcprop.getTypeSet())){
error(conn,"Outgoing propagation "+EM2Util.getPrintName(srcprop)+EM2Util.getPrintName(srcprop.getTypeSet()) +" has error types not handled by incoming propagation "+EM2Util.getPrintName(dstprop)+EM2Util.getPrintName(dstprop.getTypeSet()));
}
}
if (srccontain != null && dstcontain != null){
if(! EM2TypeSetUtil.contains(srccontain.getTypeSet(),dstcontain.getTypeSet())){
error(conn,"Outgoing containment "+EM2Util.getPrintName(srcprop)+EM2Util.getPrintName(srcprop.getTypeSet()) +" does not contain error types listed by incoming containment "+EM2Util.getPrintName(dstprop)+EM2Util.getPrintName(dstprop.getTypeSet()));
}
}
if (srcCxt instanceof Subcomponent && srcprop == null&&srccontain == null &&dstCxt instanceof Subcomponent&& (dstprop != null||dstcontain != null)){
if (srcems != null){
// has an EMV2 subclause but no propagation specification for the feature
error(conn,"Connection source has no error propagation/containment but target does: "+(dstprop!=null?EM2Util.getPrintName(dstprop):EM2Util.getPrintName(dstcontain)));
} else {
// TODO check in instance model for connection end point if no error model subclause
info(conn,"Connection source has no error model subclause but target does: "+(dstprop!=null?EM2Util.getPrintName(dstprop):EM2Util.getPrintName(dstcontain))+". Please validate propagations in instance model");
}
}
if (dstCxt instanceof Subcomponent && dstprop == null &&dstCxt instanceof Subcomponent&& dstcontain == null && (srcprop != null||srccontain != null)){
if (dstems != null){
// has an EMV2 subclause but no propagation specification for the feature
error(conn,"Connection target has no error propagation/containment but source does: "+(srcprop!=null?EM2Util.getPrintName(srcprop):EM2Util.getPrintName(srccontain)));
} else {
// TODO check in instance model for connection end point if no error model subclause
error(conn,"Connection target has no error model subclause but source does: "+(srcprop!=null?EM2Util.getPrintName(srcprop):EM2Util.getPrintName(srccontain))+". Please validate propagations in instance model");
}
}
if (conn.isBidirectional()){
// check for error flow in the opposite direction
if (srceps != null) {
dstprop = EM2Util.findIncomingErrorPropagation(srceps, src.getName());
dstcontain = EM2Util.findIncomingErrorContainment(srceps, src.getName());
}
if (dsteps != null) {
srcprop = EM2Util.findOutgoingErrorPropagation(dsteps, dst.getName());
srccontain = EM2Util.findOutgoingErrorContainment(dsteps, dst.getName());
}
if (srcprop != null && dstprop != null){
if(! EM2TypeSetUtil.contains(dstprop.getTypeSet(),srcprop.getTypeSet())){
error(conn,"Outgoing propagation "+EM2Util.getPrintName(srcprop)+EM2Util.getPrintName(srcprop.getTypeSet()) +" has error types not handled by incoming propagation "+EM2Util.getPrintName(dstprop)+EM2Util.getPrintName(dstprop.getTypeSet()));
}
}
if (srccontain != null && dstcontain != null){
if(! EM2TypeSetUtil.contains(srccontain.getTypeSet(),dstcontain.getTypeSet())){
error(conn,"Outgoing containment "+EM2Util.getPrintName(srcprop)+EM2Util.getPrintName(srcprop.getTypeSet()) +" does not contain error types listed by incoming containment "+EM2Util.getPrintName(dstprop)+EM2Util.getPrintName(dstprop.getTypeSet()));
}
}
if (srcCxt instanceof Subcomponent &&dstCxt instanceof Subcomponent&& srcprop == null&&srccontain == null && (dstprop != null||dstcontain != null)){
if (dstems != null){ // we are doing opposite direction
// has an EMV2 subclause but no propagation specification for the feature
error(conn,"Connection source has no error propagation/containment but target does: "+(dstprop!=null?EM2Util.getPrintName(dstprop):EM2Util.getPrintName(dstcontain)));
} else {
// TODO check in instance model for connection end point if no error model subclause
info(conn,"Connection source has no error model subclause but target does: "+(dstprop!=null?EM2Util.getPrintName(dstprop):EM2Util.getPrintName(dstcontain))+". Please validate propagations in instance model");
}
}
if (dstCxt instanceof Subcomponent &&dstCxt instanceof Subcomponent&& dstprop == null && dstcontain == null && (srcprop != null||srccontain != null)){
if (dstems != null){
// has an EMV2 subclause but no propagation specification for the feature
error(conn,"Connection target has no error propagation/containment but source does: "+(srcprop!=null?EM2Util.getPrintName(srcprop):EM2Util.getPrintName(srccontain)));
} else {
// TODO check in instance model for connection end point if no error model subclause
error(conn,"Connection target has no error model subclause but source does: "+(srcprop!=null?EM2Util.getPrintName(srcprop):EM2Util.getPrintName(srccontain))+". Please validate propagations in instance model");
}
}
}
}
| private void checkConnectionErrorTypes(Connection conn){
ComponentImplementation cimpl = conn.getContainingComponentImpl();
ConnectionEnd src = conn.getAllSource();
Context srcCxt = conn.getAllSourceContext();
ErrorPropagation srcprop = null;
ErrorPropagation srccontain = null;
ErrorModelSubclause srcems = null;
ErrorPropagations srceps = null;
if (srcCxt instanceof Subcomponent){
ComponentClassifier cl = ((Subcomponent)srcCxt).getClassifier();
srcems = EM2Util.getContainingClassifierEMV2Subclause(cl);
if (srcems != null) srceps = srcems.getPropagation();
} else {
srcems = EM2Util.getContainingClassifierEMV2Subclause(cimpl);
if (srcems != null) srceps = srcems.getPropagation();
}
if (srceps != null) {
srcprop = EM2Util.findOutgoingErrorPropagation(srceps, src.getName());
srccontain = EM2Util.findOutgoingErrorContainment(srceps, src.getName());
}
ConnectionEnd dst = conn.getAllDestination();
Context dstCxt = conn.getAllDestinationContext();
ErrorPropagations dsteps = null;
ErrorModelSubclause dstems = null;
ErrorPropagation dstprop = null;
ErrorPropagation dstcontain = null;
if (dstCxt instanceof Subcomponent){
ComponentClassifier cl = ((Subcomponent)dstCxt).getClassifier();
dstems = EM2Util.getContainingClassifierEMV2Subclause(cl);
if (dstems != null) dsteps = dstems.getPropagation();
} else {
dstems = EM2Util.getContainingClassifierEMV2Subclause(cimpl);
if (dstems != null) dsteps = dstems.getPropagation();
}
if (dsteps != null) {
dstprop = EM2Util.findIncomingErrorPropagation(dsteps, dst.getName());
dstcontain = EM2Util.findIncomingErrorContainment(dsteps, dst.getName());
}
if (srcprop != null && dstprop != null){
if(! EM2TypeSetUtil.contains(dstprop.getTypeSet(),srcprop.getTypeSet())){
error(conn,"Outgoing propagation "+EM2Util.getPrintName(srcprop)+EM2Util.getPrintName(srcprop.getTypeSet()) +" has error types not handled by incoming propagation "+EM2Util.getPrintName(dstprop)+EM2Util.getPrintName(dstprop.getTypeSet()));
}
}
if (srccontain != null && dstcontain != null){
if(! EM2TypeSetUtil.contains(srccontain.getTypeSet(),dstcontain.getTypeSet())){
error(conn,"Outgoing containment "+EM2Util.getPrintName(srcprop)+EM2Util.getPrintName(srcprop.getTypeSet()) +" does not contain error types listed by incoming containment "+EM2Util.getPrintName(dstprop)+EM2Util.getPrintName(dstprop.getTypeSet()));
}
}
if (srcCxt instanceof Subcomponent && srcprop == null&&srccontain == null &&dstCxt instanceof Subcomponent&& (dstprop != null||dstcontain != null)){
if (srcems != null){
// has an EMV2 subclause but no propagation specification for the feature
error(conn,"Connection source has no error propagation/containment but target does: "+(dstprop!=null?EM2Util.getPrintName(dstprop):EM2Util.getPrintName(dstcontain)));
} else {
// TODO check in instance model for connection end point if no error model subclause
info(conn,"Connection source has no error model subclause but target does: "+(dstprop!=null?EM2Util.getPrintName(dstprop):EM2Util.getPrintName(dstcontain))+". Please add error model to source or validate against error model of source subcomponents in instance model");
}
}
if (dstCxt instanceof Subcomponent && dstprop == null &&dstCxt instanceof Subcomponent&& dstcontain == null && (srcprop != null||srccontain != null)){
if (dstems != null){
// has an EMV2 subclause but no propagation specification for the feature
error(conn,"Connection target has no error propagation/containment but source does: "+(srcprop!=null?EM2Util.getPrintName(srcprop):EM2Util.getPrintName(srccontain)));
} else {
// TODO check in instance model for connection end point if no error model subclause
error(conn,"Connection target has no error model subclause but source does: "+(srcprop!=null?EM2Util.getPrintName(srcprop):EM2Util.getPrintName(srccontain))+". Please add error model to target or validate against error model of target subcomponents in instance model");
}
}
if (conn.isBidirectional()){
// check for error flow in the opposite direction
if (srceps != null) {
dstprop = EM2Util.findIncomingErrorPropagation(srceps, src.getName());
dstcontain = EM2Util.findIncomingErrorContainment(srceps, src.getName());
}
if (dsteps != null) {
srcprop = EM2Util.findOutgoingErrorPropagation(dsteps, dst.getName());
srccontain = EM2Util.findOutgoingErrorContainment(dsteps, dst.getName());
}
if (srcprop != null && dstprop != null){
if(! EM2TypeSetUtil.contains(dstprop.getTypeSet(),srcprop.getTypeSet())){
error(conn,"Outgoing propagation "+EM2Util.getPrintName(srcprop)+EM2Util.getPrintName(srcprop.getTypeSet()) +" has error types not handled by incoming propagation "+EM2Util.getPrintName(dstprop)+EM2Util.getPrintName(dstprop.getTypeSet()));
}
}
if (srccontain != null && dstcontain != null){
if(! EM2TypeSetUtil.contains(srccontain.getTypeSet(),dstcontain.getTypeSet())){
error(conn,"Outgoing containment "+EM2Util.getPrintName(srcprop)+EM2Util.getPrintName(srcprop.getTypeSet()) +" does not contain error types listed by incoming containment "+EM2Util.getPrintName(dstprop)+EM2Util.getPrintName(dstprop.getTypeSet()));
}
}
if (srcCxt instanceof Subcomponent &&dstCxt instanceof Subcomponent&& srcprop == null&&srccontain == null && (dstprop != null||dstcontain != null)){
if (dstems != null){ // we are doing opposite direction
// has an EMV2 subclause but no propagation specification for the feature
error(conn,"Connection source has no error propagation/containment but target does: "+(dstprop!=null?EM2Util.getPrintName(dstprop):EM2Util.getPrintName(dstcontain)));
} else {
// TODO check in instance model for connection end point if no error model subclause
info(conn,"Connection source has no error model subclause but target does: "+(dstprop!=null?EM2Util.getPrintName(dstprop):EM2Util.getPrintName(dstcontain))+". Please validate propagations in instance model");
}
}
if (dstCxt instanceof Subcomponent &&dstCxt instanceof Subcomponent&& dstprop == null && dstcontain == null && (srcprop != null||srccontain != null)){
if (dstems != null){
// has an EMV2 subclause but no propagation specification for the feature
error(conn,"Connection target has no error propagation/containment but source does: "+(srcprop!=null?EM2Util.getPrintName(srcprop):EM2Util.getPrintName(srccontain)));
} else {
// TODO check in instance model for connection end point if no error model subclause
error(conn,"Connection target has no error model subclause but source does: "+(srcprop!=null?EM2Util.getPrintName(srcprop):EM2Util.getPrintName(srccontain))+". Please validate propagations in instance model");
}
}
}
}
|
diff --git a/framework/src/main/java/org/qi4j/library/framework/constraint/NotEmptyConstraint.java b/framework/src/main/java/org/qi4j/library/framework/constraint/NotEmptyConstraint.java
index 830c0c602..53e11b783 100644
--- a/framework/src/main/java/org/qi4j/library/framework/constraint/NotEmptyConstraint.java
+++ b/framework/src/main/java/org/qi4j/library/framework/constraint/NotEmptyConstraint.java
@@ -1,40 +1,40 @@
/*
* Copyright 2008 Richard Wallace
* Copyright 2008 Alin Dreghiciu.
*
* 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.qi4j.library.framework.constraint;
import org.qi4j.composite.Constraint;
import org.qi4j.library.framework.constraint.annotation.NotEmpty;
/**
* Constraints that a string is non empty.
*
* @author Richard Wallace
* @author Alin Dreghiciu
* @since 09 May, 2008
*/
public class NotEmptyConstraint
implements Constraint<NotEmpty, String>
{
public boolean isValid( NotEmpty annotation, String value )
{
- return (null != value) && (value.trim().length() > 0);
+ return value.trim().length() > 0;
}
}
| true | true | public boolean isValid( NotEmpty annotation, String value )
{
return (null != value) && (value.trim().length() > 0);
}
| public boolean isValid( NotEmpty annotation, String value )
{
return value.trim().length() > 0;
}
|
diff --git a/plugins/org.eclipse.acceleo.engine/src/org/eclipse/acceleo/engine/internal/environment/DynamicModulesURIConverter.java b/plugins/org.eclipse.acceleo.engine/src/org/eclipse/acceleo/engine/internal/environment/DynamicModulesURIConverter.java
index f9109d95..b34bf5e6 100644
--- a/plugins/org.eclipse.acceleo.engine/src/org/eclipse/acceleo/engine/internal/environment/DynamicModulesURIConverter.java
+++ b/plugins/org.eclipse.acceleo.engine/src/org/eclipse/acceleo/engine/internal/environment/DynamicModulesURIConverter.java
@@ -1,430 +1,430 @@
/*******************************************************************************
* Copyright (c) 2010, 2011 Obeo.
* 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:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.acceleo.engine.internal.environment;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.acceleo.common.IAcceleoConstants;
import org.eclipse.acceleo.common.internal.utils.workspace.AcceleoWorkspaceUtil;
import org.eclipse.acceleo.common.internal.utils.workspace.BundleURLConverter;
import org.eclipse.acceleo.common.utils.CompactLinkedHashSet;
import org.eclipse.acceleo.model.mtl.Module;
import org.eclipse.emf.common.EMFPlugin;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.ContentHandler;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.URIConverter;
import org.eclipse.emf.ecore.resource.URIHandler;
import org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl;
/**
* This will allow us to handle references to file scheme URIs within the resource set containing the
* generation modules and their dynamic overrides. We need this since the dynamic overrides are loaded with
* file scheme URIs whereas the generation module can be loaded through platform scheme URIs and we need
* references to be resolved anyway.
*
* @author <a href="mailto:[email protected]">Laurent Goubet</a>
*/
final class DynamicModulesURIConverter extends ExtensibleURIConverterImpl {
/** The parent URIConverted if any. */
private URIConverter parent;
/** This will be initialized with the environment that asked for the construction of a converter. */
private final AcceleoEvaluationEnvironment parentEnvironment;
/**
* This is only meant to be instantiated once for each generation, from the
* {@link AcceleoEvaluationEnvironment} only.
*
* @param parent
* The parent URIConverter. Can be <code>null</code>.
* @param parentEnvironment
* Environment that asked for this URI converter instance.
*/
DynamicModulesURIConverter(URIConverter parent, AcceleoEvaluationEnvironment parentEnvironment) {
this.parent = parent;
this.parentEnvironment = parentEnvironment;
}
/**
* {@inheritDoc}
*
* @see ExtensibleURIConverterImpl#normalize(URI)
*/
@Override
public URI normalize(URI uri) {
URI normalized = normalizeWithParent(uri);
if (normalized == null || normalized.equals(uri)) {
normalized = dynamicNormalize(uri);
}
return normalized;
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#getURIMap()
*/
@Override
public Map<URI, URI> getURIMap() {
if (parent != null) {
return parent.getURIMap();
}
return super.getURIMap();
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#getURIHandlers()
*/
@Override
public EList<URIHandler> getURIHandlers() {
if (parent != null) {
return parent.getURIHandlers();
}
return super.getURIHandlers();
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#getURIHandler(org.eclipse.emf.common.util.URI)
*/
@Override
public URIHandler getURIHandler(URI uri) {
if (parent != null) {
return parent.getURIHandler(uri);
}
return super.getURIHandler(uri);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#getContentHandlers()
*/
@Override
public EList<ContentHandler> getContentHandlers() {
if (parent != null) {
return parent.getContentHandlers();
}
return super.getContentHandlers();
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#createInputStream(org.eclipse.emf.common.util.URI)
*/
@Override
public InputStream createInputStream(URI uri) throws IOException {
if (parent != null) {
return parent.createInputStream(uri);
}
return super.createInputStream(uri);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#createInputStream(org.eclipse.emf.common.util.URI,
* java.util.Map)
*/
@Override
public InputStream createInputStream(URI uri, Map<?, ?> options) throws IOException {
if (parent != null) {
return parent.createInputStream(uri, options);
}
return super.createInputStream(uri, options);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#createOutputStream(org.eclipse.emf.common.util.URI)
*/
@Override
public OutputStream createOutputStream(URI uri) throws IOException {
if (parent != null) {
return parent.createOutputStream(uri);
}
return super.createOutputStream(uri);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#createOutputStream(org.eclipse.emf.common.util.URI,
* java.util.Map)
*/
@Override
public OutputStream createOutputStream(URI uri, Map<?, ?> options) throws IOException {
if (parent != null) {
return parent.createOutputStream(uri, options);
}
return super.createOutputStream(uri, options);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#delete(org.eclipse.emf.common.util.URI,
* java.util.Map)
*/
@Override
public void delete(URI uri, Map<?, ?> options) throws IOException {
if (parent != null) {
parent.delete(uri, options);
}
super.delete(uri, options);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#contentDescription(org.eclipse.emf.common.util.URI,
* java.util.Map)
*/
@Override
public Map<String, ?> contentDescription(URI uri, Map<?, ?> options) throws IOException {
if (parent != null) {
return parent.contentDescription(uri, options);
}
return super.contentDescription(uri, options);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#exists(org.eclipse.emf.common.util.URI,
* java.util.Map)
*/
@Override
public boolean exists(URI uri, Map<?, ?> options) {
if (parent != null) {
return parent.exists(uri, options);
}
return super.exists(uri, options);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#getAttributes(org.eclipse.emf.common.util.URI,
* java.util.Map)
*/
@Override
public Map<String, ?> getAttributes(URI uri, Map<?, ?> options) {
if (parent != null) {
return parent.getAttributes(uri, options);
}
return super.getAttributes(uri, options);
}
/**
* {@inheritDoc}
*
* @see org.eclipse.emf.ecore.resource.impl.ExtensibleURIConverterImpl#setAttributes(org.eclipse.emf.common.util.URI,
* java.util.Map, java.util.Map)
*/
@Override
public void setAttributes(URI uri, Map<String, ?> attributes, Map<?, ?> options) throws IOException {
if (parent != null) {
parent.setAttributes(uri, attributes, options);
}
super.setAttributes(uri, attributes, options);
}
/**
* Normalizes the given URI using the parent environment.
*
* @param uri
* The uri we are to normalize.
* @return The normalized form of <code>uri</code>.
*/
private URI normalizeWithParent(URI uri) {
if (parent != null) {
return parent.normalize(uri);
}
return uri;
}
/**
* This will be called if the parent {@link URIConverter} didn't know how to convert the given URI.
*
* @param uri
* The uri we are to normalize.
* @return The normalized form of <code>uri</code>.
*/
private URI dynamicNormalize(URI uri) {
URI normalized = getURIMap().get(uri);
- if (normalized == null) {
+ if (normalized == null && EMFPlugin.IS_ECLIPSE_RUNNING) {
BundleURLConverter conv = new BundleURLConverter(uri.toString());
if (conv.resolveBundle() != null) {
normalized = URI.createURI(conv.resolveAsPlatformPlugin());
}
}
if (normalized == null
&& (!IAcceleoConstants.EMTL_FILE_EXTENSION.equals(uri.fileExtension()) || !"file".equals(uri.scheme()))) { //$NON-NLS-1$
normalized = super.normalize(uri);
}
if (normalized != null) {
getURIMap().put(uri, normalized);
return normalized;
}
String moduleName = uri.lastSegment();
moduleName = moduleName.substring(0, moduleName.lastIndexOf('.'));
Set<URI> candidateURIs = new CompactLinkedHashSet<URI>();
// Search matching module in the current generation context
Set<Module> candidateModules = searchCurrentModuleForCandidateMatches(moduleName);
for (Module candidateModule : candidateModules) {
if (candidateModule.eResource() != null) {
candidateURIs.add(candidateModule.eResource().getURI());
}
}
// If there were no matching module, search in their ResourceSet(s)
if (candidateURIs.size() == 0) {
candidateURIs.addAll(searchResourceSetForMatches(moduleName));
}
if (candidateURIs.size() == 1) {
normalized = candidateURIs.iterator().next();
} else if (candidateURIs.size() > 0) {
normalized = findBestMatchFor(uri, candidateURIs);
}
// There is a chance that our match should itself be normalized
if ((normalized == null || "file".equals(normalized.scheme())) //$NON-NLS-1$
&& EMFPlugin.IS_ECLIPSE_RUNNING) {
BundleURLConverter conv = new BundleURLConverter(uri.toString());
if (conv.resolveBundle() != null) {
normalized = URI.createURI(conv.resolveAsPlatformPlugin());
} else {
String uriToString = uri.toString();
if (uriToString.indexOf('#') > 0) {
uriToString = uriToString.substring(0, uriToString.indexOf('#'));
}
String resolvedPath = AcceleoWorkspaceUtil.resolveInBundles(uriToString);
if (resolvedPath != null) {
normalized = URI.createURI(resolvedPath);
}
}
}
if (normalized == null) {
normalized = super.normalize(uri);
}
if (!uri.equals(normalized)) {
getURIMap().put(uri, normalized);
}
return normalized;
}
/**
* Returns the normalized form of the URI, using the given multiple candidates (this means that more than
* 2 modules had a matching name).
*
* @param uri
* The URI that is to be normalized.
* @param candidateURIs
* URIs of the modules that can potentially be a match for <code>uri</code>.
* @return the normalized form
*/
private URI findBestMatchFor(URI uri, Set<URI> candidateURIs) {
URI normalized = null;
final Iterator<URI> candidatesIterator = candidateURIs.iterator();
final List<String> referenceSegments = Arrays.asList(uri.segments());
Collections.reverse(referenceSegments);
int highestEqualFragments = 0;
while (candidatesIterator.hasNext()) {
final URI next = candidatesIterator.next();
int equalFragments = 0;
final List<String> candidateSegments = Arrays.asList(next.segments());
Collections.reverse(candidateSegments);
for (int i = 0; i < Math.min(candidateSegments.size(), referenceSegments.size()); i++) {
if (candidateSegments.get(i) == referenceSegments.get(i)) {
equalFragments++;
} else {
break;
}
}
if (equalFragments > highestEqualFragments) {
highestEqualFragments = equalFragments;
normalized = next;
}
}
return normalized;
}
/**
* This will search the current generation context for a loaded module matching the given
* <code>moduleName</code>.
*
* @param moduleName
* Name of the module we seek.
* @return The Set of all modules currently loaded for generation going by the name
* <code>moduleName</code>.
*/
private Set<Module> searchCurrentModuleForCandidateMatches(String moduleName) {
Set<Module> candidates = new CompactLinkedHashSet<Module>();
for (Module module : parentEnvironment.getCurrentModules()) {
if (moduleName.equals(module.getName())) {
candidates.add(module);
}
}
return candidates;
}
/**
* This will search throughout the resourceSet(s) containing the loaded modules for modules going by name
* <code>moduleName</code>.
*
* @param moduleName
* Name of the module we seek.
* @return The Set of all modules loaded within the generation ResourceSet going by the name
* <code>moduleName</code>.
*/
private Set<URI> searchResourceSetForMatches(String moduleName) {
final Set<URI> candidates = new CompactLinkedHashSet<URI>();
final List<ResourceSet> resourceSets = new ArrayList<ResourceSet>();
for (Module module : parentEnvironment.getCurrentModules()) {
if (module != null && module.eResource() != null) {
final ResourceSet resourceSet = module.eResource().getResourceSet();
if (!resourceSets.contains(resourceSet)) {
resourceSets.add(resourceSet);
}
}
}
for (ResourceSet resourceSet : resourceSets) {
for (Resource resource : resourceSet.getResources()) {
if (IAcceleoConstants.EMTL_FILE_EXTENSION.equals(resource.getURI().fileExtension())) {
String candidateName = resource.getURI().lastSegment();
candidateName = candidateName.substring(0, candidateName.lastIndexOf('.'));
if (moduleName.equals(candidateName)) {
candidates.add(resource.getURI());
}
}
}
}
return candidates;
}
}
| true | true | private URI dynamicNormalize(URI uri) {
URI normalized = getURIMap().get(uri);
if (normalized == null) {
BundleURLConverter conv = new BundleURLConverter(uri.toString());
if (conv.resolveBundle() != null) {
normalized = URI.createURI(conv.resolveAsPlatformPlugin());
}
}
if (normalized == null
&& (!IAcceleoConstants.EMTL_FILE_EXTENSION.equals(uri.fileExtension()) || !"file".equals(uri.scheme()))) { //$NON-NLS-1$
normalized = super.normalize(uri);
}
if (normalized != null) {
getURIMap().put(uri, normalized);
return normalized;
}
String moduleName = uri.lastSegment();
moduleName = moduleName.substring(0, moduleName.lastIndexOf('.'));
Set<URI> candidateURIs = new CompactLinkedHashSet<URI>();
// Search matching module in the current generation context
Set<Module> candidateModules = searchCurrentModuleForCandidateMatches(moduleName);
for (Module candidateModule : candidateModules) {
if (candidateModule.eResource() != null) {
candidateURIs.add(candidateModule.eResource().getURI());
}
}
// If there were no matching module, search in their ResourceSet(s)
if (candidateURIs.size() == 0) {
candidateURIs.addAll(searchResourceSetForMatches(moduleName));
}
if (candidateURIs.size() == 1) {
normalized = candidateURIs.iterator().next();
} else if (candidateURIs.size() > 0) {
normalized = findBestMatchFor(uri, candidateURIs);
}
// There is a chance that our match should itself be normalized
if ((normalized == null || "file".equals(normalized.scheme())) //$NON-NLS-1$
&& EMFPlugin.IS_ECLIPSE_RUNNING) {
BundleURLConverter conv = new BundleURLConverter(uri.toString());
if (conv.resolveBundle() != null) {
normalized = URI.createURI(conv.resolveAsPlatformPlugin());
} else {
String uriToString = uri.toString();
if (uriToString.indexOf('#') > 0) {
uriToString = uriToString.substring(0, uriToString.indexOf('#'));
}
String resolvedPath = AcceleoWorkspaceUtil.resolveInBundles(uriToString);
if (resolvedPath != null) {
normalized = URI.createURI(resolvedPath);
}
}
}
if (normalized == null) {
normalized = super.normalize(uri);
}
if (!uri.equals(normalized)) {
getURIMap().put(uri, normalized);
}
return normalized;
}
| private URI dynamicNormalize(URI uri) {
URI normalized = getURIMap().get(uri);
if (normalized == null && EMFPlugin.IS_ECLIPSE_RUNNING) {
BundleURLConverter conv = new BundleURLConverter(uri.toString());
if (conv.resolveBundle() != null) {
normalized = URI.createURI(conv.resolveAsPlatformPlugin());
}
}
if (normalized == null
&& (!IAcceleoConstants.EMTL_FILE_EXTENSION.equals(uri.fileExtension()) || !"file".equals(uri.scheme()))) { //$NON-NLS-1$
normalized = super.normalize(uri);
}
if (normalized != null) {
getURIMap().put(uri, normalized);
return normalized;
}
String moduleName = uri.lastSegment();
moduleName = moduleName.substring(0, moduleName.lastIndexOf('.'));
Set<URI> candidateURIs = new CompactLinkedHashSet<URI>();
// Search matching module in the current generation context
Set<Module> candidateModules = searchCurrentModuleForCandidateMatches(moduleName);
for (Module candidateModule : candidateModules) {
if (candidateModule.eResource() != null) {
candidateURIs.add(candidateModule.eResource().getURI());
}
}
// If there were no matching module, search in their ResourceSet(s)
if (candidateURIs.size() == 0) {
candidateURIs.addAll(searchResourceSetForMatches(moduleName));
}
if (candidateURIs.size() == 1) {
normalized = candidateURIs.iterator().next();
} else if (candidateURIs.size() > 0) {
normalized = findBestMatchFor(uri, candidateURIs);
}
// There is a chance that our match should itself be normalized
if ((normalized == null || "file".equals(normalized.scheme())) //$NON-NLS-1$
&& EMFPlugin.IS_ECLIPSE_RUNNING) {
BundleURLConverter conv = new BundleURLConverter(uri.toString());
if (conv.resolveBundle() != null) {
normalized = URI.createURI(conv.resolveAsPlatformPlugin());
} else {
String uriToString = uri.toString();
if (uriToString.indexOf('#') > 0) {
uriToString = uriToString.substring(0, uriToString.indexOf('#'));
}
String resolvedPath = AcceleoWorkspaceUtil.resolveInBundles(uriToString);
if (resolvedPath != null) {
normalized = URI.createURI(resolvedPath);
}
}
}
if (normalized == null) {
normalized = super.normalize(uri);
}
if (!uri.equals(normalized)) {
getURIMap().put(uri, normalized);
}
return normalized;
}
|
diff --git a/src/main/java/net/krinsoft/jobsuite/JobManager.java b/src/main/java/net/krinsoft/jobsuite/JobManager.java
index a64e407..f931f9a 100644
--- a/src/main/java/net/krinsoft/jobsuite/JobManager.java
+++ b/src/main/java/net/krinsoft/jobsuite/JobManager.java
@@ -1,260 +1,260 @@
package net.krinsoft.jobsuite;
import net.krinsoft.jobsuite.db.Database;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author krinsdeath
*/
public class JobManager {
private final JobCore plugin;
private Database database;
private Map<Integer, Job> jobs = new HashMap<Integer, Job>();
private List<Job> claims = new ArrayList<Job>();
private int nextJob;
public JobManager(JobCore instance) {
this.plugin = instance;
}
public void load() {
database = new Database(plugin);
nextJob = plugin.getConfig().getInt("jobs.total", 0);
}
public void close() {
persist();
database.close();
}
public void persist() {
PreparedStatement schema = database.prepare("REPLACE INTO jobsuite_schema (id, NEXT_ID) VALUES (?, ?);");
PreparedStatement jobStatement = database.prepare("REPLACE INTO jobsuite_base (job_id, owner, name, description, expiry, reward, locked_by, finished, claimed) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);");
PreparedStatement itemStatement = database.prepare("REPLACE INTO jobsuite_items (job_id, item_entry, enchantment_entry, type, amount, enchanted) VALUES (?, ?, ?, ?, ?, ?);");
PreparedStatement enchStatement = database.prepare("REPLACE INTO jobsuite_enchantments (job_id, enchantment_entry, item_entry, enchantment, power) VALUES (?, ?, ?, ?, ?);");
try {
schema.setInt(1, 1);
schema.setInt(2, nextJob);
schema.executeUpdate();
jobStatement.getConnection().setAutoCommit(false);
for (Map.Entry<Integer, Job> entry : jobs.entrySet()) {
Job job = entry.getValue();
if (job.isExpired()) {
continue;
}
jobStatement.setInt(1, job.getId());
jobStatement.setString(2, job.getOwner());
jobStatement.setString(3, job.getName());
jobStatement.setString(4, job.getDescription());
jobStatement.setLong(5, job.getDuration());
jobStatement.setDouble(6, job.getReward());
jobStatement.setString(7, job.getLock());
jobStatement.setBoolean(8, job.isFinished());
jobStatement.setBoolean(9, job.isClaimed());
jobStatement.executeUpdate();
for (JobItem item : job.getItems()) {
itemStatement.setInt(1, job.getId());
itemStatement.setInt(2, item.getId());
itemStatement.setInt(3, item.hashCode());
itemStatement.setString(4, item.getItem().getType().toString());
itemStatement.setInt(5, item.getItem().getAmount());
itemStatement.setBoolean(6, item.getItem().getEnchantments().size() > 0);
itemStatement.executeUpdate();
for (Map.Entry<Enchantment, Integer> ench : item.getItem().getEnchantments().entrySet()) {
enchStatement.setInt(1, job.getId());
enchStatement.setInt(2, item.hashCode());
- enchStatement.setInt(3, ench.getKey().getId());
- enchStatement.setInt(4, item.getId());
+ enchStatement.setInt(3, item.getId());
+ enchStatement.setInt(4, ench.getKey().getId());
enchStatement.setInt(5, ench.getValue());
enchStatement.executeUpdate();
}
}
}
schema.getConnection().commit();
} catch (SQLException e) {
plugin.getLogger().warning("An SQLException occurred: " + e.getMessage());
}
}
public List<Job> getJobs(CommandSender sender) {
List<Job> temp = new ArrayList<Job>();
for (Job job : jobs.values()) {
if (job.getLock() == null || job.getLock().equals(sender.getName()) || job.getOwner().equals(sender.getName())) {
temp.add(job);
}
}
return temp;
}
/**
* Gets the specified Job by its ID
* @param id The ID of the job we're fetching
* @return The Job and all of its details, otherwise null
*/
public Job getJob(int id) {
return jobs.get(id);
}
public boolean addJob(Job job) {
Job j = jobs.get(job.getId());
if (j != null && j.equals(job)) {
plugin.getLogger().finest("Duplicate job: '" + job.getName() + "'@'" + job.getId() + "'");
return false;
} else {
plugin.getLogger().finer("Job '" + job.getName() + "'@'" + job.getId() + "' registered.");
jobs.put(job.getId(), job);
return true;
}
}
/**
* Registers the specified job
* @param owner The owner of the job
* @return true if the job is valid and added, otherwise false
*/
public boolean addJob(String owner) {
if (owner == null) { return false; }
Job job = queued.get(owner);
if (job == null) { return false; }
jobs.put(job.getId(), job);
queued.remove(owner);
plugin.getConfig().set("jobs.total", nextJob);
return true;
}
/**
* Attempts to cancel the specified job.
* @param sender The person who is issuing the command.
* @param job The job we're attempting to cancel.
* @return true if the job was successfully canceled, otherwise false.
*/
public boolean cancelJob(CommandSender sender, Job job) {
if (!(job != null && (job.getOwner().equals(sender.getName()) || sender.hasPermission("jobsuite.admin.cancel") || job.isExpired()))) {
return false;
}
Job cancel = jobs.remove(job.getId());
if (cancel != null) {
if (sender instanceof Player) {
plugin.getBank().give((Player) sender, cancel.getReward(), -1);
}
PreparedStatement basePrep = database.prepare("DELETE FROM jobsuite_base WHERE job_id = ? ;");
PreparedStatement itemPrep = database.prepare("DELETE FROM jobsuite_items WHERE job_id = ? ;");
PreparedStatement enchPrep = database.prepare("DELETE FROM jobsuite_enchantments WHERE job_id = ? ;");
try {
basePrep.setInt(1, cancel.getId());
basePrep.executeUpdate();
itemPrep.setInt(1, cancel.getId());
itemPrep.executeUpdate();
enchPrep.setInt(1, cancel.getId());
enchPrep.executeUpdate();
} catch (SQLException e) {
plugin.getLogger().warning("An SQLException occurred: " + e.getMessage());
}
}
return cancel != null;
}
public void finishJob(CommandSender sender, Job job) {
moveToClaims(job);
if (!(sender instanceof ConsoleCommandSender)) {
plugin.getBank().give((Player) sender, job.getReward(), -1);
}
}
public void moveToClaims(Job job) {
if (!job.isFinished()) {
Player owner = plugin.getServer().getPlayer(job.getOwner());
if (owner != null) {
owner.sendMessage(ChatColor.GREEN + "[Job] One of your jobs has been completed: " + ChatColor.AQUA + "/job claim");
}
job.finish();
claims.add(job);
if (job.getOwner().equals("CONSOLE")) {
claim(job);
}
}
}
public List<Job> getClaimableJobs(CommandSender sender) {
List<Job> jobs = new ArrayList<Job>();
for (Job job : claims) {
if (job.getOwner().equals(sender.getName())) {
jobs.add(job);
}
}
return jobs;
}
public Job getClaimableJob(CommandSender sender, int id) {
for (Job job : getClaimableJobs(sender)) {
if (job.getId() == id) {
return job;
}
}
return null;
}
public void claim(Job job) {
if (claims.contains(job)) {
job.claim();
claims.remove(job);
jobs.remove(job.getId());
}
}
/////////////////
// JOB QUEUING //
/////////////////
private Map<String, Job> queued = new HashMap<String, Job>();
/**
* Gets a job that is currently being created by the player's name
* @param player The player whose job we're fetching
* @return The job associated with the player, or null
*/
public Job getQueuedJob(String player) {
return queued.get(player);
}
/**
* Adds a job to the queue unless the player already has one queued
* @param player The player responsible for the job
* @param name The job's name
* @return true if the job is added, otherwise false (the player has one queued or an object was null)
*/
public boolean addQueuedJob(String player, String name) {
if (queued.get(player) == null) {
if (player == null || name == null || name.length() == 0) {
return false;
}
Job job = new Job(player, name, ++nextJob);
queued.put(player, job);
return true;
}
return false;
}
/**
* Attempts to remove the specified player's queued job
* @param player The player whose job we're removing
* @return true if the job existed and was removed, otherwise false
*/
public boolean removeQueuedJob(String player) {
return queued.remove(player) != null;
}
}
| true | true | public void persist() {
PreparedStatement schema = database.prepare("REPLACE INTO jobsuite_schema (id, NEXT_ID) VALUES (?, ?);");
PreparedStatement jobStatement = database.prepare("REPLACE INTO jobsuite_base (job_id, owner, name, description, expiry, reward, locked_by, finished, claimed) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);");
PreparedStatement itemStatement = database.prepare("REPLACE INTO jobsuite_items (job_id, item_entry, enchantment_entry, type, amount, enchanted) VALUES (?, ?, ?, ?, ?, ?);");
PreparedStatement enchStatement = database.prepare("REPLACE INTO jobsuite_enchantments (job_id, enchantment_entry, item_entry, enchantment, power) VALUES (?, ?, ?, ?, ?);");
try {
schema.setInt(1, 1);
schema.setInt(2, nextJob);
schema.executeUpdate();
jobStatement.getConnection().setAutoCommit(false);
for (Map.Entry<Integer, Job> entry : jobs.entrySet()) {
Job job = entry.getValue();
if (job.isExpired()) {
continue;
}
jobStatement.setInt(1, job.getId());
jobStatement.setString(2, job.getOwner());
jobStatement.setString(3, job.getName());
jobStatement.setString(4, job.getDescription());
jobStatement.setLong(5, job.getDuration());
jobStatement.setDouble(6, job.getReward());
jobStatement.setString(7, job.getLock());
jobStatement.setBoolean(8, job.isFinished());
jobStatement.setBoolean(9, job.isClaimed());
jobStatement.executeUpdate();
for (JobItem item : job.getItems()) {
itemStatement.setInt(1, job.getId());
itemStatement.setInt(2, item.getId());
itemStatement.setInt(3, item.hashCode());
itemStatement.setString(4, item.getItem().getType().toString());
itemStatement.setInt(5, item.getItem().getAmount());
itemStatement.setBoolean(6, item.getItem().getEnchantments().size() > 0);
itemStatement.executeUpdate();
for (Map.Entry<Enchantment, Integer> ench : item.getItem().getEnchantments().entrySet()) {
enchStatement.setInt(1, job.getId());
enchStatement.setInt(2, item.hashCode());
enchStatement.setInt(3, ench.getKey().getId());
enchStatement.setInt(4, item.getId());
enchStatement.setInt(5, ench.getValue());
enchStatement.executeUpdate();
}
}
}
schema.getConnection().commit();
} catch (SQLException e) {
plugin.getLogger().warning("An SQLException occurred: " + e.getMessage());
}
}
| public void persist() {
PreparedStatement schema = database.prepare("REPLACE INTO jobsuite_schema (id, NEXT_ID) VALUES (?, ?);");
PreparedStatement jobStatement = database.prepare("REPLACE INTO jobsuite_base (job_id, owner, name, description, expiry, reward, locked_by, finished, claimed) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);");
PreparedStatement itemStatement = database.prepare("REPLACE INTO jobsuite_items (job_id, item_entry, enchantment_entry, type, amount, enchanted) VALUES (?, ?, ?, ?, ?, ?);");
PreparedStatement enchStatement = database.prepare("REPLACE INTO jobsuite_enchantments (job_id, enchantment_entry, item_entry, enchantment, power) VALUES (?, ?, ?, ?, ?);");
try {
schema.setInt(1, 1);
schema.setInt(2, nextJob);
schema.executeUpdate();
jobStatement.getConnection().setAutoCommit(false);
for (Map.Entry<Integer, Job> entry : jobs.entrySet()) {
Job job = entry.getValue();
if (job.isExpired()) {
continue;
}
jobStatement.setInt(1, job.getId());
jobStatement.setString(2, job.getOwner());
jobStatement.setString(3, job.getName());
jobStatement.setString(4, job.getDescription());
jobStatement.setLong(5, job.getDuration());
jobStatement.setDouble(6, job.getReward());
jobStatement.setString(7, job.getLock());
jobStatement.setBoolean(8, job.isFinished());
jobStatement.setBoolean(9, job.isClaimed());
jobStatement.executeUpdate();
for (JobItem item : job.getItems()) {
itemStatement.setInt(1, job.getId());
itemStatement.setInt(2, item.getId());
itemStatement.setInt(3, item.hashCode());
itemStatement.setString(4, item.getItem().getType().toString());
itemStatement.setInt(5, item.getItem().getAmount());
itemStatement.setBoolean(6, item.getItem().getEnchantments().size() > 0);
itemStatement.executeUpdate();
for (Map.Entry<Enchantment, Integer> ench : item.getItem().getEnchantments().entrySet()) {
enchStatement.setInt(1, job.getId());
enchStatement.setInt(2, item.hashCode());
enchStatement.setInt(3, item.getId());
enchStatement.setInt(4, ench.getKey().getId());
enchStatement.setInt(5, ench.getValue());
enchStatement.executeUpdate();
}
}
}
schema.getConnection().commit();
} catch (SQLException e) {
plugin.getLogger().warning("An SQLException occurred: " + e.getMessage());
}
}
|
diff --git a/com.mobilesorcery.sdk.builder.iphoneos/src/com/mobilesorcery/sdk/builder/iphoneos/IPhoneOSPackager.java b/com.mobilesorcery.sdk.builder.iphoneos/src/com/mobilesorcery/sdk/builder/iphoneos/IPhoneOSPackager.java
index 35c5afbe..2140df11 100644
--- a/com.mobilesorcery.sdk.builder.iphoneos/src/com/mobilesorcery/sdk/builder/iphoneos/IPhoneOSPackager.java
+++ b/com.mobilesorcery.sdk.builder.iphoneos/src/com/mobilesorcery/sdk/builder/iphoneos/IPhoneOSPackager.java
@@ -1,185 +1,185 @@
/* Copyright (C) 2009 Mobile Sorcery AB
This program is free software; you can redistribute it and/or modify it
under the terms of the Eclipse Public License v1.0.
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 Eclipse Public License v1.0 for
more details.
You should have received a copy of the Eclipse Public License v1.0 along
with this program. It is also available at http://www.eclipse.org/legal/epl-v10.html
*/
package com.mobilesorcery.sdk.builder.iphoneos;
import java.io.File;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import com.mobilesorcery.sdk.core.AbstractPackager;
import com.mobilesorcery.sdk.core.DefaultPackager;
import com.mobilesorcery.sdk.core.IBuildResult;
import com.mobilesorcery.sdk.core.IBuildVariant;
import com.mobilesorcery.sdk.core.IconManager;
import com.mobilesorcery.sdk.core.MoSyncProject;
import com.mobilesorcery.sdk.core.MoSyncTool;
import com.mobilesorcery.sdk.core.Util;
import com.mobilesorcery.sdk.core.Version;
/**
* Plugin entry point. Is responsible for creating xcode
* project for iphone os devices.
*
* @author Ali Mosavian
*/
public class IPhoneOSPackager
extends AbstractPackager
{
private String m_iphoneBuildLoc;
public IPhoneOSPackager ( )
{
MoSyncTool tool = MoSyncTool.getDefault( );
m_iphoneBuildLoc = tool.getBinary( "iphone-builder" ).toOSString( );
}
/**
* This method is called upon whenever a iphone os package
* is to be built.
*
* @param project
* @param targetProfile Profile information i presume.
* @param buildResult The build result is returned through this parameter.
*
* @throws CoreException Error occurred
*/
public void createPackage ( MoSyncProject project,
IBuildVariant variant,
IBuildResult buildResult )
throws CoreException
{
String appName;
String version;
String company;
IconManager icon;
DefaultPackager intern;
// Was used for printing to console
intern = new DefaultPackager( project,
variant );
//
// Custom parameters
//
appName = intern.getParameters( ).get( DefaultPackager.APP_NAME );
version = intern.getParameters( ).get( DefaultPackager.APP_VERSION );
company = intern.getParameters( ).get( DefaultPackager.APP_VENDOR_NAME );
try
{
String ver = new Version( version ).asCanonicalString( Version.MICRO );
File in = intern.resolveFile( "%runtime-dir%/template" );
File out = intern.resolveFile( "%package-output-dir%/xcode-proj" );
out.mkdirs( );
// Create XCode template
int res = intern.runCommandLineWithRes( m_iphoneBuildLoc,
"generate",
"-project-name",
appName,
"-version",
ver,
"-company-name",
company,
"-input",
in.getAbsolutePath( ),
"-output",
out.getAbsolutePath( ) );
// Did it run successfully?
if ( res != 0 )
return;
// Copy program files to xcode template
Util.copyFile( new NullProgressMonitor( ),
intern.resolveFile( "%compile-output-dir%/data_section.bin" ),
new File( out, "data_section.bin" ) );
Util.copyFile( new NullProgressMonitor( ),
intern.resolveFile( "%compile-output-dir%/rebuild.build.cpp" ),
new File( out, "Classes/rebuild.build.cpp" ) );
File resources = intern.resolveFile( "%compile-output-dir%/resources" );
if ( resources.exists( ) == true )
{
Util.copyFile( new NullProgressMonitor( ),
resources,
new File( out, "resources" ) );
}
else
{
Util.writeToFile( new File( out, "resources" ), "" );
}
//
// Set icons here
// Note: Always set a 48x48 png at the very least!
//
try
{
File f;
icon = new IconManager( intern,
project );
// Set PNG icons
if ( icon.hasIcon( "png" ) == true )
{
int[] sizes = {57, 72};
for ( int s : sizes )
{
try
{
if ( s == 57 )
f = new File( out, "Icon.png" );
else
f = new File( out, "Icon-"+s+".png" );
if ( f.exists( ) == true )
f.delete( );
icon.inject( f, s, s, "png" );
}
catch ( Exception e )
{
buildResult.addError( e.getMessage( ) );
}
}
}
}
catch ( Exception e )
{
buildResult.addError( e.getMessage( ) );
}
buildResult.setBuildResult( out );
}
catch ( Exception e )
{
// Return stack trace in case of error
throw new CoreException( new Status( IStatus.ERROR,
"com.mobilesorcery.builder.iphoneos",
- "Failed to build the xcode template. NOTE: Building for iOS devices is only possible from Mac OS X at the moment." ));
+ "Failed to build the xcode template." ));
}
}
}
| true | true | public void createPackage ( MoSyncProject project,
IBuildVariant variant,
IBuildResult buildResult )
throws CoreException
{
String appName;
String version;
String company;
IconManager icon;
DefaultPackager intern;
// Was used for printing to console
intern = new DefaultPackager( project,
variant );
//
// Custom parameters
//
appName = intern.getParameters( ).get( DefaultPackager.APP_NAME );
version = intern.getParameters( ).get( DefaultPackager.APP_VERSION );
company = intern.getParameters( ).get( DefaultPackager.APP_VENDOR_NAME );
try
{
String ver = new Version( version ).asCanonicalString( Version.MICRO );
File in = intern.resolveFile( "%runtime-dir%/template" );
File out = intern.resolveFile( "%package-output-dir%/xcode-proj" );
out.mkdirs( );
// Create XCode template
int res = intern.runCommandLineWithRes( m_iphoneBuildLoc,
"generate",
"-project-name",
appName,
"-version",
ver,
"-company-name",
company,
"-input",
in.getAbsolutePath( ),
"-output",
out.getAbsolutePath( ) );
// Did it run successfully?
if ( res != 0 )
return;
// Copy program files to xcode template
Util.copyFile( new NullProgressMonitor( ),
intern.resolveFile( "%compile-output-dir%/data_section.bin" ),
new File( out, "data_section.bin" ) );
Util.copyFile( new NullProgressMonitor( ),
intern.resolveFile( "%compile-output-dir%/rebuild.build.cpp" ),
new File( out, "Classes/rebuild.build.cpp" ) );
File resources = intern.resolveFile( "%compile-output-dir%/resources" );
if ( resources.exists( ) == true )
{
Util.copyFile( new NullProgressMonitor( ),
resources,
new File( out, "resources" ) );
}
else
{
Util.writeToFile( new File( out, "resources" ), "" );
}
//
// Set icons here
// Note: Always set a 48x48 png at the very least!
//
try
{
File f;
icon = new IconManager( intern,
project );
// Set PNG icons
if ( icon.hasIcon( "png" ) == true )
{
int[] sizes = {57, 72};
for ( int s : sizes )
{
try
{
if ( s == 57 )
f = new File( out, "Icon.png" );
else
f = new File( out, "Icon-"+s+".png" );
if ( f.exists( ) == true )
f.delete( );
icon.inject( f, s, s, "png" );
}
catch ( Exception e )
{
buildResult.addError( e.getMessage( ) );
}
}
}
}
catch ( Exception e )
{
buildResult.addError( e.getMessage( ) );
}
buildResult.setBuildResult( out );
}
catch ( Exception e )
{
// Return stack trace in case of error
throw new CoreException( new Status( IStatus.ERROR,
"com.mobilesorcery.builder.iphoneos",
"Failed to build the xcode template. NOTE: Building for iOS devices is only possible from Mac OS X at the moment." ));
}
}
| public void createPackage ( MoSyncProject project,
IBuildVariant variant,
IBuildResult buildResult )
throws CoreException
{
String appName;
String version;
String company;
IconManager icon;
DefaultPackager intern;
// Was used for printing to console
intern = new DefaultPackager( project,
variant );
//
// Custom parameters
//
appName = intern.getParameters( ).get( DefaultPackager.APP_NAME );
version = intern.getParameters( ).get( DefaultPackager.APP_VERSION );
company = intern.getParameters( ).get( DefaultPackager.APP_VENDOR_NAME );
try
{
String ver = new Version( version ).asCanonicalString( Version.MICRO );
File in = intern.resolveFile( "%runtime-dir%/template" );
File out = intern.resolveFile( "%package-output-dir%/xcode-proj" );
out.mkdirs( );
// Create XCode template
int res = intern.runCommandLineWithRes( m_iphoneBuildLoc,
"generate",
"-project-name",
appName,
"-version",
ver,
"-company-name",
company,
"-input",
in.getAbsolutePath( ),
"-output",
out.getAbsolutePath( ) );
// Did it run successfully?
if ( res != 0 )
return;
// Copy program files to xcode template
Util.copyFile( new NullProgressMonitor( ),
intern.resolveFile( "%compile-output-dir%/data_section.bin" ),
new File( out, "data_section.bin" ) );
Util.copyFile( new NullProgressMonitor( ),
intern.resolveFile( "%compile-output-dir%/rebuild.build.cpp" ),
new File( out, "Classes/rebuild.build.cpp" ) );
File resources = intern.resolveFile( "%compile-output-dir%/resources" );
if ( resources.exists( ) == true )
{
Util.copyFile( new NullProgressMonitor( ),
resources,
new File( out, "resources" ) );
}
else
{
Util.writeToFile( new File( out, "resources" ), "" );
}
//
// Set icons here
// Note: Always set a 48x48 png at the very least!
//
try
{
File f;
icon = new IconManager( intern,
project );
// Set PNG icons
if ( icon.hasIcon( "png" ) == true )
{
int[] sizes = {57, 72};
for ( int s : sizes )
{
try
{
if ( s == 57 )
f = new File( out, "Icon.png" );
else
f = new File( out, "Icon-"+s+".png" );
if ( f.exists( ) == true )
f.delete( );
icon.inject( f, s, s, "png" );
}
catch ( Exception e )
{
buildResult.addError( e.getMessage( ) );
}
}
}
}
catch ( Exception e )
{
buildResult.addError( e.getMessage( ) );
}
buildResult.setBuildResult( out );
}
catch ( Exception e )
{
// Return stack trace in case of error
throw new CoreException( new Status( IStatus.ERROR,
"com.mobilesorcery.builder.iphoneos",
"Failed to build the xcode template." ));
}
}
|
diff --git a/src/drbd/gui/ClusterBrowser.java b/src/drbd/gui/ClusterBrowser.java
index e4ae11e3..1d9ee103 100644
--- a/src/drbd/gui/ClusterBrowser.java
+++ b/src/drbd/gui/ClusterBrowser.java
@@ -1,7250 +1,7254 @@
/*
* This file is part of DRBD Management Console by LINBIT HA-Solutions GmbH
* written by Rasto Levrinc.
*
* Copyright (C) 2009, LINBIT HA-Solutions GmbH.
*
* DRBD Management Console 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, or (at your option)
* any later version.
*
* DRBD Management Console 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 drbd; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package drbd.gui;
import drbd.AddDrbdConfigDialog;
import drbd.AddDrbdSplitBrainDialog;
import drbd.AddHostDialog;
import drbd.utilities.Tools;
import drbd.utilities.Unit;
import drbd.utilities.DRBD;
import drbd.utilities.UpdatableItem;
import drbd.Exceptions;
import drbd.gui.dialog.ClusterLogs;
import drbd.gui.dialog.ServiceLogs;
import drbd.gui.dialog.ClusterDrbdLogs;
import drbd.data.Host;
import drbd.data.Cluster;
import drbd.data.HeartbeatStatus;
import drbd.data.HeartbeatXML;
import drbd.data.DrbdXML;
import drbd.utilities.NewOutputCallback;
import drbd.utilities.ExecCallback;
import drbd.utilities.Heartbeat;
import drbd.data.resources.Resource;
import drbd.data.resources.Service;
import drbd.data.resources.CommonBlockDevice;
import drbd.data.resources.BlockDevice;
import drbd.data.resources.Network;
import drbd.data.resources.DrbdResource;
import drbd.data.HeartbeatService;
import drbd.utilities.MyMenu;
import drbd.utilities.MyMenuItem;
import drbd.gui.HostBrowser.BlockDevInfo;
import drbd.gui.HostBrowser.HostInfo;
import java.awt.Color;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.JComponent;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.event.DocumentListener;
import javax.swing.event.DocumentEvent;
import javax.swing.BoxLayout;
import javax.swing.ImageIcon;
import javax.swing.JTree;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.Box;
import javax.swing.DefaultListModel;
import java.awt.Component;
import java.awt.BorderLayout;
import java.awt.geom.Point2D;
import java.awt.Dimension;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.awt.event.ItemListener;
import java.awt.event.ItemEvent;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Enumeration;
import java.util.Map;
import java.util.HashMap;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
import EDU.oswego.cs.dl.util.concurrent.Mutex;
import org.apache.commons.collections.map.MultiKeyMap;
/**
* This class holds cluster resource data in a tree. It shows panels that allow
* to edit data of services etc.
* Every resource has its Info object, that accessible through the tree view.
*
* @author Rasto Levrinc
* @version $Id$
*
*/
public class ClusterBrowser extends Browser {
/**
* Cluster object that holds data of the cluster. (One Browser belongs to
* one cluster).
*/
private final Cluster cluster;
/** Menu's all hosts node. */
private DefaultMutableTreeNode allHostsNode;
/** Menu's all hosts in the cluster node. */
private DefaultMutableTreeNode clusterHostsNode;
/** Menu's networks node. */
private DefaultMutableTreeNode networksNode;
/** Menu's common block devices node. */
private DefaultMutableTreeNode commonBlockDevicesNode;
/** Menu's available heartbeat services node. */
private DefaultMutableTreeNode availableServicesNode;
/** Menu's heartbeat services node. */
private DefaultMutableTreeNode servicesNode;
/** Menu's heartbeat scores node. */
private DefaultMutableTreeNode scoresNode;
/** Menu's drbd node. */
private DefaultMutableTreeNode drbdNode;
/** Common file systems on all cluster nodes. */
private String[] commonFileSystems;
/** Common mount points on all cluster nodes. */
private String[] commonMountPoints;
/** name (hb type) + id to service info hash. */
private final Map<String, Map<String, ServiceInfo>> nameToServiceInfoHash =
new HashMap<String, Map<String, ServiceInfo>>();
/** drbd resource name string to drbd resource info hash. */
private final Map<String, DrbdResourceInfo> drbdResHash =
new HashMap<String, DrbdResourceInfo>();
/** drbd resource device string to drbd resource info hash. */
private final Map<String, DrbdResourceInfo> drbdDevHash =
new HashMap<String, DrbdResourceInfo>();
/** Heartbeat id to service info hash. */
private final Map<String, ServiceInfo> heartbeatIdToServiceInfo =
new HashMap<String, ServiceInfo>();
/** Score to its info panel hash. */
private final Map<String, HostScoreInfo> hostScoreInfoMap =
new HashMap<String, HostScoreInfo>();
/** List of heartbeat ids of all services. */
private final List<String> heartbeatIdList = new ArrayList<String>();
/** Heartbeat graph. */
private final HeartbeatGraph heartbeatGraph;
/** Drbd graph. */
private final DrbdGraph drbdGraph;
/** object that holds current heartbeat status. */
private HeartbeatStatus heartbeatStatus;
/** Object that holds hb ocf data. */
private HeartbeatXML heartbeatXML;
/** Object that drbd status and data. */
private DrbdXML drbdXML;
/** Common block device icon. */
private static final ImageIcon COMMON_BD_ICON =
Tools.createImageIcon(
Tools.getDefault("ClusterBrowser.CommonBlockDeviceIcon"));
/** Started service icon. */
private static final ImageIcon SERVICE_STARTED_ICON =
Tools.createImageIcon(
Tools.getDefault("ClusterBrowser.ServiceStartedIcon"));
/** Stopped service icon. */
private static final ImageIcon SERVICE_STOPPED_ICON =
Tools.createImageIcon(
Tools.getDefault("ClusterBrowser.ServiceStoppedIcon"));
/** Network icon. */
private static final ImageIcon NETWORK_ICON =
Tools.createImageIcon(
Tools.getDefault("ClusterBrowser.NetworkIcon"));
/** Available services icon. */
private static final ImageIcon AVAIL_SERVICES_ICON =
Tools.createImageIcon(
Tools.getDefault("ClusterBrowser.ServiceStoppedIcon"));
/** Remove icon. */
private static final ImageIcon REMOVE_ICON =
Tools.createImageIcon(
Tools.getDefault("ClusterBrowser.RemoveIcon"));
/** Migrate icon. */
private static final ImageIcon MIGRATE_ICON =
Tools.createImageIcon(
Tools.getDefault("HeartbeatGraph.MigrateIcon"));
/** Running service icon. */
private static final ImageIcon SERVICE_RUNNING_ICON =
Tools.createImageIcon(
Tools.getDefault("HeartbeatGraph.ServiceRunningIcon"));
/** Not running service icon. */
private static final ImageIcon SERVICE_NOT_RUNNING_ICON =
Tools.createImageIcon(
Tools.getDefault("HeartbeatGraph.ServiceNotRunningIcon"));
/** Add host icon. */
private static final ImageIcon HOST_ICON = Tools.createImageIcon(
Tools.getDefault("HostTab.HostIcon"));
/** Start service icon. */
private static final ImageIcon START_ICON = SERVICE_RUNNING_ICON;
/** Stop service icon. */
private static final ImageIcon STOP_ICON = SERVICE_NOT_RUNNING_ICON;
/** Whether drbd status was canceled by user. */
private boolean drbdStatusCanceled = true;
/** Whether hb status was canceled by user. */
private boolean hbStatusCanceled = true;
/** Tree menu root. */
private JTree treeMenu;
/** Global hb status lock. */
private final Mutex mHbStatusLock = new Mutex();
/** last dc host detected. */
private Host lastDcHost = null;
/** dc host as reported by heartbeat. */
private Host realDcHost = null;
/** Panel that holds this browser. */
private ClusterViewPanel clusterViewPanel = null;
/** Hash that holds all hb classes with descriptions that appear in the
* pull down menus. */
private static final Map<String, String> HB_CLASS_MENU =
new HashMap<String, String>();
/** Whether the hb status is run for the first time. (For the progress
* indicator. */
private boolean hbStatusFirstTime;
/** Width of the label in the info panel. */
private static final int SERVICE_LABEL_WIDTH =
Tools.getDefaultInt("ClusterBrowser.ServiceLabelWidth");
/** Width of the field in the info panel. */
private static final int SERVICE_FIELD_WIDTH =
Tools.getDefaultInt("ClusterBrowser.ServiceFieldWidth");
/** Color of the most of backgrounds. */
private static final Color PANEL_BACKGROUND =
Tools.getDefaultColor("ViewPanel.Background");
/** Color of the extra (advanced options) panel background. */
private static final Color EXTRA_PANEL_BACKGROUND =
Tools.getDefaultColor("ViewPanel.Status.Background");
/** Color of the status bar background. */
private static final Color STATUS_BACKGROUND =
Tools.getDefaultColor("ViewPanel.Status.Background");
/** Name of the drbd resource name parameter. */
private static final String DRBD_RES_PARAM_NAME = "name";
/** Name of the drbd device parameter. */
private static final String DRBD_RES_PARAM_DEV = "device";
/** Name of the boolean type in drbd. */
private static final String DRBD_RES_BOOL_TYPE_NAME = "boolean";
/** Name of the drbd after parameter. */
private static final String DRBD_RES_PARAM_AFTER = "after";
/** Name of the empty parameter, that is used while passing the parameters
* to the drbd-gui-helper script. */
private static final String HB_NONE_ARG = "..none..";
/** Name of the group hearbeat service. */
private static final String HB_GROUP_NAME = "Group";
/** Name of ocf style resource (heartbeat 2). */
private static final String HB_OCF_CLASS = "ocf";
/** Name of heartbeat style resource (heartbeat 1). */
private static final String HB_HEARTBEAT_CLASS = "heartbeat";
/** Name of lsb style resource (/etc/init.d/*). */
private static final String HB_LSB_CLASS = "lsb";
/** Name of the provider. TODO: other providers? */
private static final String HB_HEARTBEAT_PROVIDER = "heartbeat";
/** String array with all hb classes. */
private static final String[] HB_CLASSES = {HB_OCF_CLASS,
HB_HEARTBEAT_CLASS,
HB_LSB_CLASS};
/** Hb start operation. */
private static final String HB_OP_START = "start";
/** Hb stop operation. */
private static final String HB_OP_STOP = "stop";
/** Hb status operation. */
private static final String HB_OP_STATUS = "status";
/** Hb monitor operation. */
private static final String HB_OP_MONITOR = "monitor";
/** Hb meta-data operation. */
private static final String HB_OP_META_DATA = "meta-data";
/** Hb validate-all operation. */
private static final String HB_OP_VALIDATE_ALL = "validate-all";
/** Hb desc parameter. */
private static final String HB_PAR_DESC = "description";
/** Hb interval parameter. */
private static final String HB_PAR_INTERVAL = "interval";
/** Hb timeout parameter. */
private static final String HB_PAR_TIMEOUT = "timeout";
/** Hb start-delay parameter. */
private static final String HB_PAR_START_DELAY = "start-delay";
/** Hb disabled parameter. */
private static final String HB_PAR_DISABLED = "disabled";
/** Hb role parameter. */
private static final String HB_PAR_ROLE = "role";
/** Hb prereq parameter. */
private static final String HB_PAR_PREREQ = "prereq";
/** Hb on-fail parameter. */
private static final String HB_PAR_ON_FAIL = "on-fail";
/** String array with all hb operations. */
private static final String[] HB_OPERATIONS = {HB_OP_START,
HB_OP_STOP,
HB_OP_STATUS,
HB_OP_MONITOR,
HB_OP_META_DATA,
HB_OP_VALIDATE_ALL};
/** Which operations are basic and do not go to the advanced section. */
private static final List<String> HB_OP_BASIC =
Arrays.asList(new String[]{HB_OP_START, HB_OP_STOP});
/** Parameters for the hb operations. */
private static final Map<String, List<String>> HB_OPERATION_PARAMS =
new HashMap<String, List<String>>();
/** All parameters for the hb operations, so that it is possible to create
* arguments for up_rsc_full_ops. */
private static final String[] HB_OPERATION_PARAM_LIST = {HB_PAR_DESC,
HB_PAR_INTERVAL,
HB_PAR_TIMEOUT,
HB_PAR_START_DELAY,
HB_PAR_DISABLED,
HB_PAR_ROLE,
HB_PAR_PREREQ,
HB_PAR_ON_FAIL};
/**
* Prepares a new <code>CusterBrowser</code> object.
*/
public ClusterBrowser(final Cluster cluster) {
super();
this.cluster = cluster;
heartbeatGraph = new HeartbeatGraph(this);
drbdGraph = new DrbdGraph(this);
setTreeTop();
HB_CLASS_MENU.put(HB_OCF_CLASS, "heartbeat 2 (ocf)");
HB_CLASS_MENU.put(HB_HEARTBEAT_CLASS, "heartbeat 1 (hb)");
HB_CLASS_MENU.put(HB_LSB_CLASS, "lsb (init.d)");
HB_OPERATION_PARAMS.put(HB_OP_START,
new ArrayList<String>(
Arrays.asList(HB_PAR_TIMEOUT,
HB_PAR_INTERVAL)));
HB_OPERATION_PARAMS.put(HB_OP_STOP,
new ArrayList<String>(
Arrays.asList(HB_PAR_TIMEOUT,
HB_PAR_INTERVAL)));
HB_OPERATION_PARAMS.put(HB_OP_META_DATA,
new ArrayList<String>(
Arrays.asList(HB_PAR_TIMEOUT,
HB_PAR_INTERVAL)));
HB_OPERATION_PARAMS.put(HB_OP_VALIDATE_ALL,
new ArrayList<String>(
Arrays.asList(HB_PAR_TIMEOUT,
HB_PAR_INTERVAL)));
HB_OPERATION_PARAMS.put(HB_OP_STATUS,
new ArrayList<String>(
Arrays.asList(HB_PAR_TIMEOUT,
HB_PAR_INTERVAL)));
HB_OPERATION_PARAMS.put(HB_OP_MONITOR,
new ArrayList<String>(
Arrays.asList(HB_PAR_TIMEOUT,
HB_PAR_INTERVAL)));
}
/**
* Sets the cluster view panel.
*/
public final void setClusterViewPanel(
final ClusterViewPanel clusterViewPanel) {
this.clusterViewPanel = clusterViewPanel;
}
/**
* Returns cluster view panel.
*/
public final ClusterViewPanel getClusterViewPanel() {
return clusterViewPanel;
}
/**
* Returns all nodes that belong to this cluster.
*/
public final Host[] getClusterHosts() {
return cluster.getHostsArray();
}
/**
* Returns cluster data object.
*/
public final Cluster getCluster() {
return cluster;
}
/**
* Sets the info panel component in the cluster view panel.
*/
public final void setRightComponentInView(final Info i) {
clusterViewPanel.setRightComponentInView(this, i);
}
/**
* Saves positions of service and block devices from the heartbeat and drbd
* graphs to the config files on every node.
*/
public final void saveGraphPositions() {
final Map<String, Point2D> positions = new HashMap<String, Point2D>();
if (drbdGraph != null) {
drbdGraph.getPositions(positions);
}
if (heartbeatGraph != null) {
heartbeatGraph.getPositions(positions);
}
final Host[] hosts = getClusterHosts();
for (Host host : hosts) {
host.saveGraphPositions(positions);
}
}
/**
* Returns heartbeat graph for this cluster.
*/
public final ResourceGraph getHeartbeatGraph() {
return heartbeatGraph;
}
/**
* Returns drbd graph for this cluster.
*/
public final ResourceGraph getDrbdGraph() {
return drbdGraph;
}
/**
* Initializes cluster resources for cluster view.
*/
public final void initClusterResources() {
/* all hosts */
allHostsNode = new DefaultMutableTreeNode(new AllHostsInfo());
setNode(allHostsNode);
topAdd(allHostsNode);
/* hosts */
clusterHostsNode = new DefaultMutableTreeNode(
new CategoryInfo(Tools.getString("ClusterBrowser.ClusterHosts")));
setNode(clusterHostsNode);
topAdd(clusterHostsNode);
/* networks */
networksNode = new DefaultMutableTreeNode(
new CategoryInfo(Tools.getString("ClusterBrowser.Networks")));
setNode(networksNode);
topAdd(networksNode);
/* drbd */
drbdNode = new DefaultMutableTreeNode(
new DrbdInfo(Tools.getString("ClusterBrowser.Drbd")));
setNode(drbdNode);
topAdd(drbdNode);
/* heartbeat */
final HeartbeatInfo heartbeatInfo =
new HeartbeatInfo(
Tools.getString("ClusterBrowser.Heartbeat"));
final DefaultMutableTreeNode heartbeatNode =
new DefaultMutableTreeNode(heartbeatInfo);
setNode(heartbeatNode);
topAdd(heartbeatNode);
/* available services */
availableServicesNode = new DefaultMutableTreeNode(
new HbCategoryInfo(
Tools.getString("ClusterBrowser.availableServices")));
setNode(availableServicesNode);
heartbeatNode.add(availableServicesNode);
/* block devices / shared disks, TODO: */
commonBlockDevicesNode = new DefaultMutableTreeNode(
new HbCategoryInfo(
Tools.getString("ClusterBrowser.CommonBlockDevices")));
setNode(commonBlockDevicesNode);
/* heartbeatNode.add(commonBlockDevicesNode); */
/* scores TODO: make the scores editable? */
scoresNode = new DefaultMutableTreeNode(
new HbCategoryInfo(Tools.getString("ClusterBrowser.Scores")));
setNode(scoresNode);
/* heartbeatNode.add(scoresNode); */
/* scores */
final String[] scores = {"100",
"INFINITY",
"-INFINITY",
"-100",
"0"};
for (String score : scores) {
final HostScoreInfo hsi = new HostScoreInfo(score);
final DefaultMutableTreeNode hostScoreNode =
new DefaultMutableTreeNode(hsi);
hostScoreInfoMap.put(hsi.getName(), hsi);
setNode(hostScoreNode);
scoresNode.add(hostScoreNode);
}
/* services */
final ServicesInfo servicesInfo =
new ServicesInfo(Tools.getString("ClusterBrowser.Services"));
servicesNode = new DefaultMutableTreeNode(servicesInfo);
setNode(servicesNode);
heartbeatNode.add(servicesNode);
}
/**
* Updates resources of a cluster in the tree.
*
* @param clusterHosts
* hosts in this cluster
* @param commonFileSystems
* filesystems that are common on both hosts
* @param commonMountPoints
* mount points that are common on both hosts
*/
public final void updateClusterResources(final JTree treeMenu,
final Host[] clusterHosts,
final String[] commonFileSystems,
final String[] commonMountPoints,
final ClusterViewPanel clusterViewPanel) {
this.treeMenu = treeMenu;
this.commonFileSystems = commonFileSystems;
this.commonMountPoints = commonMountPoints;
DefaultMutableTreeNode resource;
/* all hosts */
final Host[] allHosts =
Tools.getConfigData().getHosts().getHostsArray();
allHostsNode.removeAllChildren();
for (Host host : allHosts) {
final HostBrowser hostBrowser = host.getBrowser();
resource = new DefaultMutableTreeNode(hostBrowser.getHostInfo());
setNode(resource);
allHostsNode.add(resource);
}
reload(allHostsNode);
/* cluster hosts */
clusterHostsNode.removeAllChildren();
for (Host clusterHost : clusterHosts) {
final HostBrowser hostBrowser = clusterHost.getBrowser();
resource = new DefaultMutableTreeNode(hostBrowser.getHostInfo());
setNode(resource);
clusterHostsNode.add(resource);
//drbdGraph.addHost(hostBrowser.getHostInfo());
heartbeatGraph.addHost(hostBrowser.getHostInfo());
}
reload(clusterHostsNode);
/* block devices */
updateCommonBlockDevices();
/* networks */
updateNetworks();
updateHeartbeatDrbdThread(clusterViewPanel);
}
/**
* Starts everything.
*/
private void updateHeartbeatDrbdThread(
final ClusterViewPanel clusterViewPanel) {
final Runnable runnable = new Runnable() {
public void run() {
Host firstHost = null;
final Host[] hosts = cluster.getHostsArray();
for (final Host host : hosts) {
final HostBrowser hostBrowser = host.getBrowser();
drbdGraph.addHost(hostBrowser.getHostInfo());
}
do { /* wait here until a host is connected. */
boolean notConnected = true;
for (final Host host : hosts) {
// TODO: fix that, use latches or callback
if (host.isConnected()) {
/* at least one connected. */
notConnected = false;
break;
} else {
//jfinal HostBrowser hostBrowser = host.getBrowser();
//jdrbdGraph.addHost(hostBrowser.getHostInfo());
}
}
if (!notConnected) {
firstHost = getFirstHost();
}
if (firstHost == null) {
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
} while (firstHost == null);
heartbeatXML = new HeartbeatXML(firstHost);
heartbeatStatus = new HeartbeatStatus(firstHost, heartbeatXML);
drbdXML = new DrbdXML(cluster.getHostsArray());
/* available services */
final String clusterName = getCluster().getName();
Tools.startProgressIndicator(clusterName,
Tools.getString("ClusterBrowser.HbUpdateResources"));
updateAvailableServices();
Tools.stopProgressIndicator(clusterName,
Tools.getString("ClusterBrowser.HbUpdateResources"));
Tools.startProgressIndicator(clusterName,
Tools.getString("ClusterBrowser.DrbdUpdate"));
updateDrbdResources();
//SwingUtilities.invokeLater(new Runnable() { public void run() {
drbdGraph.scale();
//} });
//try { Thread.sleep(10000); }
//catch (InterruptedException ex) {}
Tools.stopProgressIndicator(clusterName,
Tools.getString("ClusterBrowser.DrbdUpdate"));
cluster.getBrowser().startDrbdStatus(clusterViewPanel);
cluster.getBrowser().startHbStatus(clusterViewPanel);
}
};
final Thread thread = new Thread(runnable);
//thread.setPriority(Thread.MIN_PRIORITY);
thread.start();
}
/**
* Starts drbd status on all hosts.
*/
public final void startDrbdStatus(final ClusterViewPanel clusterViewPanel) {
final Host[] hosts = cluster.getHostsArray();
for (final Host host : hosts) {
final Thread thread = new Thread(new Runnable() {
public void run() {
startDrbdStatus(host, clusterViewPanel);
}
});
thread.start();
}
}
/**
* Starts drbd status.
*/
public final void stopDrbdStatus() {
drbdStatusCanceled = true;
final Host[] hosts = cluster.getHostsArray();
for (Host host : hosts) {
host.stopDrbdStatus();
}
for (Host host : hosts) {
host.waitOnDrbdStatus();
}
}
/**
* Starts drbd status on host.
*/
public final void startDrbdStatus(final Host host,
final ClusterViewPanel clusterViewPanel) {
boolean firstTime = true; // TODO: can use a latch for this shit too.
host.setDrbdStatus(true);
final String hostName = host.getName();
while (true) {
final boolean ft = firstTime;
drbdStatusCanceled = false;
host.execDrbdStatusCommand(
new ExecCallback() {
public void done(final String ans) {
}
public void doneError(final String ans, final int exitCode) {
Tools.debug(this, "drbd status failed: " + host.getName() + "exit code: " + exitCode, 2);
if (exitCode != 143) {
/* was killed intentionally */
host.setDrbdStatus(false);
}
//TODO: repaint ok?
//repaintSplitPane();
//drbdGraph.updatePopupMenus();
drbdGraph.repaint();
}
},
new NewOutputCallback() {
public void output(final String output) {
if (output.indexOf("No response from the DRBD driver") >= 0) {
host.setDrbdStatus(false);
return;
} else {
host.setDrbdStatus(true);
}
if (ft) {
Tools.startProgressIndicator(hostName, ": updating drbd status...");
}
final String[] lines = output.split("\n");
drbdXML.update(host);
host.setDrbdStatus(true);
for (int i = 0; i < lines.length; i++) {
parseDrbdEvent(host.getName(), lines[i]);
}
final Thread thread = new Thread(
new Runnable() {
public void run() {
repaintSplitPane();
drbdGraph.updatePopupMenus();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
repaintTree();
}
});
}
});
thread.start();
if (ft) {
Tools.stopProgressIndicator(hostName, ": updating drbd status...");
}
}
});
clusterViewPanel.drbdStatusButtonEnable();
if (!host.isDrbdStatus()) {
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
host.waitOnDrbdStatus();
firstTime = false;
if (drbdStatusCanceled) {
firstTime = true;
break;
}
}
}
/**
* Stops hb status.
*/
public final void stopHbStatus() {
hbStatusCanceled = true;
final Host[] hosts = cluster.getHostsArray();
for (Host host : hosts) {
host.stopHbStatus();
}
}
/**
* Returns true if hb status on all hosts failed.
*/
public final boolean hbStatusFailed() {
final Host[] hosts = cluster.getHostsArray();
for (Host host : hosts) {
if (host.isHbStatus()) {
return false;
}
}
return true;
}
/**
* Sets hb status (failed / not failed for every node).
*/
public final void setHbStatus() {
final Host[] hosts = cluster.getHostsArray();
for (Host host : hosts) {
host.setHbStatus(heartbeatStatus.isActiveNode(host.getName()));
}
}
/**
* Starts hb status progress indicator.
*/
public final void startHbStatusProgressIndicator(final String hostName) {
// TODO; hbStatusFirstTime closure?
Tools.startProgressIndicator(
hostName,
Tools.getString("ClusterBrowser.HbUpdateStatus"));
}
/**
* Stops hb status progress indicator.
*/
public final void stopHbStatusProgressIndicator(final String hostName) {
Tools.stopProgressIndicator(
hostName,
Tools.getString("ClusterBrowser.HbUpdateStatus"));
}
/**
* Starts hb status.
*/
public final void startHbStatus(final ClusterViewPanel clusterViewPanel) {
hbStatusFirstTime = true;
while (true) {
final Host host = getDCHost();
final String hostName = host.getName();
if (host == null) {
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
continue;
}
if (hbStatusFirstTime) {
startHbStatusProgressIndicator(hostName);
}
hbStatusCanceled = false;
host.execHbStatusCommand(
new ExecCallback() {
public void done(final String ans) {
if (hbStatusFirstTime) {
hbStatusFirstTime = false;
selectServices();
//SwingUtilities.invokeLater(new Runnable() { public void run() {
// heartbeatGraph.scale();
//} });
stopHbStatusProgressIndicator(hostName);
}
}
public void doneError(final String ans, final int exitCode) {
Tools.progressIndicatorFailed(hostName, "Heartbeat status failed");
if (hbStatusFirstTime) {
Tools.debug(this, "hb status failed: " + host.getName());
}
hbStatusLock();
final boolean prevHbStatusFailed = hbStatusFailed();
host.setHbStatus(false);
heartbeatStatus.setDC(null);
hbStatusUnlock();
if (prevHbStatusFailed != hbStatusFailed()) {
heartbeatGraph.getServicesInfo().selectMyself();
}
done(ans);
}
},
new NewOutputCallback() {
//TODO: check this buffer's size
private StringBuffer heartbeatStatusOutput = new StringBuffer(300);
public void output(final String output) {
hbStatusLock();
final boolean prevHbStatusFailed = hbStatusFailed();
if (hbStatusCanceled) {
hbStatusUnlock();
if (hbStatusFirstTime) {
hbStatusFirstTime = false;
selectServices();
//SwingUtilities.invokeLater(new Runnable() { public void run() {
heartbeatGraph.scale();
//} });
stopHbStatusProgressIndicator(hostName);
}
return;
}
if (output == null) {
host.setHbStatus(false);
if (prevHbStatusFailed != hbStatusFailed()) {
heartbeatGraph.getServicesInfo().selectMyself();
}
} else {
heartbeatStatusOutput.append(output);
if (heartbeatStatusOutput.length() > 12) {
//host.setHbStatus(true);
final String e = heartbeatStatusOutput.substring(heartbeatStatusOutput.length() - 12);
if (e.trim().equals("---done---")) {
final int i = heartbeatStatusOutput.lastIndexOf("---start---");
if (i >= 0) {
if (heartbeatStatusOutput.indexOf("is stopped") >= 0) {
/* TODO: heartbeat's not running. */
} else {
final String status = heartbeatStatusOutput.substring(i);
heartbeatStatusOutput.delete(0, heartbeatStatusOutput.length() - 1);
if ("---start---\r\nerror\r\n\r\n---done---\r\n".equals(status)) {
host.setHbStatus(false);
} else {
heartbeatStatus.parseStatus(status);
// TODO; servicesInfo can be null
heartbeatGraph.getServicesInfo().setGlobalConfig();
heartbeatGraph.getServicesInfo().setAllResources();
repaintTree();
}
}
}
}
setHbStatus();
} else {
host.setHbStatus(false);
}
}
if (prevHbStatusFailed != hbStatusFailed()) {
heartbeatGraph.getServicesInfo().selectMyself();
}
if (hbStatusFirstTime) {
hbStatusFirstTime = false;
selectServices();
//SwingUtilities.invokeLater(new Runnable() { public void run() {
// heartbeatGraph.scale();
//} });
stopHbStatusProgressIndicator(hostName);
}
hbStatusUnlock();
}
});
clusterViewPanel.hbStatusButtonEnable();
host.waitOnHbStatus();
if (hbStatusCanceled) {
hbStatusFirstTime = true;
break;
}
final boolean hbSt = hbStatusFailed();
if (hbSt) {
try {
Thread.sleep(5000);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
}
/**
* Returns 'add service' list for menus.
*/
public final List<HeartbeatService> globalGetAddServiceList(
final String cl) {
return heartbeatXML.getServices(cl);
}
/**
* Updates common block devices.
*/
private void updateCommonBlockDevices() {
if (commonBlockDevicesNode != null) {
DefaultMutableTreeNode resource;
final List<String> bd = cluster.getCommonBlockDevices();
final Enumeration e = commonBlockDevicesNode.children();
final List<DefaultMutableTreeNode> nodesToRemove =
new ArrayList<DefaultMutableTreeNode>();
while (e.hasMoreElements()) {
final DefaultMutableTreeNode node =
(DefaultMutableTreeNode) e.nextElement();
final Info cbdi = (Info) node.getUserObject();
if (bd.contains(cbdi.getName())) {
/* keeping */
bd.remove(bd.indexOf(cbdi.getName()));
} else {
/* remove not existing block devices */
nodesToRemove.add(node);
}
}
/* remove nodes */
for (DefaultMutableTreeNode node : nodesToRemove) {
node.removeFromParent();
}
/* block devices */
for (String device : bd) {
/* add new block devices */
resource = new DefaultMutableTreeNode(
new CommonBlockDevInfo(
device,
cluster.getHostBlockDevices(device)));
setNode(resource);
commonBlockDevicesNode.add(resource);
}
reload(commonBlockDevicesNode);
}
}
/**
* Updates available services.
*/
private void updateAvailableServices() {
DefaultMutableTreeNode resource;
availableServicesNode.removeAllChildren();
for (final String cl : HB_CLASSES) {
final DefaultMutableTreeNode classNode =
new DefaultMutableTreeNode(
new HbCategoryInfo(cl.toUpperCase()));
for (HeartbeatService hbService : heartbeatXML.getServices(cl)) {
resource = new DefaultMutableTreeNode(
new AvailableServiceInfo(hbService));
setNode(resource);
classNode.add(resource);
}
availableServicesNode.add(classNode);
}
//reload(availableServicesNode);
}
/**
* Updates drbd resources.
*/
private void updateDrbdResources() {
final String[] drbdResources = drbdXML.getResources();
for (int i = 0; i < drbdResources.length; i++) {
final String resName = drbdResources[i];
final String drbdDev = drbdXML.getDrbdDevice(resName);
final Map<String, String> hostDiskMap =
drbdXML.getHostDiskMap(resName);
BlockDevInfo bd1 = null;
BlockDevInfo bd2 = null;
for (String hostName : hostDiskMap.keySet()) {
if (!cluster.contains(hostName)) {
continue;
}
final String disk = hostDiskMap.get(hostName);
final BlockDevInfo bdi = drbdGraph.findBlockDevInfo(hostName,
disk);
if (bdi == null) {
if (drbdDevHash.containsKey(disk)) {
/* TODO: ignoring stacked device */
continue;
} else {
Tools.appWarning("could not find disk: " + disk
+ " on host: " + hostName);
continue;
}
}
bdi.getBlockDevice().setValue(
"DrbdNetInterfacePort",
drbdXML.getVirtualInterfacePort(hostName,
resName));
bdi.getBlockDevice().setValue(
"DrbdNetInterface",
drbdXML.getVirtualInterface(hostName,
resName));
final String drbdMetaDisk = drbdXML.getMetaDisk(hostName,
resName);
bdi.getBlockDevice().setValue("DrbdMetaDisk", drbdMetaDisk);
bdi.getBlockDevice().setValue(
"DrbdMetaDiskIndex",
drbdXML.getMetaDiskIndex(hostName,
resName));
if (drbdMetaDisk != null && !drbdMetaDisk.equals("internal")) {
final BlockDevInfo mdI =
drbdGraph.findBlockDevInfo(hostName,
drbdMetaDisk);
mdI.getBlockDevice().setIsDrbdMetaDisk(true);
bdi.getBlockDevice().setMetaDisk(mdI.getBlockDevice());
}
if (bd1 == null) {
bd1 = bdi;
} else {
bd2 = bdi;
}
}
drbdGraph.getDrbdInfo().addDrbdResource(resName,
drbdDev,
bd1,
bd2,
false);
}
}
/**
* Updates networks.
*/
private void updateNetworks() {
if (networksNode != null) {
DefaultMutableTreeNode resource;
final Network[] networks = cluster.getCommonNetworks();
networksNode.removeAllChildren();
for (int i = 0; i < networks.length; i++) {
resource = new DefaultMutableTreeNode(
new NetworkInfo(networks[i].getName(),
networks[i]));
setNode(resource);
networksNode.add(resource);
}
reload(networksNode);
}
}
/**
* Returns first host. Used for heartbeat commands, that can be
* executed on any host.
* It changes terminal panel to this host.
*/
public final Host getFirstHost() {
/* TODO: if none of the hosts is connected the null causes error during
* loading. */
Host[] hosts = getClusterHosts();
for (Host host : hosts) {
if (host.isConnected()) {
return host;
}
}
//if (hosts != null && hosts.length > 0) {
// return hosts[0];
//}
//Tools.appError("Could not find any hosts");
return null;
}
/**
* Returns whether the host is the real dc host as reported by heartbeat.
*/
public final boolean isRealDcHost(final Host host) {
return host.equals(realDcHost);
}
/**
* Finds and returns DC host.
* TODO: document what's going on.
*/
public final Host getDCHost() {
Host dcHost = null;
final String dc = heartbeatStatus.getDC();
final List<Host> hosts = new ArrayList<Host>();
int lastHostIndex = -1;
int i = 0;
for (Host host : getClusterHosts()) {
if (host.getName().equals(dc)) {
dcHost = host;
break;
}
hosts.add(host);
if (host == lastDcHost) {
lastHostIndex = i;
}
i++;
}
if (dcHost == null) {
int ix = lastHostIndex;
do {
ix++;
if (ix > hosts.size() - 1) {
ix = 0;
}
if (hosts.get(ix).isConnected()) {
lastDcHost = hosts.get(ix);
break;
}
} while (ix == lastHostIndex);
dcHost = lastDcHost;
realDcHost = null;
} else {
realDcHost = dcHost;
}
lastDcHost = dcHost;
return dcHost;
}
/**
* hbStatusLock global lock.
*/
public final void hbStatusLock() {
try {
mHbStatusLock.acquire();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
/**
* hbStatusLock global unlock.
*/
public final void hbStatusUnlock() {
mHbStatusLock.release();
}
/**
* Parses drbd event from host.
*/
public final void parseDrbdEvent(final String hostName,
final String output) {
if (drbdXML == null) {
return;
}
drbdXML.parseDrbdEvent(hostName, drbdGraph, output);
}
/**
* Highlights drbd node.
*/
public final void selectDrbd() {
reload(drbdNode);
}
/**
* Highlights services.
*/
public final void selectServices() {
// this fires treeStructureChanged in ViewPanel.
reload(servicesNode);
}
/**
* Returns ServiceInfo object identified by name and id.
*/
protected final ServiceInfo getServiceInfoFromId(final String name,
final String id) {
final Map<String, ServiceInfo> idToInfoHash =
nameToServiceInfoHash.get(name);
if (idToInfoHash == null) {
return null;
}
return idToInfoHash.get(id);
}
/**
* Removes ServiceInfo from the ServiceInfo hash.
*
* @param serviceInfo
* service info object
*/
protected final void removeFromServiceInfoHash(
final ServiceInfo serviceInfo) {
final Service service = serviceInfo.getService();
final Map<String, ServiceInfo> idToInfoHash =
nameToServiceInfoHash.get(service.getName());
if (idToInfoHash != null) {
idToInfoHash.remove(service.getId());
}
}
/**
* Adds heartbeat id from service to the list. If service does not have an
* id it is generated.
*
* @param si
* service info object
*/
private void addToHeartbeatIdList(final ServiceInfo si) {
String id = si.getService().getHeartbeatId();
if (id == null) {
if (HB_GROUP_NAME.equals(si.getName())) {
id = "grp_";
} else {
id = "res_" + si.getName() + "_";
}
int i = 1;
while (heartbeatIdList.contains(id + Integer.toString(i))) {
i++;
}
final String newId = id + Integer.toString(i);
heartbeatIdList.add(newId);
si.getService().setHeartbeatId(newId);
heartbeatIdToServiceInfo.put(newId, si);
} else {
if (!heartbeatIdList.contains(id)) {
heartbeatIdList.add(id);
}
if (heartbeatIdToServiceInfo.get(id) == null) {
heartbeatIdToServiceInfo.put(id, si);
}
}
}
/**
* Deletes caches of all Filesystem infoPanels.
* This is usefull if something have changed.
*/
public final void resetFilesystems() {
for (String hbId : heartbeatIdToServiceInfo.keySet()) {
final ServiceInfo si = heartbeatIdToServiceInfo.get(hbId);
if (si.getName().equals("Filesystem")) {
si.setInfoPanel(null);
}
}
}
/**
* Adds ServiceInfo in the name to ServiceInfo hash. Id and name
* are taken from serviceInfo object. nameToServiceInfoHash
* contains a hash with id as a key and ServiceInfo as a value.
*
* @param serviceInfo
* service info object
*/
protected final void addNameToServiceInfoHash(
final ServiceInfo serviceInfo) {
/* add to the hash with service name and id as
* keys */
final Service service = serviceInfo.getService();
Map<String, ServiceInfo> idToInfoHash =
nameToServiceInfoHash.get(service.getName());
if (idToInfoHash == null) {
idToInfoHash = new HashMap<String, ServiceInfo>();
if (service.getId() == null) {
service.setId("1");
}
} else {
if (service.getId() == null) {
final Iterator it = idToInfoHash.keySet().iterator();
int index = 0;
while (it.hasNext()) {
final String id =
idToInfoHash.get((String) it.next()).getService().getId();
try {
final int i = Integer.parseInt(id);
if (i > index) {
index = i;
}
} catch (NumberFormatException nfe) {
/* not a number */
}
}
service.setId(Integer.toString(index + 1));
}
}
idToInfoHash.remove(service.getId());
idToInfoHash.put(service.getId(), serviceInfo);
nameToServiceInfoHash.remove(service.getName());
nameToServiceInfoHash.put(service.getName(), idToInfoHash);
}
/**
* Starts heartbeats on all nodes.
*/
public final void startHeartbeats() {
final Host[] hosts = cluster.getHostsArray();
for (Host host : hosts) {
Heartbeat.start(host);
}
}
/**
* This class holds info data for a preferred host score.
* Nothing is displayed.
*/
class HostScoreInfo extends HbCategoryInfo {
/** Heartbeat score to keep a service on a host. It can be number,
* INFINITY or -INFINITY.
*/
private final String score;
/**
* Prepares a new <code>ScoreInfo</code> object.
*
* @param score
* host score, it is either number, INFINITY or -INFINITY
*/
HostScoreInfo(final String score) {
super(Tools.scoreToString(score));
this.score = score;
}
/**
* Returns text about host score info.
*/
public String getInfo() {
return null;
}
/**
* Returns score as string.
*/
public String getScore() {
return score;
}
}
/**
* This class holds info data for a network.
*/
class NetworkInfo extends Info {
/**
* Prepares a new <code>NetworkInfo</code> object.
*/
public NetworkInfo(final String name, final Network network) {
super(name);
setResource(network);
}
/**
* Returns network info.
*/
public String getInfo() {
final String ret = "Net info: " + getNetwork().getName() + "\n"
+ " IPs: " + getNetwork().getIps() + "\n"
+ "Net mask: " + getNetwork().getNetMask()
+ "\n";
return ret;
}
/**
* Returns network resource object.
*/
public Network getNetwork() {
return (Network) getResource();
}
/**
* Returns menu icon for network.
*/
public ImageIcon getMenuIcon() {
return NETWORK_ICON;
}
}
/**
* This interface provides getDevice function for drbd block devices or
* block devices that don't have drbd over them but are used by heartbeat.
*/
public interface CommonDeviceInterface {
/** Returns the name. */
String getName();
/** Returns the device name. */
String getDevice();
/** Sets whether the device is used by heartbeat. */
void setUsedByHeartbeat(boolean isUsedByHeartbeat);
/** Returns whether the device is used by heartbeat. */
boolean isUsedByHeartbeat();
}
/**
* Returns common file systems on all nodes as StringInfo array.
* The defaultValue is stored as the first item in the array.
*/
public final StringInfo[] getCommonFileSystems(final String defaultValue) {
StringInfo[] cfs = new StringInfo[commonFileSystems.length + 1];
cfs[0] = new StringInfo(defaultValue, null);
int i = 1;
for (String cf : commonFileSystems) {
cfs[i] = new StringInfo(cf, cf);
i++;
}
return cfs;
}
/**
* this class holds info data, menus and configuration
* for a drbd resource.
*/
public class DrbdResourceInfo extends EditableInfo
implements CommonDeviceInterface {
/** BlockDevInfo object of the first block device. */
private final BlockDevInfo blockDevInfo1;
/** BlockDevInfo object of the second block device. */
private final BlockDevInfo blockDevInfo2;
/**
* Whether the block device is used by heartbeat via Filesystem
* service.
*/
private boolean isUsedByHeartbeat;
/** Cache for getInfoPanel method. */
private JComponent infoPanel = null;
/** Whether the meta-data has to be created or not. */
private boolean haveToCreateMD = false;
/**
* Prepares a new <code>DrbdResourceInfo</code> object.
*
* @param name
* name that will be shown in the tree
* @param drbdDev
* drbd device
* @param blockDevInfo1
* first block device info object belonging to this drbd device
* @param blockDevInfo2
* second block device info object belonging to this drbd device
*/
public DrbdResourceInfo(final String name,
final String drbdDev,
final BlockDevInfo blockDevInfo1,
final BlockDevInfo blockDevInfo2) {
super(name);
setResource(new DrbdResource(name, null));
initApplyButton();
setResource(new DrbdResource(name, drbdDev));
// TODO: drbdresource
getResource().setValue(DRBD_RES_PARAM_DEV, drbdDev);
this.blockDevInfo1 = blockDevInfo1;
this.blockDevInfo2 = blockDevInfo2;
initApplyButton();
}
/**
* Returns device name, like /dev/drbd0.
*/
public final String getDevice() {
return getDrbdResource().getDevice();
}
/**
* Returns menu icon for drbd resource.
*/
public final ImageIcon getMenuIcon() {
return null;
}
/**
* Returns cluster object to resource belongs.
*/
public final Cluster getCluster() {
return cluster;
}
/**
* Returns other block device in the drbd cluster.
*/
public final BlockDevInfo getOtherBlockDevInfo(final BlockDevInfo bdi) {
if (bdi.equals(blockDevInfo1)) {
return blockDevInfo2;
} else if (bdi.equals(blockDevInfo2)) {
return blockDevInfo1;
} else {
return null;
}
}
/**
* Returns first block dev info.
*/
public final BlockDevInfo getFirstBlockDevInfo() {
return blockDevInfo1;
}
/**
* Returns second block dev info.
*/
public final BlockDevInfo getSecondBlockDevInfo() {
return blockDevInfo2;
}
/**
* Returns true if this is first block dev info.
*/
public final boolean isFirstBlockDevInfo(final BlockDevInfo bdi) {
return blockDevInfo1 == bdi;
}
/**
* Creates drbd config for sections and returns it. Removes 'drbd: '
* from the 'after' parameter.
* TODO: move this out of gui
*/
private String drbdSectionsConfig()
throws Exceptions.DrbdConfigException {
final StringBuffer config = new StringBuffer("");
final String[] sections = drbdXML.getSections();
for (String section : sections) {
if ("resource".equals(section) || "global".equals(section)) {
// TODO: Tools.getString
continue;
}
final String[] params = drbdXML.getSectionParams(section);
if (params.length != 0) {
final StringBuffer sectionConfig = new StringBuffer("");
for (String param : params) {
final String value = getResource().getValue(param);
if (value == null) {
Tools.debug(this, "section: " + section
+ ", param " + param + " ("
+ getName() + ") not defined");
throw new Exceptions.DrbdConfigException("param "
+ param + " (" + getName()
+ ") not defined");
}
if (!value.equals(drbdXML.getParamDefault(param))) {
if (isCheckBox(param)
&& value.equals(
Tools.getString("Boolean.True"))) {
/* boolean parameter */
sectionConfig.append("\t\t" + param + ";\n");
} else if (DRBD_RES_PARAM_AFTER.equals(param)) {
/* after parameter */
if (!value.equals(Tools.getString(
"ClusterBrowser.None"))) {
sectionConfig.append("\t\t");
sectionConfig.append(param);
sectionConfig.append('\t');
sectionConfig.append(
Tools.escapeConfig(value));
sectionConfig.append(";\n");
}
} else { /* name value parameter */
sectionConfig.append("\t\t");
sectionConfig.append(param);
sectionConfig.append('\t');
sectionConfig.append(Tools.escapeConfig(value));
sectionConfig.append(";\n");
}
}
}
if (sectionConfig.length() > 0) {
config.append("\t" + section + " {\n");
config.append(sectionConfig);
config.append("\t}\n\n");
}
}
}
return config.toString();
}
/**
* Creates and returns drbd config for resources.
*
* TODO: move this out of gui
*/
public final String drbdResourceConfig()
throws Exceptions.DrbdConfigException {
final StringBuffer config = new StringBuffer(50);
config.append("resource " + getName() + " {\n");
/* protocol... */
final String[] params = drbdXML.getSectionParams("resource");
for (String param : params) {
config.append('\t');
config.append(param);
config.append('\t');
config.append(getResource().getValue(param));
config.append(";\n");
}
if (params.length != 0) {
config.append('\n');
}
/* section config */
try {
config.append(drbdSectionsConfig());
} catch (Exceptions.DrbdConfigException dce) {
throw dce;
}
// startup
// disk
// syncer
// net
config.append('\n');
config.append(blockDevInfo1.drbdNodeConfig(getName(), getDevice()));
config.append('\n');
config.append(blockDevInfo2.drbdNodeConfig(getName(), getDevice()));
config.append("}\n");
return config.toString();
}
/**
* Clears info panel cache.
*/
public final boolean selectAutomaticallyInTreeMenu() {
return infoPanel == null;
}
/**
* Returns sync progress in percent.
*/
public final String getSyncedProgress() {
return blockDevInfo1.getBlockDevice().getSyncedProgress();
}
/**
* Returns whether the cluster is syncing.
*/
public final boolean isSyncing() {
return blockDevInfo1.getBlockDevice().isSyncing();
}
/**
* Connect block device from the specified host.
*/
public final void connect(final Host host) {
if (blockDevInfo1.getHost() == host
&& !blockDevInfo1.getBlockDevice().isConnectedOrWF()) {
blockDevInfo1.connect();
} else if (blockDevInfo2.getHost() == host
&& !blockDevInfo2.getBlockDevice().isConnectedOrWF()) {
blockDevInfo2.connect();
}
}
/**
* Returns whether the resources is connected, meaning both devices are
* connected.
*/
public final boolean isConnected() {
return blockDevInfo1.getBlockDevice().isConnected()
&& blockDevInfo2.getBlockDevice().isConnected();
}
/**
* Returns whether any of the sides in the drbd resource are in
* paused-sync state.
*/
public final boolean isPausedSync() {
return blockDevInfo1.getBlockDevice().isPausedSync()
|| blockDevInfo2.getBlockDevice().isPausedSync();
}
/**
* Returns whether any of the sides in the drbd resource are in
* split-brain.
*/
public final boolean isSplitBrain() {
return blockDevInfo1.getBlockDevice().isSplitBrain()
|| blockDevInfo2.getBlockDevice().isSplitBrain();
}
/**
* Returns drbd graphical view.
*/
public final JPanel getGraphicalView() {
return drbdGraph.getGraphPanel();
}
/**
* Returns the DrbdInfo object (for all drbds).
*/
public final DrbdInfo getDrbdInfo() {
return drbdGraph.getDrbdInfo();
}
/**
* Returns all parameters.
*/
public final String[] getParametersFromXML() {
return drbdXML.getParameters();
}
/**
* Checks the new value of the parameter if it is conforms to its type
* and other constrains.
*/
protected final boolean checkParam(final String param,
final String newValue) {
return drbdXML.checkParam(param, newValue);
}
/**
* Returns the default value for the drbd parameter.
*/
protected final String getParamDefault(final String param) {
return drbdXML.getParamDefault(param);
}
/**
* Returns the possible values for the pulldown menus, if applicable.
*/
protected final Object[] getParamPossibleChoices(final String param) {
return drbdXML.getPossibleChoices(param);
}
/**
* Returns the short description of the drbd parameter that is used as
* a label.
*/
protected final String getParamShortDesc(final String param) {
return drbdXML.getParamShortDesc(param);
}
/**
* Returns a long description of the parameter that is used for tool
* tip.
*/
protected final String getParamLongDesc(final String param) {
return drbdXML.getParamLongDesc(param);
}
/**
* Returns section to which this drbd parameter belongs.
*/
protected final String getSection(final String param) {
return drbdXML.getSection(param);
}
/**
* Returns whether this drbd parameter is required parameter.
*/
protected final boolean isRequired(final String param) {
return drbdXML.isRequired(param);
}
/**
* Returns whether this drbd parameter is of integer type.
*/
protected final boolean isInteger(final String param) {
return drbdXML.isInteger(param);
}
/**
* Returns whether this drbd parameter is of time type.
*/
protected final boolean isTimeType(final String param) {
/* not required */
return false;
}
/**
* Returns whether this parameter has a unit prefix.
*/
protected final boolean hasUnitPrefix(final String param) {
return drbdXML.hasUnitPrefix(param);
}
/**
* Returns the long unit name.
*/
protected final String getUnitLong(final String param) {
return drbdXML.getUnitLong(param);
}
/**
* Returns the default unit for the parameter.
*/
protected final String getDefaultUnit(final String param) {
return drbdXML.getDefaultUnit(param);
}
/**
* Returns whether the parameter is of the boolean type and needs the
* checkbox.
*/
protected final boolean isCheckBox(final String param) {
final String type = drbdXML.getParamType(param);
if (type == null) {
return false;
}
if (DRBD_RES_BOOL_TYPE_NAME.equals(type)) {
return true;
}
return false;
}
/**
* Returns the type of the parameter (like boolean).
*/
protected final String getParamType(final String param) {
return drbdXML.getParamType(param);
}
/**
* Returns the widget that is used to edit this parameter.
*/
protected final GuiComboBox getParamComboBox(final String param,
final String prefix,
final int width) {
GuiComboBox paramCb;
final Object[] possibleChoices = getParamPossibleChoices(param);
getResource().setPossibleChoices(param, possibleChoices);
if (DRBD_RES_PARAM_NAME.equals(param)) {
String resName;
if (getResource().getValue(DRBD_RES_PARAM_NAME) == null) {
resName =
getResource().getDefaultValue(DRBD_RES_PARAM_NAME);
} else {
resName = getResource().getName();
}
paramCb = new GuiComboBox(resName, null, null, null, width);
paramCb.setEnabled(!getDrbdResource().isCommited());
paramComboBoxAdd(param, prefix, paramCb);
} else if (DRBD_RES_PARAM_DEV.equals(param)) {
final List<String> drbdDevices = new ArrayList<String>();
if (getResource().getValue(DRBD_RES_PARAM_DEV) == null) {
final String defaultItem =
getDrbdResource().getDefaultValue(DRBD_RES_PARAM_DEV);
drbdDevices.add(defaultItem);
int i = 0;
int index = 0;
while (i < 11) {
final String drbdDevStr = "/dev/drbd"
+ Integer.toString(index);
if (!drbdDevHash.containsKey(drbdDevStr)) {
drbdDevices.add(drbdDevStr);
i++;
}
index++;
}
paramCb = new GuiComboBox(defaultItem,
drbdDevices.toArray(
new String[drbdDevices.size()]),
null,
null,
width);
paramCb.setEditable(true);
} else {
final String defaultItem = getDevice();
String regexp = null;
if (isInteger(param)) {
regexp = "^-?\\d*$";
}
paramCb = new GuiComboBox(
defaultItem,
getResource().getPossibleChoices(param),
null,
regexp,
width);
}
paramCb.setEnabled(!getDrbdResource().isCommited());
paramComboBoxAdd(param, prefix, paramCb);
} else if (DRBD_RES_PARAM_AFTER.equals(param)) {
final List<Object> l = new ArrayList<Object>();
String defaultItem =
getResource().getValue(DRBD_RES_PARAM_AFTER);
final StringInfo di = new StringInfo(
Tools.getString("ClusterBrowser.None"),
"-1");
l.add(di);
if (defaultItem == null) {
defaultItem = Tools.getString("ClusterBrowser.None");
}
for (final String drbdRes : drbdResHash.keySet()) {
final DrbdResourceInfo r = drbdResHash.get(drbdRes);
DrbdResourceInfo odri = r;
boolean cyclicRef = false;
while ((odri = drbdResHash.get(
odri.getResource().getValue("after"))) != null) {
if (odri == this) {
cyclicRef = true;
// cyclic reference
//Tools.appError("cyclic reference: "
// + odri.toString());
}
}
if (r != this && !cyclicRef) {
l.add(r);
}
}
paramCb = new GuiComboBox(defaultItem,
l.toArray(new Object[l.size()]),
null,
null,
width);
paramComboBoxAdd(param, prefix, paramCb);
} else if (hasUnitPrefix(param)) {
String selectedValue = getResource().getValue(param);
if (selectedValue == null) {
selectedValue = getParamDefault(param);
}
String unit = getUnitLong(param);
if (unit == null) {
unit = "";
}
final int index = unit.indexOf('/');
String unitPart = "";
if (index > -1) {
unitPart = unit.substring(index);
}
final Unit[] units = {
new Unit("", "", "Byte", "Bytes"),
new Unit("K",
"k",
"KiByte" + unitPart,
"KiBytes" + unitPart),
new Unit("M",
"m",
"MiByte" + unitPart,
"MiBytes" + unitPart),
new Unit("G",
"g",
"GiByte" + unitPart,
"GiBytes" + unitPart),
new Unit("S",
"s",
"Sector" + unitPart,
"Sectors" + unitPart)
};
String regexp = null;
if (isInteger(param)) {
regexp = "^-?\\d*$";
}
paramCb = new GuiComboBox(selectedValue,
getPossibleChoices(param),
units,
GuiComboBox.Type.TEXTFIELDWITHUNIT,
regexp,
width);
paramComboBoxAdd(param, prefix, paramCb);
} else {
paramCb = super.getParamComboBox(param, prefix, width);
if (possibleChoices != null) {
paramCb.setEditable(false);
}
}
return paramCb;
}
/**
* Returns the DrbdResource object of this drbd resource.
*/
private DrbdResource getDrbdResource() {
return (DrbdResource) getResource();
}
/**
* Applies changes that user made to the drbd resource fields.
*/
public final void apply() {
final String[] params = getParametersFromXML();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
applyButton.setEnabled(false);
}
});
drbdResHash.remove(getName());
drbdDevHash.remove(getDevice());
storeComboBoxValues(params);
final String name = getResource().getValue(DRBD_RES_PARAM_NAME);
final String drbdDevStr =
getResource().getValue(DRBD_RES_PARAM_DEV);
getDrbdResource().setName(name);
setName(name);
getDrbdResource().setDevice(drbdDevStr);
drbdResHash.put(name, this);
drbdDevHash.put(drbdDevStr, this);
drbdGraph.repaint();
}
/**
* Returns panel with form to configure a drbd resource.
*/
public final JComponent getInfoPanel() {
drbdGraph.pickInfo(this);
if (infoPanel != null) {
return infoPanel;
}
final JPanel mainPanel = new JPanel();
mainPanel.setBackground(PANEL_BACKGROUND);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
final JPanel buttonPanel = new JPanel(new BorderLayout());
buttonPanel.setBackground(STATUS_BACKGROUND);
buttonPanel.setMinimumSize(new Dimension(0, 50));
buttonPanel.setPreferredSize(new Dimension(0, 50));
buttonPanel.setMaximumSize(new Dimension(Short.MAX_VALUE, 50));
final JPanel optionsPanel = new JPanel();
optionsPanel.setBackground(PANEL_BACKGROUND);
optionsPanel.setLayout(new BoxLayout(optionsPanel,
BoxLayout.Y_AXIS));
optionsPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
final JPanel extraOptionsPanel = new JPanel();
extraOptionsPanel.setBackground(EXTRA_PANEL_BACKGROUND);
extraOptionsPanel.setLayout(new BoxLayout(extraOptionsPanel,
BoxLayout.Y_AXIS));
extraOptionsPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
mainPanel.add(buttonPanel);
/* expert mode */
buttonPanel.add(Tools.expertModeButton(extraOptionsPanel),
BorderLayout.WEST);
/* Actions */
final JMenuBar mb = new JMenuBar();
mb.setBackground(PANEL_BACKGROUND);
final JMenu serviceCombo = getActionsMenu();
updateMenus(null);
mb.add(serviceCombo);
buttonPanel.add(mb, BorderLayout.EAST);
/* resource name */
getResource().setValue(DRBD_RES_PARAM_NAME,
getDrbdResource().getName());
getResource().setValue(DRBD_RES_PARAM_DEV,
getDevice());
final String[] params = getParametersFromXML();
addParams(optionsPanel,
extraOptionsPanel,
params,
Tools.getDefaultInt("ClusterBrowser.DrbdResLabelWidth"),
Tools.getDefaultInt("ClusterBrowser.DrbdResFieldWidth")
);
applyButton.addActionListener(
new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Thread thread = new Thread(new Runnable() {
public void run() {
hbStatusLock();
apply();
try {
getDrbdInfo().createDrbdConfig();
for (final Host h : cluster.getHostsArray()) {
DRBD.adjust(h, "all");
}
} catch (Exceptions.DrbdConfigException dce) {
hbStatusUnlock();
Tools.appError("config failed");
}
hbStatusUnlock();
}
});
thread.start();
}
}
);
addApplyButton(mainPanel);
applyButton.setEnabled(checkResourceFields(null, params));
mainPanel.add(optionsPanel);
mainPanel.add(extraOptionsPanel);
infoPanel = new JPanel();
infoPanel.setBackground(PANEL_BACKGROUND);
infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));
infoPanel.add(buttonPanel);
infoPanel.add(new JScrollPane(mainPanel));
infoPanel.add(Box.createVerticalGlue());
return infoPanel;
}
/**
* Removes this drbd resource with confirmation dialog.
*/
public final void removeMyself() {
String desc = Tools.getString(
"ClusterBrowser.confirmRemoveDrbdResource.Description");
desc = desc.replaceAll("@RESOURCE@", getName());
if (Tools.confirmDialog(
Tools.getString(
"ClusterBrowser.confirmRemoveDrbdResource.Title"),
desc,
Tools.getString(
"ClusterBrowser.confirmRemoveDrbdResource.Yes"),
Tools.getString(
"ClusterBrowser.confirmRemoveDrbdResource.No"))) {
removeMyselfNoConfirm();
}
}
/**
* removes this object from jtree and from list of drbd resource
* infos without confirmation dialog.
*/
public final void removeMyselfNoConfirm() {
drbdGraph.removeDrbdResource(this);
final Host[] hosts = cluster.getHostsArray();
for (Host host : hosts) {
DRBD.down(host, getName());
}
super.removeMyself();
final DrbdResourceInfo dri = drbdResHash.get(getName());
drbdResHash.remove(getName());
dri.setName(null);
reload(servicesNode);
//reload(drbdNode);
//getDrbdInfo().selectMyself();
drbdDevHash.remove(getDevice());
blockDevInfo1.removeFromDrbd();
blockDevInfo2.removeFromDrbd();
blockDevInfo1.removeMyself();
blockDevInfo2.removeMyself();
updateCommonBlockDevices();
try {
drbdGraph.getDrbdInfo().createDrbdConfig();
} catch (Exceptions.DrbdConfigException dce) {
Tools.appError("config failed");
}
drbdGraph.getDrbdInfo().setSelectedNode(null);
drbdGraph.getDrbdInfo().selectMyself();
//SwingUtilities.invokeLater(new Runnable() { public void run() {
drbdGraph.updatePopupMenus();
//} });
resetFilesystems();
infoPanel = null;
reload(drbdNode);
}
/**
* Returns string of the drbd resource.
*/
public final String toString() {
String name = getName();
if (name == null) {
name = Tools.getString("ClusterBrowser.DrbdResUnconfigured");
}
return "drbd: " + name;
}
/**
* Returns whether two drbd resources are equal.
*/
public final boolean equals(final Object value) {
if (value == null) {
return false;
}
if (Tools.isStringClass(value)) {
return getDrbdResource().getValue(DRBD_RES_PARAM_DEV).equals(
value.toString());
} else {
if (toString() == null) {
return false;
}
return toString().equals(value.toString());
}
}
//public int hashCode() {
// return toString().hashCode();
//}
/**
* Returns the device name that is used as the string value of the drbd
* resource in Filesystem hb service.
*/
public final String getStringValue() {
return getDevice();
}
/**
* Adds drbddisk service in the heartbeat and graph.
*
* @param fi
* File system before which this drbd info should be
* started
*/
public final void addDrbdDisk(final FilesystemInfo fi) {
final Point2D p = null;
final DrbddiskInfo di = (DrbddiskInfo) heartbeatGraph.getServicesInfo().addServicePanel(heartbeatXML.getHbDrbddisk(), p, true, null);
//di.setResourceName(getName());
di.setGroupInfo(fi.getGroupInfo());
addToHeartbeatIdList(di);
fi.setDrbddiskInfo(di);
di.getInfoPanel();
di.paramComboBoxGet("1", null).setValueAndWait(getName());
di.apply();
heartbeatGraph.addColocation(di, fi);
}
/**
* Remove drbddisk heartbeat service.
*/
public final void removeDrbdDisk(final FilesystemInfo fi) {
final DrbddiskInfo drbddiskInfo = fi.getDrbddiskInfo();
if (drbddiskInfo != null) {
drbddiskInfo.removeMyselfNoConfirm();
}
}
/**
* Sets that this drbd resource is used by hb.
*/
public final void setUsedByHeartbeat(final boolean isUsedByHeartbeat) {
this.isUsedByHeartbeat = isUsedByHeartbeat;
}
/**
* Returns whether this drbd resource is used by heartbeat.
*/
public final boolean isUsedByHeartbeat() {
return isUsedByHeartbeat;
}
/**
* Returns common file systems. This is call from a dialog and it calls
* the normal getCommonFileSystems function. TODO: It's a hack.
*/
public final StringInfo[] getCommonFileSystems2(
final String defaultValue) {
return getCommonFileSystems(defaultValue);
}
/**
* Returns both hosts of the drbd connection, sorted alphabeticaly.
*/
public final Host[] getHosts() {
final Host h1 = blockDevInfo1.getHost();
final Host h2 = blockDevInfo2.getHost();
if (h1.getName().compareToIgnoreCase(h2.getName()) < 0) {
return new Host[]{h1, h2};
} else {
return new Host[]{h2, h1};
}
}
/**
* Starts resolve split brain dialog.
*/
public final void resolveSplitBrain() {
final AddDrbdSplitBrainDialog adrd =
new AddDrbdSplitBrainDialog(this);
adrd.showDialogs();
}
/**
* Returns whether the specified host has this drbd resource.
*/
public final boolean resourceInHost(final Host host) {
if (blockDevInfo1.getHost() == host
|| blockDevInfo2.getHost() == host) {
return true;
}
return false;
}
/**
* Returns the list of items for the popup menu for drbd resource.
*/
public final List<UpdatableItem> createPopup() {
final List<UpdatableItem> items = new ArrayList<UpdatableItem>();
final MyMenuItem removeResMenu = new MyMenuItem(
Tools.getString("ClusterBrowser.Drbd.RemoveEdge"),
REMOVE_ICON,
Tools.getString(
"ClusterBrowser.Drbd.RemoveEdge.ToolTip")
) {
private static final long serialVersionUID = 1L;
public void action() {
// this drbdResourceInfo remove myself and this calls
// removeDrbdResource in this class, that removes the edge in
// the graph.
removeMyself();
}
public boolean enablePredicate() {
return !isUsedByHeartbeat();
}
};
registerMenuItem(removeResMenu);
items.add(removeResMenu);
final DrbdResourceInfo thisClass = this;
final MyMenuItem connectMenu = new MyMenuItem(
Tools.getString("ClusterBrowser.Drbd.ResourceConnect"),
null,
Tools.getString(
"ClusterBrowser.Drbd.ResourceConnect.ToolTip"),
Tools.getString(
"ClusterBrowser.Drbd.ResourceDisconnect"),
null,
Tools.getString(
"ClusterBrowser.Drbd.ResourceDisconnect.ToolTip")
) {
private static final long serialVersionUID = 1L;
public boolean predicate() {
return !isConnected();
}
public boolean enablePredicate() {
return !isSyncing();
}
public void action() {
BlockDevInfo sourceBDI = drbdGraph.getSource(thisClass);
BlockDevInfo destBDI = drbdGraph.getDest(thisClass);
if (this.getText().equals(Tools.getString(
"ClusterBrowser.Drbd.ResourceConnect"))) {
if (!destBDI.getBlockDevice().isConnectedOrWF()) {
destBDI.connect();
}
if (!sourceBDI.getBlockDevice().isConnectedOrWF()) {
sourceBDI.connect();
}
} else {
destBDI.disconnect();
sourceBDI.disconnect();
}
}
};
registerMenuItem(connectMenu);
items.add(connectMenu);
final MyMenuItem resumeSync = new MyMenuItem(
Tools.getString("ClusterBrowser.Drbd.ResourceResumeSync"),
null,
Tools.getString(
"ClusterBrowser.Drbd.ResourceResumeSync.ToolTip"),
Tools.getString("ClusterBrowser.Drbd.ResourcePauseSync"),
null,
Tools.getString(
"ClusterBrowser.Drbd.ResourcePauseSync.ToolTip")
) {
private static final long serialVersionUID = 1L;
public boolean predicate() {
return isPausedSync();
}
public boolean enablePredicate() {
return isSyncing();
}
public void action() {
BlockDevInfo sourceBDI = drbdGraph.getSource(thisClass);
BlockDevInfo destBDI = drbdGraph.getDest(thisClass);
if (this.getText().equals(Tools.getString(
"ClusterBrowser.Drbd.ResourceResumeSync"))) {
if (destBDI.getBlockDevice().isPausedSync()) {
destBDI.resumeSync();
}
if (sourceBDI.getBlockDevice().isPausedSync()) {
sourceBDI.resumeSync();
}
} else {
sourceBDI.pauseSync();
destBDI.pauseSync();
}
}
};
registerMenuItem(resumeSync);
items.add(resumeSync);
/* resolve split-brain */
final MyMenuItem splitBrainMenu = new MyMenuItem(
Tools.getString("ClusterBrowser.Drbd.ResolveSplitBrain"),
null,
Tools.getString(
"ClusterBrowser.Drbd.ResolveSplitBrain.ToolTip")
) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
return isSplitBrain();
}
public void action() {
resolveSplitBrain();
}
};
registerMenuItem(splitBrainMenu);
items.add(splitBrainMenu);
/* view log */
final MyMenuItem viewLogMenu = new MyMenuItem(
Tools.getString("ClusterBrowser.Drbd.ViewLogs"),
null,
null) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
return true;
}
public void action() {
final String device = getDevice();
final Thread thread = new Thread(
new Runnable() {
public void run() {
ClusterDrbdLogs l =
new ClusterDrbdLogs(getCluster(),
device);
l.showDialog();
}
});
thread.start();
}
};
registerMenuItem(viewLogMenu);
items.add(viewLogMenu);
return items;
}
/**
* Sets whether the meta-data have to be created, meaning there are no
* existing meta-data for this resource on both nodes.
*/
public final void setHaveToCreateMD(final boolean haveToCreateMD) {
this.haveToCreateMD = haveToCreateMD;
}
/**
* Returns whether the md has to be created or not.
*/
public final boolean isHaveToCreateMD() {
return haveToCreateMD;
}
/**
* Returns meta-disk device for the specified host.
*/
public final String getMetaDiskForHost(final Host host) {
return drbdXML.getMetaDisk(host.getName(), getName());
}
/**
* Returns tool tip when mouse is over the resource edge.
*/
public String getToolTipForGraph() {
return getName();
}
}
/**
* This class holds the information about heartbeat service from the ocfs,
* to show it to the user.
*/
class AvailableServiceInfo extends HbCategoryInfo {
/** Info about the service. */
private final HeartbeatService hbService;
/**
* Prepares a new <code>AvailableServiceInfo</code> object.
*/
public AvailableServiceInfo(final HeartbeatService hbService) {
super(hbService.getName());
this.hbService = hbService;
}
/**
* Returns heartbeat service class.
*/
public HeartbeatService getHeartbeatService() {
return hbService;
}
/**
* Returns icon for this menu category.
*/
public ImageIcon getMenuIcon() {
return AVAIL_SERVICES_ICON;
}
/**
* Returns the info about the service.
*/
public String getInfo() {
final StringBuffer s = new StringBuffer(30);
s.append("<h2>");
s.append(getName());
s.append(" (");
s.append(heartbeatXML.getVersion(hbService));
s.append(")</h2><h3>");
s.append(heartbeatXML.getShortDesc(hbService));
s.append("</h3>");
s.append(heartbeatXML.getLongDesc(hbService));
final String[] params = heartbeatXML.getParameters(hbService);
for (String param : params) {
s.append(heartbeatXML.getParamLongDesc(hbService, param));
s.append("<br>");
}
return s.toString();
}
}
/**
* This class holds info data for a block device that is common
* in all hosts in the cluster and can be chosen in the scrolling list in
* the filesystem service.
*/
class CommonBlockDevInfo extends HbCategoryInfo
implements CommonDeviceInterface {
/** block devices of this common block device on all nodes. */
private final BlockDevice[] blockDevices;
/**
* Prepares a new <code>CommonBlockDevInfo</code> object.
*/
public CommonBlockDevInfo(final String name,
final BlockDevice[] blockDevices) {
super(name);
setResource(new CommonBlockDevice(name));
this.blockDevices = blockDevices;
}
/**
* Returns icon for common block devices menu category.
*/
public ImageIcon getMenuIcon() {
return COMMON_BD_ICON;
}
/**
* Returns device name of this block device.
*/
public String getDevice() {
return getCommonBlockDevice().getDevice();
}
/**
* Returns info for this block device.
*/
public String getInfo() {
return "Device : " + getCommonBlockDevice().getName() + "\n";
}
/**
* Returns string representation of the block devices, used in the pull
* down menu.
*/
public String toString() {
String name = getName();
if (name == null) {
name = Tools.getString(
"ClusterBrowser.CommonBlockDevUnconfigured");
}
return name;
}
/**
* Sets this block device on all nodes ass used by heartbeat.
*/
public void setUsedByHeartbeat(final boolean isUsedByHeartbeat) {
for (BlockDevice bd : blockDevices) {
bd.setUsedByHeartbeat(isUsedByHeartbeat);
}
}
/**
* Returns if all of the block devices are used by heartbeat.
* TODO: or any is used by hb?
*/
public boolean isUsedByHeartbeat() {
boolean is = true;
for (int i = 0; i < blockDevices.length; i++) {
is = is && blockDevices[i].isUsedByHeartbeat();
}
return is;
}
/**
* Retruns resource object of this block device.
*/
public CommonBlockDevice getCommonBlockDevice() {
return (CommonBlockDevice) getResource();
}
}
/**
* This class holds info about IPaddr/IPaddr2 heartbeat service. It adds a
* better ip entering capabilities.
*/
class IPaddrInfo extends ServiceInfo {
/**
* Creates new IPaddrInfo object.
*/
public IPaddrInfo(final String name, final HeartbeatService hbService) {
super(name, hbService);
}
/**
* Creates new IPaddrInfo object.
*/
public IPaddrInfo(final String name,
final HeartbeatService hbService,
final String hbId,
final Map<String, String> resourceNode) {
super(name, hbService, hbId, resourceNode);
}
/**
* Adds if field.
*/
protected void addIdField(final JPanel panel,
final int leftWidth,
final int rightWidth) {
super.addIdField(panel, leftWidth, rightWidth);
}
/**
* Returns whether all the parameters are correct. If param is null,
* all paremeters will be checked, otherwise only the param, but other
* parameters will be checked only in the cache. This is good if only
* one value is changed and we don't want to check everything.
*/
public boolean checkResourceFieldsCorrect(final String param,
final String[] params) {
boolean ret = super.checkResourceFieldsCorrect(param, params);
final GuiComboBox cb;
if (getHeartbeatService().isHeartbeatClass()) {
cb = paramComboBoxGet("1", null);
} else if (getHeartbeatService().isOCFClass()) {
cb = paramComboBoxGet("ip", null);
} else {
return true;
}
if (cb == null) {
return false;
}
cb.setEditable(true);
cb.selectSubnet();
if (ret) {
final String ip = cb.getStringValue();
if (!Tools.checkIp(ip)) {
ret = false;
}
}
return ret;
}
/**
* Returns combo box for parameter.
*/
protected GuiComboBox getParamComboBox(final String param,
final String prefix,
final int width) {
GuiComboBox paramCb;
if ("ip".equals(param)) {
/* get networks */
final String ip = getResource().getValue("ip");
Info defaultValue;
if (ip == null) {
defaultValue = new StringInfo(
Tools.getString("ClusterBrowser.SelectNetInterface"),
null);
} else {
defaultValue = new StringInfo(ip, ip);
}
final Info[] networks =
enumToInfoArray(defaultValue,
getName(),
networksNode.children());
final String regexp = "^[\\d.*]*|Select\\.\\.\\.$";
paramCb = new GuiComboBox(ip,
networks,
GuiComboBox.Type.COMBOBOX,
regexp,
width);
paramCb.setAlwaysEditable(true);
paramComboBoxAdd(param, prefix, paramCb);
} else {
paramCb = super.getParamComboBox(param, prefix, width);
}
return paramCb;
}
/**
* Returns string representation of the ip address.
* In the form of 'ip (interface)'
*/
public String toString() {
final String id = getService().getId();
if (id == null) {
return super.toString(); // this is for 'new IPaddrInfo'
}
final StringBuffer s = new StringBuffer(getName());
String inside = "";
if (!id.matches("^\\d+$")) {
inside = id + " / ";
}
String ip = getResource().getValue("ip");
if (ip == null) {
ip = Tools.getString("ClusterBrowser.Ip.Unconfigured");
}
s.append(" (" + inside + ip + ")");
return s.toString();
}
}
/**
* This class holds info about Filesystem service. It is treated in special
* way, so that it can use block device information and drbd devices. If
* drbd device is selected, the drbddisk service will be added too.
*/
class FilesystemInfo extends ServiceInfo {
/** drbddisk service object. */
private DrbddiskInfo drbddiskInfo = null;
/**
* Creates the FilesystemInfo object.
*/
public FilesystemInfo(final String name,
final HeartbeatService hbService) {
super(name, hbService);
}
/**
* Creates the FilesystemInfo object.
*/
public FilesystemInfo(final String name,
final HeartbeatService hbService,
final String hbId,
final Map<String, String> resourceNode) {
super(name, hbService, hbId, resourceNode);
}
/**
* Sets DrbddiskInfo object for this Filesystem service if it uses drbd
* block device.
*/
public void setDrbddiskInfo(final DrbddiskInfo drbddiskInfo) {
this.drbddiskInfo = drbddiskInfo;
}
/**
* Returns DrbddiskInfo object that is associated with the drbd device
* or null if it is not a drbd device.
*/
public DrbddiskInfo getDrbddiskInfo() {
return drbddiskInfo;
}
/**
* Adds id field.
*/
protected void addIdField(final JPanel panel,
final int leftWidth,
final int rightWidth) {
super.addIdField(panel, leftWidth, rightWidth);
}
/**
* Returns whether all the parameters are correct. If param is null,
* all paremeters will be checked, otherwise only the param, but other
* parameters will be checked only in the cache. This is good if only
* one value is changed and we don't want to check everything.
*/
public boolean checkResourceFieldsCorrect(final String param,
final String[] params) {
final boolean ret = super.checkResourceFieldsCorrect(param, params);
if (!ret) {
return false;
}
final GuiComboBox cb = paramComboBoxGet(DRBD_RES_PARAM_DEV, null);
if (cb == null || cb.getValue() == null) {
return false;
}
return true;
}
/**
* Applies changes to the Filesystem service paramters.
*/
public void apply() {
final String dir = getComboBoxValue("directory");
for (Host host : getClusterHosts()) {
final String hostName = host.getName();
final String ret = Tools.execCommandProgressIndicator(
host,
"stat -c \"%F\" " + dir,
null,
true);
if (ret == null || !"directory\r\n".equals(ret)) {
String title =
Tools.getString("ClusterBrowser.CreateDir.Title");
String desc =
Tools.getString("ClusterBrowser.CreateDir.Description");
title = title.replaceAll("@DIR@", dir);
title = title.replaceAll("@HOST@", host.getName());
desc = desc.replaceAll("@DIR@", dir);
desc = desc.replaceAll("@HOST@", host.getName());
if (Tools.confirmDialog(
title,
desc,
Tools.getString("ClusterBrowser.CreateDir.Yes"),
Tools.getString("ClusterBrowser.CreateDir.No"))) {
Tools.execCommandProgressIndicator(host, "mkdir " + dir, null, true);
}
}
}
super.apply();
//TODO: escape dir
}
/**
* Returns editable element for the parameter.
*/
protected GuiComboBox getParamComboBox(final String param,
final String prefix,
final int width) {
GuiComboBox paramCb;
if (DRBD_RES_PARAM_DEV.equals(param)) {
final String selectedValue =
getResource().getValue(DRBD_RES_PARAM_DEV);
Info defaultValue = null;
if (selectedValue == null) {
defaultValue = new StringInfo(
Tools.getString("ClusterBrowser.SelectBlockDevice"),
null);
}
final Info[] commonBlockDevInfos =
getCommonBlockDevInfos(defaultValue,
getName());
paramCb = new GuiComboBox(selectedValue,
commonBlockDevInfos,
null,
null,
width);
paramComboBoxAdd(param, prefix, paramCb);
} else if ("fstype".equals(param)) {
final String defaultValue =
Tools.getString("ClusterBrowser.SelectFilesystem");
final String selectedValue = getResource().getValue("fstype");
paramCb = new GuiComboBox(selectedValue,
getCommonFileSystems(defaultValue),
null,
null,
width);
paramComboBoxAdd(param, prefix, paramCb);
paramCb.setEditable(false);
} else if ("directory".equals(param)) {
Object[] items = new Object[commonMountPoints.length + 1];
System.arraycopy(commonMountPoints,
0,
items,
1,
commonMountPoints.length);
items[0] = new StringInfo(
Tools.getString("ClusterBrowser.SelectMountPoint"),
null);
//for (int i = 0; i < commonMountPoints.length; i++) {
// items[i + 1] = commonMountPoints[i];
//}
getResource().setPossibleChoices(param, items);
final String selectedValue =
getResource().getValue("directory");
final String regexp = "^/.*$";
paramCb = new GuiComboBox(selectedValue,
items,
null,
regexp,
width);
paramComboBoxAdd(param, prefix, paramCb);
paramCb.setAlwaysEditable(true);
} else {
paramCb = super.getParamComboBox(param, prefix, width);
}
return paramCb;
}
/**
* Returns string representation of the filesystem service.
*/
public String toString() {
String id = getService().getId();
if (id == null) {
return super.toString(); // this is for 'new Filesystem'
}
final StringBuffer s = new StringBuffer(getName());
final DrbdResourceInfo dri =
drbdDevHash.get(getResource().getValue(DRBD_RES_PARAM_DEV));
if (dri == null) {
id = getResource().getValue(DRBD_RES_PARAM_DEV);
} else {
id = dri.getName();
s.delete(0, s.length());
s.append("Filesystem / Drbd");
}
if (id == null) {
id = Tools.getString(
"ClusterBrowser.ClusterBlockDevice.Unconfigured");
}
s.append(" (" + id + ")");
return s.toString();
}
/**
* Adds DrbddiskInfo before the filesysteminfo is added.
*/
public void addResourceBefore() {
final DrbdResourceInfo oldDri =
drbdDevHash.get(getResource().getValue(DRBD_RES_PARAM_DEV));
final DrbdResourceInfo newDri =
drbdDevHash.get(getComboBoxValue(DRBD_RES_PARAM_DEV));
if (newDri.equals(oldDri)) {
return;
}
//final DrbddiskInfo oddi = getDrbddiskInfo();
if (oldDri != null) {
oldDri.removeDrbdDisk(this);
oldDri.setUsedByHeartbeat(false);
setDrbddiskInfo(null);
}
if (newDri != null) {
newDri.setUsedByHeartbeat(true);
newDri.addDrbdDisk(this);
}
//if (oddi != null) {
// oddi.cleanupResource();
//}
}
}
/**
* DrbddiskInfo class is used for drbddisk heartbeat service that is
* treated in special way.
*/
class DrbddiskInfo extends ServiceInfo {
/**
* Creates new DrbddiskInfo object.
*/
public DrbddiskInfo(final String name,
final HeartbeatService hbService) {
super(name, hbService);
}
/**
* Creates new DrbddiskInfo object.
*/
public DrbddiskInfo(final String name,
final HeartbeatService hbService,
final String resourceName) {
super(name, hbService);
getResource().setValue("1", resourceName);
}
/**
* Creates new DrbddiskInfo object.
*/
public DrbddiskInfo(final String name,
final HeartbeatService hbService,
final String hbId,
final Map<String, String> resourceNode) {
super(name, hbService, hbId, resourceNode);
}
/**
* Returns string representation of the drbddisk service.
*/
public String toString() {
return getName() + " (" + getResource().getValue("1") + ")";
}
/**
* Returns resource name / parameter "1".
*/
public String getResourceName() {
return getResource().getValue("1");
}
/**
* Sets resource name / parameter "1".
*/
public void setResourceName(final String resourceName) {
getResource().setValue("1", resourceName);
}
/**
* Removes the drbddisk service.
*/
public void removeMyselfNoConfirm() {
super.removeMyselfNoConfirm();
final DrbdResourceInfo dri = drbdResHash.get(getResourceName());
if (dri != null) {
dri.setUsedByHeartbeat(false);
}
}
}
/**
* GroupInfo class holds data for heartbeat group, that is in some ways
* like normal service, but it can contain other services.
*/
class GroupInfo extends ServiceInfo {
// should extend EditableInfo: TODO
/**
* Creates new GroupInfo object.
*/
public GroupInfo(final HeartbeatService hbService) {
super(HB_GROUP_NAME, hbService);
}
/**
* Returns all group parameters. (empty)
*/
public String[] getParametersFromXML() {
return new String[]{};
}
/**
* Applies the changes to the group parameters.
*/
public void apply() {
final String[] params = getParametersFromXML();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
applyButton.setEnabled(false);
idField.setEnabled(false);
}
});
/* add myself to the hash with service name and id as
* keys */
removeFromServiceInfoHash(this);
final String oldHeartbeatId = getService().getHeartbeatId();
if (oldHeartbeatId != null) {
heartbeatIdToServiceInfo.remove(oldHeartbeatId);
heartbeatIdList.remove(oldHeartbeatId);
}
final String id = idField.getStringValue();
getService().setId(id);
addToHeartbeatIdList(this);
addNameToServiceInfoHash(this);
/*
MSG_ADD_GRP group
param_id1 param_name1 param_value1
param_id2 param_name2 param_value2
...
param_idn param_namen param_valuen
*/
final String heartbeatId = getService().getHeartbeatId();
if (getService().isNew()) {
final String[] parents = heartbeatGraph.getParents(this);
Heartbeat.setOrderAndColocation(getDCHost(),
heartbeatId,
parents);
}
setLocations(heartbeatId);
storeComboBoxValues(params);
reload(getNode());
heartbeatGraph.repaint();
}
/**
* Returns the list of services that can be added to the group.
*/
public List<HeartbeatService> getAddGroupServiceList(final String cl) {
return heartbeatXML.getServices(cl);
}
/**
* Adds service to this group. Adds it in the submenu in the menu tree
* and initializes it.
*
* @param newServiceInfo
* service info object of the new service
*/
public void addGroupServicePanel(final ServiceInfo newServiceInfo) {
newServiceInfo.getService().setHeartbeatClass(
newServiceInfo.getHeartbeatService().getHeartbeatClass());
newServiceInfo.setGroupInfo(this);
addToHeartbeatIdList(newServiceInfo);
final DefaultMutableTreeNode newServiceNode =
new DefaultMutableTreeNode(newServiceInfo);
newServiceInfo.setNode(newServiceNode);
getNode().add(newServiceNode);
reload(getNode()); // TODO: something will not work I guess
reload(newServiceNode);
}
/**
* Adds service to this group and creates new service info object.
*/
public void addGroupServicePanel(final HeartbeatService newHbService) {
ServiceInfo newServiceInfo;
final String name = newHbService.getName();
if (newHbService.isFilesystem()) {
newServiceInfo = new FilesystemInfo(name, newHbService);
} else if (newHbService.isDrbddisk()) {
newServiceInfo = new DrbddiskInfo(name, newHbService);
} else if (newHbService.isIPaddr()) {
newServiceInfo = new IPaddrInfo(name, newHbService);
} else if (newHbService.isGroup()) {
Tools.appError("No groups in group allowed");
return;
} else {
newServiceInfo = new ServiceInfo(name, newHbService);
}
addGroupServicePanel(newServiceInfo);
}
/**
* Returns on which node this group is running, meaning on which node
* all the services are running. Null if they running on different
* nodes or not at all.
*/
public String getRunningOnNode() {
String node = null;
final List<String> resources = heartbeatStatus.getGroupResources(
getService().getHeartbeatId());
if (resources != null) {
for (final String hbId : resources) {
final String n = heartbeatStatus.getRunningOnNode(hbId);
if (node == null) {
node = n;
} else if (!node.toLowerCase().equals(n.toLowerCase())) {
return null;
}
}
}
return node;
}
/**
* Returns items for the group popup.
*/
public List<UpdatableItem> createPopup() {
final List<UpdatableItem>items = super.createPopup();
/* add group service */
final MyMenu addGroupServiceMenuItem =new MyMenu(
Tools.getString("ClusterBrowser.Hb.AddGroupService")) {
private static final long serialVersionUID = 1L;
public void update() {
super.update();
removeAll();
for (final String cl : HB_CLASSES) {
final MyMenu classItem =
new MyMenu(HB_CLASS_MENU.get(cl));
DefaultListModel m = new DefaultListModel();
for (final HeartbeatService hbService
: getAddGroupServiceList(cl)) {
final MyMenuItem mmi =
new MyMenuItem(hbService.getMenuName()) {
private static final long serialVersionUID = 1L;
public void action() {
getPopup().setVisible(false);
addGroupServicePanel(hbService);
repaint();
}
};
m.addElement(mmi);
}
classItem.add(Tools.getScrollingMenu(classItem, m));
add(classItem);
}
}
};
items.add(1, (UpdatableItem) addGroupServiceMenuItem);
registerMenuItem((UpdatableItem) addGroupServiceMenuItem);
return items;
}
/**
* Removes this group from the heartbeat.
*/
public void removeMyself() {
getService().setRemoved(true);
String desc = Tools.getString(
"ClusterBrowser.confirmRemoveGroup.Description");
final StringBuffer services = new StringBuffer();
final Enumeration e = getNode().children();
while (e.hasMoreElements()) {
DefaultMutableTreeNode n =
(DefaultMutableTreeNode) e.nextElement();
final ServiceInfo child = (ServiceInfo) n.getUserObject();
services.append(child.toString());
if (e.hasMoreElements()) {
services.append(", ");
}
}
desc = desc.replaceAll("@GROUP@", "'" + toString() + "'");
desc = desc.replaceAll("@SERVICES@", services.toString());
if (Tools.confirmDialog(
Tools.getString("ClusterBrowser.confirmRemoveGroup.Title"),
desc,
Tools.getString("ClusterBrowser.confirmRemoveGroup.Yes"),
Tools.getString("ClusterBrowser.confirmRemoveGroup.No"))) {
removeMyselfNoConfirm();
}
getService().doneRemoving();
getService().setNew(false);
}
/**
* Remove all the services in the group and the group.
*/
public void removeMyselfNoConfirm() {
super.removeMyselfNoConfirm();
if (!getService().isNew()) {
for (String hbId : heartbeatStatus.getGroupResources(
getService().getHeartbeatId())) {
final ServiceInfo child =
heartbeatIdToServiceInfo.get(hbId);
child.removeMyselfNoConfirm();
}
}
}
/**
* Removes the group, but not the services.
*/
public void removeMyselfNoConfirmFromChild() {
super.removeMyselfNoConfirm();
}
/**
* Returns tool tip for the group vertex.
*/
public String getToolTipText() {
String hostName = getRunningOnNode();
if (hostName == null) {
hostName = "none";
}
final StringBuffer sb = new StringBuffer(220);
sb.append("<b>");
sb.append(toString());
sb.append(" running on node: ");
sb.append(hostName);
sb.append("</b>");
final Enumeration e = getNode().children();
while (e.hasMoreElements()) {
DefaultMutableTreeNode n =
(DefaultMutableTreeNode) e.nextElement();
final ServiceInfo child = (ServiceInfo) n.getUserObject();
sb.append('\n');
sb.append(child.getToolTipText());
}
return sb.toString();
}
}
/**
* This class holds info data for one hearteat service and allows to enter
* its arguments and execute operations on it.
*/
class ServiceInfo extends EditableInfo {
/** This is a map from host to the combobox with scores. */
private final Map<HostInfo, GuiComboBox> scoreComboBoxHash =
new HashMap<HostInfo, GuiComboBox>();
/** A map from host to stored score. */
private Map<HostInfo, HostScoreInfo> savedHostScoreInfos =
new HashMap<HostInfo, HostScoreInfo>();
/** A map from operation to the stored value. First key is
* operation name like "start" and second key is parameter like
* "timeout". */
private MultiKeyMap savedOperation = new MultiKeyMap();
/** A map from operation to its combo box. */
private MultiKeyMap operationsComboBoxHash = new MultiKeyMap();
/** idField text field. */
protected GuiComboBox idField = null;
/** Cache for the info panel. */
private JComponent infoPanel = null;
/** Group info object of the group this service is in or null, if it is
* not in any group. */
private GroupInfo groupInfo = null;
/** HeartbeatService object of the service, with name, ocf informations
* etc. */
private final HeartbeatService hbService;
/**
* Prepares a new <code>ServiceInfo</code> object and creates
* new service object.
*/
public ServiceInfo(final String name,
final HeartbeatService hbService) {
super(name);
this.hbService = hbService;
setResource(new Service(name));
/* init save button */
initApplyButton();
getService().setNew(true);
}
/**
* Prepares a new <code>ServiceInfo</code> object and creates
* new service object. It also initializes parameters along with
* heartbeat id with values from xml stored in resourceNode.
*/
public ServiceInfo(final String name,
final HeartbeatService hbService,
final String heartbeatId,
final Map<String, String> resourceNode) {
this(name, hbService);
getService().setHeartbeatId(heartbeatId);
setParameters(resourceNode);
}
/**
* Returns id of the service, which is heartbeatId.
*/
public String getId() {
return getService().getHeartbeatId();
}
/**
* Sets info panel of the service.
* TODO: is it used?
*/
public void setInfoPanel(final JPanel infoPanel) {
this.infoPanel = infoPanel;
}
/**
* Returns true if the node is active.
*/
public boolean isActiveNode(final String node) {
return heartbeatStatus.isActiveNode(node);
}
/**
* Returns whether all the parameters are correct. If param is null,
* all paremeters will be checked, otherwise only the param, but other
* parameters will be checked only in the cache. This is good if only
* one value is changed and we don't want to check everything.
*/
public boolean checkResourceFieldsCorrect(final String param,
final String[] params) {
if (!super.checkResourceFieldsCorrect(param, params)) {
return false;
}
if (idField == null) {
return false;
}
final String id = idField.getStringValue();
// TODO: check uniq id
if (id == null || id.equals("")) {
return false;
}
return true;
}
/**
* Returns whether the specified parameter or any of the parameters
* have changed. If param is null, only param will be checked,
* otherwise all parameters will be checked.
*/
protected boolean checkResourceFieldsChanged(final String param,
final String[] params) {
boolean ret;
if (super.checkResourceFieldsChanged(param, params)) {
ret = true;
} else {
final String id = idField.getStringValue();
final String heartbeatId = getService().getHeartbeatId();
if (HB_GROUP_NAME.equals(getName())) {
if (heartbeatId.equals("grp_" + id)
|| heartbeatId.equals(id)) {
ret = checkHostScoreFieldsChanged() || checkOperationFieldsChanged();
} else {
ret = true;
}
} else {
if (HB_GROUP_NAME.equals(getName())) {
if (heartbeatId.equals("grp_" + id)
|| heartbeatId.equals(id)) {
ret = checkHostScoreFieldsChanged() || checkOperationFieldsChanged();
} else {
ret = true;
}
} else {
if (heartbeatId.equals("res_" + getName() + "_" + id)
|| heartbeatId.equals(id)) {
ret = checkHostScoreFieldsChanged() || checkOperationFieldsChanged();
} else {
ret = true;
}
}
}
}
final String cl = getService().getHeartbeatClass();
if (cl != null && cl.equals(HB_HEARTBEAT_CLASS)) {
/* in old style resources don't show all the textfields */
boolean visible = false;
GuiComboBox cb = null;
for (int i = params.length - 1; i >= 0; i--) {
final GuiComboBox prevCb = paramComboBoxGet(params[i],
null);
if (prevCb == null) {
continue;
}
if (!visible && !prevCb.getStringValue().equals("")) {
visible = true;
}
if (cb != null && cb.isVisible() != visible) {
final boolean v = visible;
final GuiComboBox c = cb;
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
c.setVisible(v);
getLabel(c).setVisible(v);
}
});
}
cb = prevCb;
}
}
return ret;
}
/**
* Sets service parameters with values from resourceNode hash.
*/
public void setParameters(final Map<String, String> resourceNode) {
if (heartbeatXML == null) {
Tools.appError("heartbeatXML is null");
return;
}
final String[] params = heartbeatXML.getParameters(hbService);
if (params != null) {
for (String param : params) {
String value = resourceNode.get(param);
if (value == null) {
value = getParamDefault(param);
}
if (value == null) {
value = "";
}
if (!value.equals(getResource().getValue(param))) {
getResource().setValue(param, value);
if (infoPanel != null) {
final GuiComboBox cb = paramComboBoxGet(param,
null);
if (cb != null) {
cb.setValue(value);
}
}
}
}
}
/* scores */
for (Host host : getClusterHosts()) {
final HostInfo hi = host.getBrowser().getHostInfo();
String score = heartbeatStatus.getScore(
getService().getHeartbeatId(),
hi.getName());
if (score == null) {
score = "0";
}
final String scoreString = Tools.scoreToString(score);
if (!hostScoreInfoMap.get(scoreString).equals(savedHostScoreInfos.get(hi))) {
final GuiComboBox cb = scoreComboBoxHash.get(hi);
savedHostScoreInfos.put(hi, hostScoreInfoMap.get(scoreString));
if (cb != null) {
cb.setValue(scoreString);
}
}
}
/* operations */
for (final String op : HB_OPERATIONS) {
for (final String param : HB_OPERATION_PARAMS.get(op)) {
final GuiComboBox cb =
(GuiComboBox) operationsComboBoxHash.get(op, param);
String value = heartbeatStatus.getOperation(
getService().getHeartbeatId(),
op,
param);
if (value == null) {
value = "";
}
if (!value.equals(savedOperation.get(op, param))) {
savedOperation.put(op, param, value);
if (cb != null && value != null) {
cb.setValue(value);
}
}
}
}
getService().setAvailable();
}
/**
* Returns a name of the service with id in the parentheses.
* It adds prefix 'new' if id is null.
*/
public String toString() {
final StringBuffer s = new StringBuffer(getName());
final String string = getService().getId();
/* 'string' contains the last string if there are more dependent
* resources, although there is usually only one. */
if (string == null) {
s.insert(0, "new ");
} else {
if (!"".equals(string)) {
s.append(" (" + string + ")");
}
}
return s.toString();
}
/**
* Sets id in the service object.
*/
public void setId(final String id) {
getService().setId(id);
}
/**
* Returns node name of the host where this service is running.
*/
public String getRunningOnNode() {
return heartbeatStatus.getRunningOnNode(
getService().getHeartbeatId());
}
/**
* Returns whether service is started.
*/
public boolean isStarted() {
final String hbV = getDCHost().getHeartbeatVersion();
String targetRoleString = "target-role";
if (Tools.compareVersions(hbV, "2.1.4") <= 0) {
targetRoleString = "target_role";
}
final String targetRole =
heartbeatStatus.getParameter(getService().getHeartbeatId(),
targetRoleString);
if (targetRole != null && targetRole.equals("started")) {
return true;
}
return false;
}
/**
* Returns whether service is stopped.
*/
public boolean isStopped() {
final String hbV = getDCHost().getHeartbeatVersion();
String targetRoleString = "target-role";
if (Tools.compareVersions(hbV, "2.1.4") <= 0) {
targetRoleString = "target_role";
}
final String targetRole =
heartbeatStatus.getParameter(getService().getHeartbeatId(),
targetRoleString);
if (targetRole != null && targetRole.equals("stopped")) {
return true;
}
return false;
}
/**
* Returns whether service is managed.
* TODO: "default" value
*/
final public boolean isManaged() {
final String hbV = getDCHost().getHeartbeatVersion();
String isManagedString = "is-managed";
if (Tools.compareVersions(hbV, "2.1.4") <= 0) {
isManagedString = "is_managed";
}
final String isManaged =
heartbeatStatus.getParameter(getService().getHeartbeatId(),
isManagedString);
if (isManaged == null || isManaged.equals("true")) {
return true;
}
return false;
}
/**
* Returns whether the service is running.
*/
final public boolean isRunning() {
return !"".equals(getRunningOnNode());
}
/**
* Returns whether the resource has failed to start. It is detected in
* this way that the resource is started but is not running.
*/
final public boolean isFailed() {
return isStarted() && !isRunning();
}
/**
* Sets whether the service is managed.
*/
final public void setManaged(final boolean isManaged) {
setUpdated(true);
Heartbeat.setManaged(getDCHost(),
getService().getHeartbeatId(),
isManaged);
}
/**
* Returns color for the host vertex.
*/
public Color getHostColor() {
return cluster.getHostColor(getRunningOnNode());
}
/**
* Returns service icon in the menu. It can be started or stopped.
* TODO: broken icon, not managed icon.
*/
public ImageIcon getMenuIcon() {
if (isStopped()) {
return SERVICE_STOPPED_ICON;
} else if (isStarted()) {
return SERVICE_STARTED_ICON;
}
if (getRunningOnNode() == null) {
return SERVICE_STOPPED_ICON;
}
return SERVICE_STARTED_ICON;
}
/**
* Saves the host score infos.
* TODO: check it.
*/
public void setSavedHostScoreInfos(
final Map<HostInfo, HostScoreInfo> hsi) {
savedHostScoreInfos = hsi;
}
/**
* Gets saved host score infos.
*/
public Map<HostInfo, HostScoreInfo> getSavedHostScoreInfos() {
return savedHostScoreInfos;
}
/**
* Returns list of all host names in this cluster.
*/
public List<String> getHostNames() {
final List<String> hostNames = new ArrayList<String>();
final Enumeration e = clusterHostsNode.children();
while (e.hasMoreElements()) {
DefaultMutableTreeNode n =
(DefaultMutableTreeNode) e.nextElement();
final String hostName =
((HostInfo) n.getUserObject()).getName();
hostNames.add(hostName);
}
return hostNames;
}
/**
* TODO: wrong doku
* Converts enumeration to the info array, get objects from
* hash if they exist.
*/
protected Info[] enumToInfoArray(final Info defaultValue,
final String serviceName,
final Enumeration e) {
final List<Info> list = new ArrayList<Info>();
if (defaultValue != null) {
list.add(defaultValue);
}
while (e.hasMoreElements()) {
DefaultMutableTreeNode n =
(DefaultMutableTreeNode) e.nextElement();
final Info i =(Info) n.getUserObject();
final String name = i.getName();
final ServiceInfo si = getServiceInfoFromId(serviceName,
i.getName());
if (si == null && !name.equals(defaultValue)) {
list.add(i);
}
}
return list.toArray(new Info[list.size()]);
}
/**
* Stores score infos for host.
*/
private void storeHostScoreInfos() {
savedHostScoreInfos.clear();
for (Host host : getClusterHosts()) {
final HostInfo hi = host.getBrowser().getHostInfo();
final GuiComboBox cb = scoreComboBoxHash.get(hi);
final HostScoreInfo hsi = (HostScoreInfo) cb.getValue();
savedHostScoreInfos.put(hi, hsi);
}
// TODO: rename this
heartbeatGraph.setHomeNode(this, savedHostScoreInfos);
}
/**
* Returns thrue if an operation field changed.
*/
private boolean checkOperationFieldsChanged() {
for (final String op : HB_OPERATIONS) {
for (final String param : HB_OPERATION_PARAMS.get(op)) {
final GuiComboBox cb =
(GuiComboBox) operationsComboBoxHash.get(op, param);
if (cb == null) {
return false;
}
final String value = cb.getStringValue();
final String savedOp =
(String) savedOperation.get(op, param);
final String defaultValue =
hbService.getOperationDefault(op, param);
if (savedOp == null) {
if (value != null && !value.equals(defaultValue)) {
return true;
}
} else if (!savedOp.equals(value)) {
return true;
}
}
}
return false;
}
/**
* Returns true if some of the scores have changed.
*/
private boolean checkHostScoreFieldsChanged() {
for (Host host : getClusterHosts()) {
final HostInfo hi = host.getBrowser().getHostInfo();
final GuiComboBox cb = scoreComboBoxHash.get(hi);
final HostScoreInfo hsiSaved = savedHostScoreInfos.get(hi);
if (cb == null) {
return false;
}
final HostScoreInfo hsi = (HostScoreInfo) cb.getValue();
if (hsiSaved == null && !hsi.getScore().equals("0")) {
return true;
} else if (hsiSaved != null && !hsi.equals(hsiSaved)) {
return true;
}
}
return false;
}
/**
* Returns the list of all services, that can be used in the 'add
* service' action.
*/
public List<HeartbeatService> getAddServiceList(final String cl) {
return globalGetAddServiceList(cl);
}
/**
* Returns 'existing service' list for graph popup menu.
*/
public List<ServiceInfo> getExistingServiceList(final ServiceInfo p) {
final List<ServiceInfo> existingServiceList =
new ArrayList<ServiceInfo>();
for (final String name : nameToServiceInfoHash.keySet()) {
final Map<String, ServiceInfo> idHash =
nameToServiceInfoHash.get(name);
for (final String id : idHash.keySet()) {
final ServiceInfo si = idHash.get(id);
if (!heartbeatGraph.existsInThePath(si, p)) {
existingServiceList.add(si);
}
}
}
return existingServiceList;
}
/**
* Returns info object of all block devices on all hosts that have the
* same names and other attributes.
*/
Info[] getCommonBlockDevInfos(final Info defaultValue,
final String serviceName) {
final List<Info> list = new ArrayList<Info>();
/* drbd resources */
final Enumeration drbdResources = drbdNode.children();
if (defaultValue != null) {
list.add(defaultValue);
}
while (drbdResources.hasMoreElements()) {
DefaultMutableTreeNode n =
(DefaultMutableTreeNode) drbdResources.nextElement();
final CommonDeviceInterface drbdRes =
(CommonDeviceInterface) n.getUserObject();
list.add((Info) drbdRes);
}
/* block devices that are the same on all hosts */
final Enumeration cbds = commonBlockDevicesNode.children();
while (cbds.hasMoreElements()) {
DefaultMutableTreeNode n =
(DefaultMutableTreeNode) cbds.nextElement();
final CommonDeviceInterface cbd =
(CommonDeviceInterface) n.getUserObject();
list.add((Info) cbd);
}
return list.toArray(new Info[list.size()]);
}
/**
* Selects the node in the menu and reloads everything underneath.
*/
public void selectMyself() {
super.selectMyself();
nodeChanged(getNode());
}
/**
* Creates id text field with label and adds it to the panel.
*/
protected void addIdField(final JPanel optionsPanel,
final int leftWidth,
final int rightWidth) {
final JPanel panel = getParamPanel("ID");
final String regexp = "^[\\w-]+$";
final String id = getService().getId();
idField = new GuiComboBox(id, null, null, regexp, rightWidth);
idField.setValue(id);
final String[] params = getParametersFromXML();
idField.getDocument().addDocumentListener(
new DocumentListener() {
private void check() {
Thread thread = new Thread(new Runnable() {
public void run() {
final boolean enable =
checkResourceFields("id",
params);
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
applyButton.setEnabled(enable);
}
});
}
});
thread.start();
}
public void insertUpdate(final DocumentEvent e) {
check();
}
public void removeUpdate(final DocumentEvent e) {
check();
}
public void changedUpdate(final DocumentEvent e) {
check();
}
}
);
paramComboBoxAdd("id", null, idField);
addField(panel, new JLabel("id"), idField, leftWidth, rightWidth);
SpringUtilities.makeCompactGrid(panel, 1, 2, // rows, cols
1, 1, // initX, initY
1, 1); // xPad, yPad
optionsPanel.add(panel);
if (!getService().isNew()) {
idField.setEnabled(false);
}
}
/**
* Sets value for id field.
*/
protected void setIdField(final String id) {
idField.setValue(id);
}
/**
* Creates heartbeat id and group text field with label and adds them
* to the panel.
*/
protected void addHeartbeatFields(final JPanel optionsPanel,
final int leftWidth,
final int rightWidth) {
final JLabel heartbeatIdLabel =
new JLabel(getService().getHeartbeatId());
final JPanel panel = getParamPanel("Heartbeat");
addField(panel,
new JLabel(Tools.getString("ClusterBrowser.HeartbeatId")),
heartbeatIdLabel,
leftWidth,
rightWidth);
final JLabel heartbeatClassLabel =
new JLabel(getService().getHeartbeatClass());
addField(panel,
new JLabel(Tools.getString("ClusterBrowser.HeartbeatClass")),
heartbeatClassLabel,
leftWidth,
rightWidth);
int rows = 2;
if (groupInfo != null) {
final String groupId = groupInfo.getService().getHeartbeatId();
final JLabel groupLabel = new JLabel(groupId);
addField(panel,
new JLabel(Tools.getString("ClusterBrowser.Group")),
groupLabel,
leftWidth,
rightWidth);
rows++;
}
SpringUtilities.makeCompactGrid(panel, rows, 2, // rows, cols
1, 1, // initX, initY
1, 1); // xPad, yPad
optionsPanel.add(panel);
}
/**
* Creates host score combo boxes with labels, one per host.
*/
protected void addHostScores(final JPanel optionsPanel,
final int leftWidth,
final int rightWidth) {
int rows = 0;
scoreComboBoxHash.clear();
final JPanel panel =
getParamPanel(Tools.getString("ClusterBrowser.HostScores"));
for (Host host : getClusterHosts()) {
final HostInfo hi = host.getBrowser().getHostInfo();
final Info[] scores = enumToInfoArray(null,
getName(),
scoresNode.children());
int defaultScore = scores.length - 1; // score )
final GuiComboBox cb =
new GuiComboBox(scores[defaultScore].toString(),
scores,
GuiComboBox.Type.COMBOBOX,
null,
rightWidth);
defaultScore = 0; // score -infinity
scoreComboBoxHash.put(hi, cb);
/* set selected host scores in the combo box from
* savedHostScoreInfos */
final HostScoreInfo hsiSaved = savedHostScoreInfos.get(hi);
if (hsiSaved != null) {
cb.setValue(hsiSaved);
}
}
/* host score combo boxes */
for (Host host : getClusterHosts()) {
final HostInfo hi = host.getBrowser().getHostInfo();
final GuiComboBox cb = scoreComboBoxHash.get(hi);
addField(panel,
new JLabel("on " + hi.getName()),
cb,
leftWidth,
rightWidth);
rows++;
}
SpringUtilities.makeCompactGrid(panel, rows, 2, // rows, cols
1, 1, // initX, initY
1, 1); // xPad, yPad
optionsPanel.add(panel);
}
/**
* Creates operations combo boxes with labels,
*/
protected void addOperations(final JPanel optionsPanel,
final JPanel extraOptionsPanel,
final int leftWidth,
final int rightWidth) {
int rows = 0;
int extraRows = 0;
operationsComboBoxHash.clear();
final JPanel panel = getParamPanel(
Tools.getString("ClusterBrowser.Operations"));
final JPanel extraPanel = getParamPanel(
Tools.getString("ClusterBrowser.AdvancedOperations"),
EXTRA_PANEL_BACKGROUND
);
for (final String op : HB_OPERATIONS) {
for (final String param : HB_OPERATION_PARAMS.get(op)) {
GuiComboBox.Type type;
Unit[] units = null;
final String regexp = "^-?\\d*$";
type = GuiComboBox.Type.TEXTFIELDWITHUNIT;
// TODO: having this on two places
units = new Unit[] {
new Unit("", "", "", ""),
new Unit("ms",
"ms",
"Millisecond",
"Milliseconds"),
new Unit("us",
"us",
"Microsecond",
"Microseconds"),
new Unit("s", "s", "Second", "Seconds"),
new Unit("m", "m", "Minute", "Minutes"),
new Unit("h", "h", "Hour", "Hours"),
};
String defaultValue =
hbService.getOperationDefault(op, param);
// TODO: old style resources
if (defaultValue == null) {
defaultValue = "0";
}
final GuiComboBox cb =
new GuiComboBox(defaultValue,
null,
units,
type,
regexp,
rightWidth);
operationsComboBoxHash.put(op, param, cb);
final String savedValue =
(String) savedOperation.get(op, param);
if (savedValue != null) {
cb.setValue(savedValue);
}
JPanel p;
if (HB_OP_BASIC.contains(op)) {
p = panel;
rows++;
} else {
p = extraPanel;
extraRows++;
}
addField(p,
new JLabel(Tools.ucfirst(op)
+ " / " + Tools.ucfirst(param)),
cb,
leftWidth,
rightWidth);
}
}
SpringUtilities.makeCompactGrid(panel, rows, 2, // rows, cols
1, 1, // initX, initY
1, 1); // xPad, yPad
SpringUtilities.makeCompactGrid(extraPanel, extraRows, 2,
1, 1, // initX, initY
1, 1); // xPad, yPad
optionsPanel.add(panel);
extraOptionsPanel.add(extraPanel);
}
/**
* Returns parameters.
*/
public String[] getParametersFromXML() {
return heartbeatXML.getParameters(hbService);
}
/**
* Returns true if the value of the parameter is ok.
*/
protected boolean checkParam(final String param,
final String newValue) {
if (param.equals("ip")
&& newValue != null
&& !Tools.checkIp(newValue)) {
return false;
}
return heartbeatXML.checkParam(hbService,
param,
newValue);
}
/**
* Returns default value for specified parameter.
*/
protected String getParamDefault(final String param) {
return heartbeatXML.getParamDefault(hbService,
param);
}
/**
* Returns possible choices for drop down lists.
*/
protected Object[] getParamPossibleChoices(final String param) {
if (isCheckBox(param)) {
return heartbeatXML.getCheckBoxChoices(hbService, param);
} else {
// TODO: this does nothing, I think
return heartbeatXML.getParamPossibleChoices(hbService, param);
}
}
/**
* Returns short description of the specified parameter.
*/
protected String getParamShortDesc(final String param) {
return heartbeatXML.getParamShortDesc(hbService,
param);
}
/**
* Returns long description of the specified parameter.
*/
protected String getParamLongDesc(final String param) {
return heartbeatXML.getParamLongDesc(hbService,
param);
}
/**
* Returns section to which the specified parameter belongs.
*/
protected String getSection(final String param) {
return heartbeatXML.getSection(hbService,
param);
}
/**
* Returns true if the specified parameter is required.
*/
protected boolean isRequired(final String param) {
return heartbeatXML.isRequired(hbService,
param);
}
/**
* Returns true if the specified parameter is meta attribute.
*/
protected boolean isMetaAttr(final String param) {
return heartbeatXML.isMetaAttr(hbService,
param);
}
/**
* Returns true if the specified parameter is integer.
*/
protected boolean isInteger(final String param) {
return heartbeatXML.isInteger(hbService,
param);
}
/**
* Returns true if the specified parameter is of time type.
*/
protected boolean isTimeType(final String param) {
return heartbeatXML.isTimeType(hbService,
param);
}
/**
* Returns whether parameter is checkbox.
*/
protected boolean isCheckBox(final String param) {
final String type = heartbeatXML.getParamType(hbService,
param);
if (type == null) {
return false;
}
if (DRBD_RES_BOOL_TYPE_NAME.equals(type)) {
return true;
}
return false;
}
/**
* Returns the type of the parameter according to the OCF.
*/
protected String getParamType(final String param) {
return heartbeatXML.getParamType(hbService,
param);
}
/**
* Is called before the service is added. This is for example used by
* FilesystemInfo so that it can add DrbddiskInfo before it adds
* itself.
*/
public void addResourceBefore() {
}
/**
* Returns info panel with comboboxes for service parameters.
*/
public JComponent getInfoPanel() {
heartbeatGraph.pickInfo(this);
if (infoPanel != null) {
return infoPanel;
}
/* main, button and options panels */
final JPanel mainPanel = new JPanel();
mainPanel.setBackground(PANEL_BACKGROUND);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
final JPanel buttonPanel = new JPanel(new BorderLayout());
buttonPanel.setBackground(STATUS_BACKGROUND);
buttonPanel.setMinimumSize(new Dimension(0, 50));
buttonPanel.setPreferredSize(new Dimension(0, 50));
buttonPanel.setMaximumSize(new Dimension(Short.MAX_VALUE, 50));
final JPanel optionsPanel = new JPanel();
optionsPanel.setBackground(PANEL_BACKGROUND);
optionsPanel.setLayout(new BoxLayout(optionsPanel,
BoxLayout.Y_AXIS));
optionsPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
final JPanel extraOptionsPanel = new JPanel();
extraOptionsPanel.setBackground(EXTRA_PANEL_BACKGROUND);
extraOptionsPanel.setLayout(new BoxLayout(extraOptionsPanel,
BoxLayout.Y_AXIS));
extraOptionsPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
/* expert mode */
buttonPanel.add(Tools.expertModeButton(extraOptionsPanel),
BorderLayout.WEST);
/* Actions */
final JMenuBar mb = new JMenuBar();
mb.setBackground(PANEL_BACKGROUND);
final JMenu serviceCombo = getActionsMenu();
updateMenus(null);
mb.add(serviceCombo);
buttonPanel.add(mb, BorderLayout.EAST);
/* id textfield */
addIdField(optionsPanel, SERVICE_LABEL_WIDTH, SERVICE_FIELD_WIDTH);
/* heartbeat fields */
addHeartbeatFields(optionsPanel,
SERVICE_LABEL_WIDTH,
SERVICE_FIELD_WIDTH);
/* score combo boxes */
addHostScores(optionsPanel,
SERVICE_LABEL_WIDTH,
SERVICE_FIELD_WIDTH);
/* get dependent resources and create combo boxes for ones, that
* need parameters */
paramComboBoxClear();
final String[] params = getParametersFromXML();
addParams(optionsPanel,
extraOptionsPanel,
params,
SERVICE_LABEL_WIDTH,
SERVICE_FIELD_WIDTH);
if (!getHeartbeatService().isGroup()) {
/* Operations */
addOperations(optionsPanel,
extraOptionsPanel,
SERVICE_LABEL_WIDTH,
SERVICE_FIELD_WIDTH);
}
/* add item listeners to the host scores combos */
for (Host host : getClusterHosts()) {
final HostInfo hi = host.getBrowser().getHostInfo();
final GuiComboBox cb = scoreComboBoxHash.get(hi);
cb.addListeners(
new ItemListener() {
public void itemStateChanged(final ItemEvent e) {
if (cb.isCheckBox()
|| e.getStateChange() == ItemEvent.SELECTED) {
Thread thread = new Thread(new Runnable() {
public void run() {
final boolean enable =
checkResourceFields("cached",
params);
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
applyButton.setEnabled(enable);
}
});
}
});
thread.start();
}
}
},
new DocumentListener() {
private void check() {
Thread thread = new Thread(new Runnable() {
public void run() {
final boolean enable =
checkResourceFields("cached", params);
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
applyButton.setEnabled(enable);
}
});
}
});
thread.start();
}
public void insertUpdate(final DocumentEvent e) {
check();
}
public void removeUpdate(final DocumentEvent e) {
check();
}
public void changedUpdate(final DocumentEvent e) {
check();
}
}
);
}
if (!getHeartbeatService().isGroup()) {
/* add item listeners to the operations combos */
for (final String op : HB_OPERATIONS) {
for (final String param : HB_OPERATION_PARAMS.get(op)) {
final GuiComboBox cb =
(GuiComboBox) operationsComboBoxHash.get(op, param);
cb.addListeners(
new ItemListener() {
public void itemStateChanged(final ItemEvent e) {
if (cb.isCheckBox()
|| e.getStateChange() == ItemEvent.SELECTED) {
Thread thread = new Thread(new Runnable() {
public void run() {
final boolean enable =
checkResourceFields("cached", params);
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
applyButton.setEnabled(enable);
}
});
}
});
thread.start();
}
}
},
new DocumentListener() {
private void check() {
Thread thread = new Thread(new Runnable() {
public void run() {
final boolean enable =
checkResourceFields("cached",
params);
SwingUtilities.invokeLater(
new Runnable() {
public void run() {
applyButton.setEnabled(enable);
}
});
}
});
thread.start();
}
public void insertUpdate(final DocumentEvent e) {
check();
}
public void removeUpdate(final DocumentEvent e) {
check();
}
public void changedUpdate(final DocumentEvent e) {
check();
}
}
);
}
}
}
/* add item listeners to the apply button. */
applyButton.addActionListener(
new ActionListener() {
public void actionPerformed(final ActionEvent e) {
final Thread thread = new Thread(
new Runnable() {
public void run() {
hbStatusLock();
apply();
hbStatusUnlock();
}
}
);
thread.start();
}
}
);
/* apply button */
addApplyButton(mainPanel);
applyButton.setEnabled(
checkResourceFields(null, params)
);
mainPanel.add(optionsPanel);
mainPanel.add(extraOptionsPanel);
infoPanel = new JPanel();
infoPanel.setBackground(PANEL_BACKGROUND);
infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));
infoPanel.add(buttonPanel);
infoPanel.add(new JScrollPane(mainPanel));
infoPanel.add(Box.createVerticalGlue());
/* if id textfield was changed and this id is not used,
* enable apply button */
return infoPanel;
}
/**
* Clears the info panel cache, forcing it to reload.
*/
public boolean selectAutomaticallyInTreeMenu() {
return infoPanel == null;
}
/**
* Goes through the scores and sets preferred locations.
*/
protected void setLocations(final String heartbeatId) {
final Host dcHost = getDCHost();
for (Host host : getClusterHosts()) {
final HostInfo hi = host.getBrowser().getHostInfo();
final GuiComboBox cb = scoreComboBoxHash.get(hi);
final HostScoreInfo hsi = (HostScoreInfo) cb.getValue();
final HostScoreInfo hsiSaved = savedHostScoreInfos.get(hi);
if (!hsi.equals(hsiSaved)) {
final String onHost = hi.getName();
final String score = hsi.getScore();
final String locationId =
heartbeatStatus.getLocationId(
getService().getHeartbeatId(),
onHost);
Heartbeat.setLocation(dcHost,
getService().getHeartbeatId(),
onHost,
score,
locationId);
}
}
storeHostScoreInfos();
}
/**
* Returns hash with changed operation ids and all name, value pairs.
* This works for new heartbeats >= 2.99.0
*/
private Map<String, Map<String, String>> getOperations(
String heartbeatId) {
final Map<String, Map<String, String>> operations =
new HashMap<String, Map<String, String>>();
for (final String op : HB_OPERATIONS) {
final Map<String, String> opHash =
new HashMap<String, String>();
String opId = heartbeatStatus.getOpId(heartbeatId, op);
if (opId == null) {
/* generate one */
opId = "op-" + heartbeatId + "-" + op;
}
for (final String param : HB_OPERATION_PARAM_LIST) {
if (HB_OPERATION_PARAMS.get(op).contains(param)) {
final GuiComboBox cb =
(GuiComboBox) operationsComboBoxHash.get(op,
param);
final String value = cb.getStringValue();
String savedOp =
(String) savedOperation.get(op, param);
if (savedOp == null) {
savedOp = "";
}
if (!value.equals(savedOp)) {
opHash.put(param, value);
}
}
if (opHash.size() > 0) {
operations.put(op, opHash);
opHash.put("id", opId);
opHash.put("name", op);
}
}
}
return operations;
}
/**
* Applies the changes to the service parameters.
*/
public void apply() {
/* TODO: make progress indicator per resource. */
setUpdated(true);
final String[] params = getParametersFromXML();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
applyButton.setEnabled(false);
idField.setEnabled(false);
}
});
/* add myself to the hash with service name and id as
* keys */
removeFromServiceInfoHash(this);
final String oldHeartbeatId = getService().getHeartbeatId();
if (oldHeartbeatId != null) {
heartbeatIdToServiceInfo.remove(oldHeartbeatId);
heartbeatIdList.remove(oldHeartbeatId);
}
final String id = idField.getStringValue();
getService().setId(id);
addToHeartbeatIdList(this);
addNameToServiceInfoHash(this);
addResourceBefore();
/*
MSG_ADD_RSC rsc_id rsc_class rsc_type rsc_provider group("" for NONE)
advance(""|"clone"|"master") advance_id clone_max
clone_node_max master_max master_node_max
param_id1 param_name1 param_value1
param_id2 param_name2 param_value2
...
param_idn param_namen param_valuen
in heartbeat 2.1.3 there is additional new_group parameter (sometimes it is, sometime not 2.1.3-2)
*/
Map<String,String> pacemakerResAttrs =
new HashMap<String,String>();
Map<String,String> pacemakerResArgs = new HashMap<String,String>();
Map<String,String> pacemakerMetaArgs = new HashMap<String,String>();
final String hbClass = getService().getHeartbeatClass();
final String type = getResource().getName();
String heartbeatId = getService().getHeartbeatId();
pacemakerResAttrs.put("id", heartbeatId);
pacemakerResAttrs.put("class", hbClass);
pacemakerResAttrs.put("type", type);
String group;
String groupId = null; /* for pacemaker */
if (groupInfo == null) {
group = HB_NONE_ARG;
} else {
group = groupInfo.getService().getHeartbeatId();
groupId = group;
}
if (getService().isNew()) {
final String provider = HB_HEARTBEAT_PROVIDER;
if (hbClass.equals("ocf")) {
pacemakerResAttrs.put("provider", provider);
}
final String advance = HB_NONE_ARG;
final String advanceId = HB_NONE_ARG;
final String cloneMax = HB_NONE_ARG;
final String cloneNodeMax = HB_NONE_ARG;
final String masterMax = HB_NONE_ARG;
final String masterNodeMax = HB_NONE_ARG;
final String newGroup = HB_NONE_ARG;
final StringBuffer args = new StringBuffer(120);
args.append(heartbeatId);
args.append(' ');
args.append(hbClass);
args.append(' ');
args.append(type);
args.append(' ');
args.append(provider);
args.append(' ');
args.append(group);
args.append(' ');
args.append(advance);
args.append(' ');
args.append(advanceId);
args.append(' ');
args.append(cloneMax);
args.append(' ');
args.append(cloneNodeMax);
args.append(' ');
args.append(masterMax);
args.append(' ');
args.append(masterNodeMax);
/* TODO: there are more attributes. */
final String hbV = getDCHost().getHeartbeatVersion();
if (Tools.compareVersions(hbV, "2.1.3") >= 0) {
args.append(' ');
args.append(newGroup);
}
for (String param : params) {
String value = getComboBoxValue(param);
if (value.equals(getParamDefault(param))
&& !isMetaAttr(param)) {
continue;
}
if ("".equals(value)) {
value = HB_NONE_ARG;
} else {
/* for pacemaker */
if (isMetaAttr(param)) {
pacemakerMetaArgs.put(param, value);
} else {
pacemakerResArgs.put(param, value);
}
}
args.append(' ');
args.append(heartbeatId);
args.append('-');
args.append(param);
args.append(' ');
args.append(param);
args.append(" \"");
args.append(value);
args.append('"');
}
String command = "-C";
if (groupInfo != null && !groupInfo.getService().isNew()) {
command = "-U";
}
Heartbeat.setParameters(getDCHost(),
command,
heartbeatId,
groupId,
args.toString(),
pacemakerResAttrs,
pacemakerResArgs,
pacemakerMetaArgs,
null,
null,
getOperations(heartbeatId),
null);
if (groupInfo == null) {
final String[] parents = heartbeatGraph.getParents(this);
Heartbeat.setOrderAndColocation(getDCHost(),
heartbeatId,
parents);
}
} else {
// update parameters
final StringBuffer args = new StringBuffer("");
for (String param : params) {
final String oldValue = getResource().getValue(param);
String value = getComboBoxValue(param);
if (value.equals(oldValue)) {
continue;
}
if ("".equals(value)) {
value = getParamDefault(param);
} else {
if (isMetaAttr(param)) {
pacemakerMetaArgs.put(param, value);
} else {
pacemakerResArgs.put(param, value);
}
}
args.append(' ');
args.append(heartbeatId);
args.append('-');
args.append(param);
args.append(' ');
args.append(param);
args.append(" \"");
args.append(value);
args.append('"');
}
args.insert(0, heartbeatId);
Heartbeat.setParameters(
getDCHost(),
"-U",
heartbeatId,
groupId,
args.toString(),
pacemakerResAttrs,
pacemakerResArgs,
pacemakerMetaArgs,
heartbeatStatus.getResourceInstanceAttrId(heartbeatId),
heartbeatStatus.getParametersNvpairsIds(heartbeatId),
getOperations(heartbeatId),
heartbeatStatus.getOperationsId(heartbeatId));
}
if (groupInfo != null && groupInfo.getService().isNew()) {
groupInfo.apply();
}
if (groupInfo == null) {
setLocations(heartbeatId);
}
storeComboBoxValues(params);
reload(getNode());
heartbeatGraph.repaint();
}
/**
* Removes order.
*/
public void removeOrder(final ServiceInfo parent) {
parent.setUpdated(true);
setUpdated(true);
final String parentHbId = parent.getService().getHeartbeatId();
final String orderId =
heartbeatStatus.getOrderId(parentHbId,
getService().getHeartbeatId());
final String score =
heartbeatStatus.getOrderScore(
parent.getService().getHeartbeatId(),
getService().getHeartbeatId());
final String symmetrical =
heartbeatStatus.getOrderSymmetrical(
parent.getService().getHeartbeatId(),
getService().getHeartbeatId());
Heartbeat.removeOrder(getDCHost(),
orderId,
parentHbId,
getService().getHeartbeatId(),
score,
symmetrical);
}
/**
* Adds order constraint from this service to the parent.
*/
public void addOrder(final ServiceInfo parent) {
parent.setUpdated(true);
setUpdated(true);
final String parentHbId = parent.getService().getHeartbeatId();
Heartbeat.addOrder(getDCHost(),
parentHbId,
getService().getHeartbeatId());
}
/**
* Removes colocation.
*/
public void removeColocation(final ServiceInfo parent) {
parent.setUpdated(true);
setUpdated(true);
final String parentHbId = parent.getService().getHeartbeatId();
final String colocationId =
heartbeatStatus.getColocationId(parentHbId,
getService().getHeartbeatId());
final String score =
heartbeatStatus.getColocationScore(
parent.getService().getHeartbeatId(),
getService().getHeartbeatId());
Heartbeat.removeColocation(getDCHost(),
colocationId,
parentHbId, /* from */
getService().getHeartbeatId(), /* to */
score
);
}
/**
* Adds colocation constraint from this service to the parent. The
* parent - child order is here important, in case colocation
* constraint is used along with order constraint.
*/
public void addColocation(final ServiceInfo parent) {
parent.setUpdated(true);
setUpdated(true);
final String parentHbId = parent.getService().getHeartbeatId();
Heartbeat.addColocation(getDCHost(),
parentHbId,
getService().getHeartbeatId());
}
/**
* Returns panel with graph.
*/
public JPanel getGraphicalView() {
return heartbeatGraph.getGraphPanel();
}
/**
* Adds service panel to the position 'pos'.
*/
public ServiceInfo addServicePanel(final HeartbeatService newHbService,
final Point2D pos,
final boolean reloadNode) {
ServiceInfo newServiceInfo;
final String name = newHbService.getName();
if (newHbService.isFilesystem()) {
newServiceInfo = new FilesystemInfo(name, newHbService);
} else if (newHbService.isDrbddisk()) {
newServiceInfo = new DrbddiskInfo(name, newHbService);
} else if (newHbService.isIPaddr()) {
newServiceInfo = new IPaddrInfo(name, newHbService);
} else if (newHbService.isGroup()) {
newServiceInfo = new GroupInfo(newHbService);
} else {
newServiceInfo = new ServiceInfo(name, newHbService);
}
addToHeartbeatIdList(newServiceInfo);
addServicePanel(newServiceInfo, pos, reloadNode);
return newServiceInfo;
}
/**
* Adds service panel to the position 'pos'.
* TODO: is it used?
*/
public void addServicePanel(final ServiceInfo serviceInfo,
final Point2D pos,
final boolean reloadNode) {
serviceInfo.getService().setHeartbeatClass(
serviceInfo.getHeartbeatService().getHeartbeatClass());
if (heartbeatGraph.addResource(serviceInfo, this, pos)) {
// edge added
final String parentId = getService().getHeartbeatId();
final String heartbeatId =
serviceInfo.getService().getHeartbeatId();
Heartbeat.setOrderAndColocation(getDCHost(),
heartbeatId,
new String[]{parentId});
} else {
addNameToServiceInfoHash(serviceInfo);
final DefaultMutableTreeNode newServiceNode =
new DefaultMutableTreeNode(serviceInfo);
serviceInfo.setNode(newServiceNode);
servicesNode.add(newServiceNode);
if (reloadNode) {
reload(servicesNode);
reload(newServiceNode);
}
}
heartbeatGraph.reloadServiceMenus();
}
/**
* Returns service that belongs to this info object.
*/
public Service getService() {
return (Service) getResource();
}
/**
* Starts resource in heartbeat.
*/
public void startResource() {
setUpdated(true);
Heartbeat.startResource(getDCHost(),
getService().getHeartbeatId());
}
/**
* Moves resource up in the group.
*/
public void moveGroupResUp() {
setUpdated(true);
Heartbeat.moveGroupResUp(getDCHost(),
getService().getHeartbeatId());
}
/**
* Moves resource down in the group.
*/
public void moveGroupResDown() {
setUpdated(true);
Heartbeat.moveGroupResDown(getDCHost(),
getService().getHeartbeatId());
}
/**
* Stops resource in heartbeat.
*/
public void stopResource() {
setUpdated(true);
Heartbeat.stopResource(getDCHost(),
getService().getHeartbeatId());
}
/**
* Migrates resource in heartbeat from current location.
*/
public void migrateResource(final String onHost) {
setUpdated(true);
Heartbeat.migrateResource(getDCHost(),
getService().getHeartbeatId(),
onHost);
}
/**
* Removes constraints created by resource migrate command.
*/
public void unmigrateResource() {
setUpdated(true);
Heartbeat.unmigrateResource(getDCHost(),
getService().getHeartbeatId());
}
/**
* Cleans up the resource.
*/
public void cleanupResource() {
setUpdated(true);
Heartbeat.cleanupResource(getDCHost(),
getService().getHeartbeatId(),
getClusterHosts());
}
/**
* Removes the service without confirmation dialog.
*/
protected void removeMyselfNoConfirm() {
setUpdated(true);
getService().setRemoved(true);
//super.removeMyself();
if (getService().isNew()) {
heartbeatGraph.getServicesInfo().setAllResources();
} else {
if (groupInfo == null) {
final String[] parents = heartbeatGraph.getParents(this);
for (String parent : parents) {
final String colocationId =
heartbeatStatus.getColocationId(
parent, getService().getHeartbeatId());
final String colScore =
heartbeatStatus.getColocationScore(
parent,
getService().getHeartbeatId());
Heartbeat.removeColocation(getDCHost(),
colocationId,
parent,
getService().getHeartbeatId(),
colScore);
final String orderId =
heartbeatStatus.getOrderId(
parent, getService().getHeartbeatId());
final String ordScore =
heartbeatStatus.getOrderScore(
parent,
getService().getHeartbeatId());
final String symmetrical =
heartbeatStatus.getOrderSymmetrical(
parent,
getService().getHeartbeatId());
Heartbeat.removeOrder(getDCHost(),
orderId,
parent,
getService().getHeartbeatId(),
ordScore,
symmetrical);
}
final String[] children = heartbeatGraph.getChildren(this);
for (String child : children) {
final String colocationId =
heartbeatStatus.getColocationId(
child, getService().getHeartbeatId());
final String colScore =
heartbeatStatus.getColocationScore(
getService().getHeartbeatId(),
child);
Heartbeat.removeColocation(getDCHost(),
colocationId,
getService().getHeartbeatId(),
child,
colScore);
final String orderId = heartbeatStatus.getOrderId(child,
getService().getHeartbeatId());
final String ordScore =
heartbeatStatus.getOrderScore(
getService().getHeartbeatId(),
child);
final String symmetrical =
heartbeatStatus.getOrderSymmetrical(
getService().getHeartbeatId(),
child);
Heartbeat.removeOrder(getDCHost(),
orderId,
getService().getHeartbeatId(),
child,
ordScore,
symmetrical);
}
for (String locId : heartbeatStatus.getLocationIds(getService().getHeartbeatId())) {
final String locScore =
heartbeatStatus.getLocationScore(locId);
Heartbeat.removeLocation(getDCHost(),
locId,
getService().getHeartbeatId(),
locScore);
}
}
if (!getHeartbeatService().isGroup()) {
String groupId = null; /* for pacemaker */
if (groupInfo != null) {
/* get group id only if there is only one resource in a
* group.
*/
final String group = groupInfo.getService().getHeartbeatId();
final Enumeration e = groupInfo.getNode().children();
while (e.hasMoreElements()) {
DefaultMutableTreeNode n =
(DefaultMutableTreeNode) e.nextElement();
final ServiceInfo child =
(ServiceInfo) n.getUserObject();
child.getService().setModified(true);
child.getService().doneModifying();
}
if (heartbeatStatus.getGroupResources(group).size() == 1) {
groupInfo.getService().setRemoved(true);
groupInfo.removeMyselfNoConfirmFromChild();
groupId = group;
groupInfo.getService().doneRemoving();
}
}
Heartbeat.removeResource(getDCHost(),
getService().getHeartbeatId(),
groupId);
}
}
//if (groupInfo == null)
// heartbeatGraph.removeInfo(this);
removeFromServiceInfoHash(this);
infoPanel = null;
getService().doneRemoving();
}
/**
* Removes this service from the heartbeat with confirmation dialog.
*/
public void removeMyself() {
String desc = Tools.getString(
"ClusterBrowser.confirmRemoveService.Description");
desc = desc.replaceAll("@SERVICE@", toString());
if (Tools.confirmDialog(
Tools.getString("ClusterBrowser.confirmRemoveService.Title"),
desc,
Tools.getString("ClusterBrowser.confirmRemoveService.Yes"),
Tools.getString("ClusterBrowser.confirmRemoveService.No"))) {
removeMyselfNoConfirm();
}
getService().setNew(false);
}
/**
* Removes the service from some global hashes and lists.
*/
public void removeInfo() {
heartbeatIdToServiceInfo.remove(getService().getHeartbeatId());
heartbeatIdList.remove(getService().getHeartbeatId());
removeFromServiceInfoHash(this);
super.removeMyself();
}
/**
* Sets this service as part of a group.
*/
public void setGroupInfo(final GroupInfo groupInfo) {
this.groupInfo = groupInfo;
}
/**
* Returns the group to which this service belongs or null, if it is
* not in any group.
*/
public GroupInfo getGroupInfo() {
return groupInfo;
}
/**
* Returns list of items for service popup menu with actions that can
* be executed on the heartbeat services.
*/
public List<UpdatableItem> createPopup() {
final List<UpdatableItem> items = new ArrayList<UpdatableItem>();
/* remove service */
final MyMenuItem removeMenuItem = new MyMenuItem(
Tools.getString(
"ClusterBrowser.Hb.RemoveService"),
REMOVE_ICON) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
// TODO: if it was migrated
return !getService().isRemoved();
}
public void action() {
removeMyself();
heartbeatGraph.getVisualizationViewer().repaint();
}
};
items.add((UpdatableItem) removeMenuItem);
registerMenuItem((UpdatableItem) removeMenuItem);
if (groupInfo == null) {
/* add new group and dependency*/
final MyMenuItem addGroupMenuItem =
new MyMenuItem(Tools.getString(
"ClusterBrowser.Hb.AddDependentGroup"),
null,
null) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
return !getService().isRemoved();
}
public void action() {
final StringInfo gi = new StringInfo(HB_GROUP_NAME,
HB_GROUP_NAME);
addServicePanel(heartbeatXML.getHbGroup(), getPos(), true);
heartbeatGraph.getVisualizationViewer().repaint();
}
};
items.add((UpdatableItem) addGroupMenuItem);
registerMenuItem((UpdatableItem) addGroupMenuItem);
/* add new service and dependency*/
final MyMenu addServiceMenuItem = new MyMenu(
Tools.getString(
"ClusterBrowser.Hb.AddDependency")) {
private static final long serialVersionUID = 1L;
public void update() {
super.update();
removeAll();
final Point2D pos = getPos();
final HeartbeatService fsService =
heartbeatXML.getHbService("Filesystem",
"ocf");
if (fsService != null) { /* just skip it, if it is not*/
final MyMenuItem fsMenuItem =
new MyMenuItem(fsService.getMenuName()) {
private static final long serialVersionUID = 1L;
public void action() {
getPopup().setVisible(false);
addServicePanel(fsService,
getPos(),
true);
heartbeatGraph.getVisualizationViewer().repaint();
}
};
fsMenuItem.setPos(pos);
add(fsMenuItem);
}
final HeartbeatService ipService =
heartbeatXML.getHbService("IPaddr2",
"ocf");
if (ipService != null) { /* just skip it, if it is not*/
final MyMenuItem ipMenuItem =
new MyMenuItem(ipService.getMenuName()) {
private static final long serialVersionUID = 1L;
public void action() {
getPopup().setVisible(false);
addServicePanel(ipService,
getPos(),
true);
heartbeatGraph.getVisualizationViewer().repaint();
}
};
ipMenuItem.setPos(pos);
add(ipMenuItem);
}
for (final String cl : HB_CLASSES) {
final MyMenu classItem =
new MyMenu(HB_CLASS_MENU.get(cl));
DefaultListModel m = new DefaultListModel();
//Point2D pos = getPos();
for (final HeartbeatService hbService : getAddServiceList(cl)) {
final MyMenuItem mmi =
new MyMenuItem(hbService.getMenuName()) {
private static final long serialVersionUID = 1L;
public void action() {
getPopup().setVisible(false);
addServicePanel(hbService,
getPos(),
true);
heartbeatGraph.getVisualizationViewer().repaint();
}
};
mmi.setPos(pos);
m.addElement(mmi);
}
classItem.add(Tools.getScrollingMenu(classItem, m));
add(classItem);
}
}
};
items.add((UpdatableItem) addServiceMenuItem);
registerMenuItem((UpdatableItem) addServiceMenuItem);
/* add existing service dependency*/
final ServiceInfo thisClass = this;
final MyMenu existingServiceMenuItem =
new MyMenu(
Tools.getString(
"ClusterBrowser.Hb.AddStartBefore")) {
private static final long serialVersionUID = 1L;
public void update() {
super.update();
removeAll();
DefaultListModel m = new DefaultListModel();
for (final ServiceInfo asi : getExistingServiceList(thisClass)) {
+ if (asi.getGroupInfo() != null) {
+ /* skip services that are in group. */
+ continue;
+ }
final MyMenuItem mmi =
new MyMenuItem(asi.toString()) {
private static final long serialVersionUID = 1L;
public void action() {
final Thread thread = new Thread(
new Runnable() {
public void run() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
getPopup().setVisible(false);
}
});
addServicePanel(asi, null, true);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
repaint();
}
});
}
});
thread.start();
}
};
m.addElement(mmi);
}
add(Tools.getScrollingMenu(this, m));
}
};
items.add((UpdatableItem) existingServiceMenuItem);
registerMenuItem((UpdatableItem) existingServiceMenuItem);
} else { /* group service */
final MyMenuItem moveUpMenuItem =
new MyMenuItem(Tools.getString(
"ClusterBrowser.Hb.ResGrpMoveUp"),
null, // upIcon,
null) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
// TODO: don't if it is up
return getService().isAvailable();
}
public void action() {
moveGroupResUp();
}
};
items.add(moveUpMenuItem);
registerMenuItem(moveUpMenuItem);
/* move down */
final MyMenuItem moveDownMenuItem =
new MyMenuItem(Tools.getString(
"ClusterBrowser.Hb.ResGrpMoveDown"),
null, // TODO: downIcon,
null) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
// TODO: don't if it is down
return getService().isAvailable();
}
public void action() {
moveGroupResDown();
}
};
items.add(moveDownMenuItem);
registerMenuItem(moveDownMenuItem);
}
/* start resource */
final MyMenuItem startMenuItem =
new MyMenuItem(
Tools.getString("ClusterBrowser.Hb.StartResource"),
START_ICON,
Tools.getString("ClusterBrowser.Hb.StartResource.ToolTip")
) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
return getService().isAvailable() && !isStarted();
}
public void action() {
startResource();
}
};
items.add((UpdatableItem) startMenuItem);
registerMenuItem((UpdatableItem) startMenuItem);
/* stop resource */
final MyMenuItem stopMenuItem =
new MyMenuItem(
Tools.getString("ClusterBrowser.Hb.StopResource"),
STOP_ICON,
Tools.getString("ClusterBrowser.Hb.StopResource.ToolTip")
) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
return getService().isAvailable() && !isStopped();
}
public void action() {
stopResource();
}
};
items.add((UpdatableItem) stopMenuItem);
registerMenuItem((UpdatableItem) stopMenuItem);
/* manage resource */
final MyMenuItem manageMenuItem =
new MyMenuItem(
Tools.getString("ClusterBrowser.Hb.ManageResource"),
START_ICON, // TODO: icons
Tools.getString("ClusterBrowser.Hb.ManageResource.ToolTip"),
Tools.getString("ClusterBrowser.Hb.UnmanageResource"),
STOP_ICON, // TODO: icons
Tools.getString("ClusterBrowser.Hb.UnmanageResource.ToolTip")
) {
private static final long serialVersionUID = 1L;
public boolean predicate() {
return !isManaged();
}
public boolean enablePredicate() {
return getService().isAvailable();
}
public void action() {
if (this.getText().equals(Tools.getString(
"ClusterBrowser.Hb.ManageResource"))) {
setManaged(true);
} else {
setManaged(false);
}
}
};
items.add((UpdatableItem) manageMenuItem);
registerMenuItem((UpdatableItem) manageMenuItem);
/* migrate resource */
for (final String hostName : getHostNames()) {
final MyMenuItem migrateMenuItem =
new MyMenuItem(
Tools.getString(
"ClusterBrowser.Hb.MigrateResource")
+ " " + hostName,
MIGRATE_ICON,
Tools.getString(
"ClusterBrowser.Hb.MigrateResource.ToolTip"),
Tools.getString(
"ClusterBrowser.Hb.MigrateResource")
+ " " + hostName + " (inactive)",
MIGRATE_ICON,
Tools.getString(
"ClusterBrowser.Hb.MigrateResource.ToolTip")
) {
private static final long serialVersionUID = 1L;
public boolean predicate() {
return isActiveNode(hostName);
}
public boolean enablePredicate() {
String runningOnNode = getRunningOnNode();
if (runningOnNode != null) {
runningOnNode = runningOnNode.toLowerCase();
}
return getService().isAvailable()
&& !hostName.toLowerCase().equals(
runningOnNode)
&& isActiveNode(hostName);
}
public void action() {
migrateResource(hostName);
}
};
items.add((UpdatableItem) migrateMenuItem);
registerMenuItem((UpdatableItem) migrateMenuItem);
}
/* unmigrate resource */
final MyMenuItem unmigrateMenuItem =
new MyMenuItem(Tools.getString(
"ClusterBrowser.Hb.UnmigrateResource")) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
// TODO: if it was migrated
return getService().isAvailable();
}
public void action() {
unmigrateResource();
}
};
items.add((UpdatableItem) unmigrateMenuItem);
registerMenuItem((UpdatableItem) unmigrateMenuItem);
/* clean up resource */
final MyMenuItem cleanupMenuItem =
new MyMenuItem(Tools.getString(
"ClusterBrowser.Hb.CleanUpResource")) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
return getService().isAvailable();
}
public void action() {
cleanupResource();
}
};
items.add((UpdatableItem) cleanupMenuItem);
registerMenuItem((UpdatableItem) cleanupMenuItem);
/* view log */
final MyMenuItem viewLogMenu = new MyMenuItem(
Tools.getString("ClusterBrowser.Hb.ViewServiceLog"),
null,
null) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
return !getService().isNew();
}
public void action() {
final Thread thread = new Thread(
new Runnable() {
public void run() {
ServiceLogs l =
new ServiceLogs(getCluster(),
getService().getHeartbeatId());
l.showDialog();
}
});
thread.start();
}
};
registerMenuItem(viewLogMenu);
items.add(viewLogMenu);
return items;
}
/**
* Returns tool tip for the hearbeat service.
*/
public String getToolTipText() {
String node = getRunningOnNode();
if (node == null) {
node = "none";
}
final StringBuffer sb = new StringBuffer(200);
sb.append("<b>");
sb.append(toString());
if (isFailed()) {
sb.append("</b><br><b>Failed</b>");
} else if (isStopped()) {
sb.append("</b><br>not running");
} else {
sb.append("</b><br>running on: ");
sb.append(node);
}
if (!isManaged()) {
sb.append(" (unmanaged)");
}
return sb.toString();
}
/**
* Returns heartbeat service class.
*/
public HeartbeatService getHeartbeatService() {
return hbService;
}
}
/**
* This class is used for all kind of categories in the heartbeat
* hierarchy. Its point is to show heartbeat graph all the time, ane
* heartbeat category is clicked.
*/
class HbCategoryInfo extends CategoryInfo {
/**
* Creates the new HbCategoryInfo object with name of the category.
*/
HbCategoryInfo(final String name) {
super(name);
}
/**
* Returns info for the category.
*/
public String getInfo() {
return "<h2>" + getName() + "</h2>";
}
/**
* Returns heartbeat graph.
*/
public JPanel getGraphicalView() {
return heartbeatGraph.getGraphPanel();
}
}
/**
* This class holds data that describe the heartbeat as whole.
*/
class HeartbeatInfo extends HbCategoryInfo {
/**
* Prepares a new <code>ServicesInfo</code> object.
*
* @param name
* name that will be shown in the tree
*/
public HeartbeatInfo(final String name) {
super(name);
}
/**
* Returns icon for the heartbeat menu item.
*/
public ImageIcon getMenuIcon() {
return null;
}
/**
* Returns info for the Heartbeat menu.
*/
public String getInfo() {
final StringBuffer s = new StringBuffer(30);
s.append("<h2>");
s.append(getName());
if (heartbeatXML == null) {
s.append("</h2><br>info not available");
return s.toString();
}
final Host[] hosts = getClusterHosts();
int i = 0;
final StringBuffer hbVersion = new StringBuffer();
boolean differentHbVersions = false;
for (Host host : hosts) {
if (i == 0) {
hbVersion.append(host.getHeartbeatVersion());
} else if (!hbVersion.toString().equals(
host.getHeartbeatVersion())) {
differentHbVersions = true;
hbVersion.append(", ");
hbVersion.append(host.getHeartbeatVersion());
}
i++;
}
s.append(" (" + hbVersion.toString() + ")</h2><br>");
if (differentHbVersions) {
s.append(Tools.getString(
"ClusterBrowser.DifferentHbVersionsWarning"));
s.append("<br>");
}
return s.toString();
}
}
/**
* This class holds info data for services view and global heartbeat
* config.
*/
class ServicesInfo extends EditableInfo {
/** Cache for the info panel. */
private JComponent infoPanel = null;
/**
* Prepares a new <code>ServicesInfo</code> object.
*
* @param name
* name that will be shown in the tree
*/
public ServicesInfo(final String name) {
super(name);
setResource(new Resource(name));
heartbeatGraph.setServicesInfo(this);
initApplyButton();
}
/**
* Sets info panel.
* TODO: dead code?
*/
public void setInfoPanel(final JComponent infoPanel) {
this.infoPanel = infoPanel;
}
/**
* Returns icon for services menu item.
*/
public ImageIcon getMenuIcon() {
return null;
}
/**
* Returns names of all global parameters.
*/
public String[] getParametersFromXML() {
return heartbeatXML.getGlobalParameters();
}
/**
* Returns long description of the global parameter, that is used for
* tool tips.
*/
protected String getParamLongDesc(final String param) {
return heartbeatXML.getGlobalParamLongDesc(param);
}
/**
* Returns short description of the gloval parameter, that is used as
* label.
*/
protected String getParamShortDesc(final String param) {
return heartbeatXML.getGlobalParamShortDesc(param);
}
/**
* Returns default for this global parameter.
*/
protected String getParamDefault(final String param) {
return heartbeatXML.getGlobalParamDefault(param);
}
/**
* Returns possible choices for pulldown menus if applicable.
*/
protected Object[] getParamPossibleChoices(final String param) {
return heartbeatXML.getGlobalParamPossibleChoices(param);
}
/**
* Checks if the new value is correct for the parameter type and
* constraints.
*/
protected boolean checkParam(final String param,
final String newValue) {
return heartbeatXML.checkGlobalParam(param, newValue);
}
/**
* Returns whether the global parameter is of the integer type.
*/
protected boolean isInteger(final String param) {
return heartbeatXML.isGlobalInteger(param);
}
/**
* Returns whether the global parameter is of the time type.
*/
protected boolean isTimeType(final String param) {
return heartbeatXML.isGlobalTimeType(param);
}
/**
* Returns whether the global parameter is required.
*/
protected boolean isRequired(final String param) {
return heartbeatXML.isGlobalRequired(param);
}
/**
* Returns whether the global parameter is of boolean type and
* requires a checkbox.
*/
protected boolean isCheckBox(final String param) {
final String type = heartbeatXML.getGlobalParamType(param);
if (type == null) {
return false;
}
if (DRBD_RES_BOOL_TYPE_NAME.equals(type)) {
return true;
}
return false;
}
/**
* Returns type of the global parameter.
*/
protected String getParamType(final String param) {
return heartbeatXML.getGlobalParamType(param);
}
/**
* Returns section to which the global parameter belongs.
*/
protected String getSection(final String param) {
return heartbeatXML.getGlobalSection(param);
}
/**
* Applies changes that user has entered.
*/
public void apply() {
final String[] params = getParametersFromXML();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
applyButton.setEnabled(false);
}
});
/* update heartbeat */
final Map<String,String> args = new HashMap<String,String>();
for (String param : params) {
final String oldValue = getResource().getValue(param);
String value = getComboBoxValue(param);
if (value.equals(oldValue)) {
continue;
}
if (oldValue == null && value.equals(getParamDefault(param))) {
continue;
}
if ("".equals(value)) {
value = getParamDefault(param);
}
args.put(param, value);
}
if (!args.isEmpty()) {
Heartbeat.setGlobalParameters(getDCHost(),
args);
}
storeComboBoxValues(params);
}
/**
* Sets heartbeat global parameters after they were obtained.
*/
public void setGlobalConfig() {
final String[] params = getParametersFromXML();
for (String param : params) {
String value = heartbeatStatus.getGlobalParam(param);
final String oldValue = getResource().getValue(param);
//if (value == null) {
// value = "";
//}
if (value != null && !value.equals(oldValue)) {
getResource().setValue(param, value);
final GuiComboBox cb = paramComboBoxGet(param, null);
if (cb != null) {
cb.setValue(value);
}
}
}
final Host[] hosts = cluster.getHostsArray();
for (Host host : hosts) {
if (!heartbeatStatus.isActiveNode(host.getName())) {
//TODO: something's missing here
//System.out.println("is active node: " + host.getName());
}
}
if (infoPanel == null) {
selectMyself();
}
}
/**
* This functions goes through all services, constrains etc. in
* heartbeatStatus and updates the internal structures and graph.
*/
public void setAllResources() {
final String[] allGroups = heartbeatStatus.getAllGroups();
heartbeatGraph.clearVertexIsPresentList();
List<ServiceInfo> groupServiceIsPresent =
new ArrayList<ServiceInfo>();
groupServiceIsPresent.clear();
for (String group : allGroups) {
//TODO: need hb class here
for (final String hbId : heartbeatStatus.getGroupResources(group)) {
final HeartbeatService newHbService =
heartbeatStatus.getResourceType(hbId);
if (newHbService == null) {
/* This is bad. There is a service but we do not have
* the heartbeat script of this service.
*/
continue;
}
GroupInfo newGi = null;
if (!"none".equals(group)) {
newGi = (GroupInfo) heartbeatIdToServiceInfo.get(group);
if (newGi == null) {
final Point2D p = null;
newGi = (GroupInfo) heartbeatGraph.getServicesInfo().addServicePanel(
heartbeatXML.getHbGroup(),
p,
true,
group);
//newGi.getService().setHeartbeatId(group); // TODO: to late
newGi.getService().setNew(false);
addToHeartbeatIdList(newGi);
} else {
final Map<String, String> resourceNode =
heartbeatStatus.getParamValuePairs(hbId);
newGi.setParameters(resourceNode);
newGi.setUpdated(false);
heartbeatGraph.repaint();
}
heartbeatGraph.setVertexIsPresent(newGi);
}
/* continue of creating/updating of the
* service in the gui.
*/
ServiceInfo newSi = heartbeatIdToServiceInfo.get(hbId);
final Map<String, String> resourceNode =
heartbeatStatus.getParamValuePairs(hbId);
if (newSi == null) {
// TODO: get rid of the service name? (everywhere)
final String serviceName = newHbService.getName();
if (newHbService.isFilesystem()) {
newSi = new FilesystemInfo(serviceName,
newHbService,
hbId,
resourceNode);
} else if (newHbService.isDrbddisk()) {
newSi = new DrbddiskInfo(serviceName,
newHbService,
hbId,
resourceNode);
} else if (newHbService.isIPaddr()) {
newSi = new IPaddrInfo(serviceName,
newHbService,
hbId,
resourceNode);
} else {
newSi = new ServiceInfo(serviceName,
newHbService,
hbId,
resourceNode);
}
newSi.getService().setHeartbeatId(hbId);
addToHeartbeatIdList(newSi);
final Point2D p = null;
if (newGi == null) {
heartbeatGraph.getServicesInfo().addServicePanel(
newSi,
p,
true);
} else {
newGi.addGroupServicePanel(newSi);
}
} else {
newSi.setParameters(resourceNode);
newSi.setUpdated(false);
heartbeatGraph.repaint();
}
newSi.getService().setNew(false);
heartbeatGraph.setVertexIsPresent(newSi);
if (newGi != null) {
groupServiceIsPresent.add(newSi);
}
}
}
heartbeatGraph.clearColocationList();
final Map<String, List<String>> colocationMap =
heartbeatStatus.getColocationMap();
for (final String heartbeatIdP : colocationMap.keySet()) {
final List<String> tos = colocationMap.get(heartbeatIdP);
for (final String heartbeatId : tos) {
//final String heartbeatId = colocationMap.get(heartbeatIdP);
final ServiceInfo si =
heartbeatIdToServiceInfo.get(heartbeatId);
final ServiceInfo siP =
heartbeatIdToServiceInfo.get(heartbeatIdP);
heartbeatGraph.addColocation(siP, si);
}
}
heartbeatGraph.clearOrderList();
final Map<String, List<String>> orderMap =
heartbeatStatus.getOrderMap();
for (final String heartbeatIdP : orderMap.keySet()) {
for (final String heartbeatId : orderMap.get(heartbeatIdP)) {
final ServiceInfo si =
heartbeatIdToServiceInfo.get(heartbeatId);
if (si != null) { /* not yet complete */
final ServiceInfo siP =
heartbeatIdToServiceInfo.get(heartbeatIdP);
if (siP != null && siP.getName() != null) {
/* dangling orders and colocations */
if (siP.getName().equals("drbddisk")
&& si.getName().equals("Filesystem")) {
final List<String> colIds =
colocationMap.get(heartbeatIdP);
// TODO: race here
if (colIds != null) {
for (String colId : colIds) {
if (colId != null
&& colId.equals(heartbeatId)) {
/* drbddisk -> Filesystem */
((FilesystemInfo) si).setDrbddiskInfo((DrbddiskInfo) siP);
final DrbdResourceInfo dri = drbdResHash.get(((DrbddiskInfo) siP).getResourceName());
if (dri != null) {
dri.setUsedByHeartbeat(true);
}
}
}
}
}
heartbeatGraph.addOrder(siP, si);
}
}
}
}
final Enumeration e = getNode().children();
while (e.hasMoreElements()) {
DefaultMutableTreeNode n =
(DefaultMutableTreeNode) e.nextElement();
final ServiceInfo g =
(ServiceInfo) n.getUserObject();
if (g.getHeartbeatService().isGroup()) {
final Enumeration ge = g.getNode().children();
while (ge.hasMoreElements()) {
DefaultMutableTreeNode gn =
(DefaultMutableTreeNode) ge.nextElement();
final ServiceInfo s =
(ServiceInfo) gn.getUserObject();
if (!groupServiceIsPresent.contains(s)
&& !s.getService().isNew()) {
/* remove the group service from the menu that does
* not exist anymore. */
s.removeInfo();
}
}
}
}
heartbeatGraph.killRemovedEdges();
heartbeatGraph.killRemovedVertices();
}
/**
* Clears the info panel cache, forcing it to reload.
*/
public boolean selectAutomaticallyInTreeMenu() {
return infoPanel == null;
}
/**
* Returns info for info panel, that hb status failed or null, in which
* case the getInfoPanel() function will show.
*/
public String getInfo() {
if (hbStatusFailed()) {
return Tools.getString("ClusterBrowser.HbStatusFailed");
}
return null;
}
/**
* Returns editable info panel for global heartbeat config.
*/
public JComponent getInfoPanel() {
/* if don't have hb status we don't have all the info we need here.
* TODO: OR we need to get hb status only once
*/
if (hbStatusFailed()) {
return super.getInfoPanel();
}
if (infoPanel != null) {
heartbeatGraph.pickBackground();
return infoPanel;
}
infoPanel = new JPanel();
infoPanel.setBackground(PANEL_BACKGROUND);
infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));
//infoPanel.add(getButtonPanel());
if (heartbeatXML == null) {
return infoPanel;
}
final JPanel mainPanel = new JPanel();
mainPanel.setBackground(PANEL_BACKGROUND);
mainPanel.setLayout(new BoxLayout(mainPanel,
BoxLayout.Y_AXIS));
final JPanel optionsPanel = new JPanel();
optionsPanel.setBackground(PANEL_BACKGROUND);
optionsPanel.setLayout(new BoxLayout(optionsPanel,
BoxLayout.Y_AXIS));
optionsPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
final JPanel extraOptionsPanel = new JPanel();
extraOptionsPanel.setBackground(EXTRA_PANEL_BACKGROUND);
extraOptionsPanel.setLayout(new BoxLayout(extraOptionsPanel,
BoxLayout.Y_AXIS));
extraOptionsPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
final JPanel buttonPanel = new JPanel(new BorderLayout());
buttonPanel.setBackground(STATUS_BACKGROUND);
buttonPanel.setMinimumSize(new Dimension(0, 50));
buttonPanel.setPreferredSize(new Dimension(0, 50));
buttonPanel.setMaximumSize(new Dimension(Short.MAX_VALUE, 50));
/* expert mode */
buttonPanel.add(Tools.expertModeButton(extraOptionsPanel),
BorderLayout.WEST);
final JMenuBar mb = new JMenuBar();
mb.setBackground(PANEL_BACKGROUND);
final JMenu serviceCombo = getActionsMenu();
updateMenus(null);
mb.add(serviceCombo);
buttonPanel.add(mb, BorderLayout.EAST);
infoPanel.add(buttonPanel);
final String[] params = getParametersFromXML();
addParams(optionsPanel,
extraOptionsPanel,
params,
Tools.getDefaultInt("ClusterBrowser.DrbdResLabelWidth"),
Tools.getDefaultInt("ClusterBrowser.DrbdResFieldWidth")
);
applyButton.addActionListener(
new ActionListener() {
public void actionPerformed(final ActionEvent e) {
final Thread thread = new Thread(
new Runnable() {
public void run() {
hbStatusLock();
apply();
hbStatusUnlock();
}
}
);
thread.start();
}
}
);
/* apply button */
addApplyButton(mainPanel);
applyButton.setEnabled(checkResourceFields(null, params));
mainPanel.add(optionsPanel);
mainPanel.add(extraOptionsPanel);
infoPanel.add(new JScrollPane(mainPanel));
infoPanel.add(Box.createVerticalGlue());
heartbeatGraph.pickBackground();
return infoPanel;
}
/**
* Returns heartbeat graph.
*/
public JPanel getGraphicalView() {
return heartbeatGraph.getGraphPanel();
}
/**
* Adds service to the list of services.
* TODO: are they both used?
*/
public ServiceInfo addServicePanel(final HeartbeatService newHbService,
final Point2D pos,
final boolean reloadNode,
final String heartbeatId) {
ServiceInfo newServiceInfo;
final String name = newHbService.getName();
if (newHbService.isFilesystem()) {
newServiceInfo = new FilesystemInfo(name, newHbService);
} else if (newHbService.isDrbddisk()) {
newServiceInfo = new DrbddiskInfo(name, newHbService);
} else if (newHbService.isIPaddr()) {
newServiceInfo = new IPaddrInfo(name, newHbService);
} else if (newHbService.isGroup()) {
newServiceInfo = new GroupInfo(newHbService);
} else {
newServiceInfo = new ServiceInfo(name, newHbService);
}
if (heartbeatId != null) {
addToHeartbeatIdList(newServiceInfo);
newServiceInfo.getService().setHeartbeatId(heartbeatId);
}
addServicePanel(newServiceInfo, pos, reloadNode);
return newServiceInfo;
}
/**
* Adds new service to the specified position. If position is null, it
* will be computed later. ReloadNode specifies if the node in
* the menu should be reloaded and get uptodate.
*/
public void addServicePanel(final ServiceInfo newServiceInfo,
final Point2D pos,
final boolean reloadNode) {
newServiceInfo.getService().setHeartbeatClass(
newServiceInfo.getHeartbeatService().getHeartbeatClass());
if (!heartbeatGraph.addResource(newServiceInfo, null, pos)) {
addNameToServiceInfoHash(newServiceInfo);
final DefaultMutableTreeNode newServiceNode =
new DefaultMutableTreeNode(newServiceInfo);
newServiceInfo.setNode(newServiceNode);
servicesNode.add(newServiceNode);
if (reloadNode) {
/* show it */
reload(servicesNode);
reload(newServiceNode);
}
//heartbeatGraph.scale();
}
heartbeatGraph.reloadServiceMenus();
}
/**
* Returns 'add service' list for graph popup menu.
*/
public List<HeartbeatService> getAddServiceList(final String cl) {
return globalGetAddServiceList(cl);
}
/**
* Returns background popup. Click on background represents cluster as
* whole.
*/
public List<UpdatableItem> createPopup() {
final List<UpdatableItem> items = new ArrayList<UpdatableItem>();
final MyMenuItem removeMenuItem = new MyMenuItem(
Tools.getString(
"ClusterBrowser.Hb.RemoveAllServices"),
REMOVE_ICON) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
return !getExistingServiceList().isEmpty();
}
public void action() {
if (Tools.confirmDialog(
Tools.getString(
"ClusterBrowser.confirmRemoveAllServices.Title"),
Tools.getString(
"ClusterBrowser.confirmRemoveAllServices.Description"),
Tools.getString(
"ClusterBrowser.confirmRemoveAllServices.Yes"),
Tools.getString(
"ClusterBrowser.confirmRemoveAllServices.No"))) {
for (ServiceInfo si : getExistingServiceList()) {
si.removeMyselfNoConfirm();
}
heartbeatGraph.getVisualizationViewer().repaint();
}
}
};
items.add((UpdatableItem) removeMenuItem);
registerMenuItem((UpdatableItem) removeMenuItem);
/* add group */
final MyMenuItem addGroupMenuItem =
new MyMenuItem(Tools.getString("ClusterBrowser.Hb.AddGroup"),
null,
null) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
return true;
}
public void action() {
final StringInfo gi = new StringInfo(HB_GROUP_NAME,
HB_GROUP_NAME);
addServicePanel(heartbeatXML.getHbGroup(), getPos(), true, null);
heartbeatGraph.getVisualizationViewer().repaint();
}
};
items.add((UpdatableItem) addGroupMenuItem);
registerMenuItem((UpdatableItem) addGroupMenuItem);
/* add service */
final MyMenu addServiceMenuItem = new MyMenu(
Tools.getString("ClusterBrowser.Hb.AddService")) {
private static final long serialVersionUID = 1L;
public void update() {
super.update();
removeAll();
Point2D pos = getPos();
final HeartbeatService fsService =
heartbeatXML.getHbService("Filesystem",
"ocf");
if (fsService != null) { /* just skip it, if it is not*/
final MyMenuItem fsMenuItem =
new MyMenuItem(fsService.getMenuName()) {
private static final long serialVersionUID = 1L;
public void action() {
getPopup().setVisible(false);
addServicePanel(fsService,
getPos(),
true, null);
heartbeatGraph.getVisualizationViewer().repaint();
}
};
fsMenuItem.setPos(pos);
add(fsMenuItem);
}
final HeartbeatService ipService =
heartbeatXML.getHbService("IPaddr2",
"ocf");
if (ipService != null) { /* just skip it, if it is not*/
final MyMenuItem ipMenuItem =
new MyMenuItem(ipService.getMenuName()) {
private static final long serialVersionUID = 1L;
public void action() {
getPopup().setVisible(false);
addServicePanel(ipService,
getPos(),
true, null);
heartbeatGraph.getVisualizationViewer().repaint();
}
};
ipMenuItem.setPos(pos);
add(ipMenuItem);
}
for (final String cl : HB_CLASSES) {
final MyMenu classItem =
new MyMenu(HB_CLASS_MENU.get(cl));
DefaultListModel m = new DefaultListModel();
for (final HeartbeatService s : getAddServiceList(cl)) {
final MyMenuItem mmi =
new MyMenuItem(s.getMenuName()) {
private static final long serialVersionUID = 1L;
public void action() {
getPopup().setVisible(false);
addServicePanel(s, getPos(), true, null);
heartbeatGraph.repaint();
}
};
mmi.setPos(pos);
m.addElement(mmi);
}
classItem.add(Tools.getScrollingMenu(classItem, m));
add(classItem);
}
}
};
items.add((UpdatableItem) addServiceMenuItem);
registerMenuItem((UpdatableItem) addServiceMenuItem);
/* view logs */
final MyMenuItem viewLogsItem =
new MyMenuItem(Tools.getString("ClusterBrowser.Hb.ViewLogs"),
null,
null) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
return true;
}
public void action() {
ClusterLogs l = new ClusterLogs(getCluster());
l.showDialog();
}
};
items.add((UpdatableItem) viewLogsItem);
registerMenuItem((UpdatableItem) viewLogsItem);
return items;
}
/**
* Return list of all services.
*/
public List<ServiceInfo> getExistingServiceList() {
final List<ServiceInfo> existingServiceList =
new ArrayList<ServiceInfo>();
for (final String name : nameToServiceInfoHash.keySet()) {
final Map<String, ServiceInfo> idHash =
nameToServiceInfoHash.get(name);
for (final String id : idHash.keySet()) {
final ServiceInfo si = idHash.get(id);
existingServiceList.add(si);
}
}
return existingServiceList;
}
}
/**
* Returns nw hb connection info object. This is called from heartbeat
* graph.
*/
public final HbConnectionInfo getNewHbConnectionInfo(final ServiceInfo p,
final ServiceInfo si) {
return new HbConnectionInfo(p, si);
}
/**
* This class describes a connection between two heartbeat services.
* It can be order, colocation or both. Colocation although technically
* don't have child, parent relationship, they are stored as such.
*/
public class HbConnectionInfo extends Info {
/** Cache for the info panel. */
private JComponent infoPanel = null;
/** Connected parent service. */
private ServiceInfo serviceInfoParent;
/** Connected child service. */
private ServiceInfo serviceInfo;
/**
* Prepares a new <code>HbConnectionInfo</code> object.
*/
public HbConnectionInfo(final ServiceInfo serviceInfoParent,
final ServiceInfo serviceInfo) {
super("HbConnectionInfo");
this.serviceInfoParent = serviceInfoParent;
this.serviceInfo = serviceInfo;
}
/**
* Returns parent that is connected to this service with constraint.
*/
public final ServiceInfo getServiceInfoParent() {
return serviceInfoParent;
}
/**
* Returns service info object of the child in this connection.
*/
public final ServiceInfo getServiceInfo() {
return serviceInfo;
}
/**
* Returns heartbeat graphical view.
*/
public final JPanel getGraphicalView() {
return heartbeatGraph.getGraphPanel();
}
/**
* Returns info panel for hb connection (order and/or colocation
* constraint.
*/
public final JComponent getInfoPanel() {
if (infoPanel != null) {
return infoPanel;
}
final JPanel buttonPanel = new JPanel(new BorderLayout());
buttonPanel.setBackground(STATUS_BACKGROUND);
buttonPanel.setMinimumSize(new Dimension(0, 50));
buttonPanel.setPreferredSize(new Dimension(0, 50));
buttonPanel.setMaximumSize(new Dimension(Short.MAX_VALUE, 50));
/* Actions */
final JMenuBar mb = new JMenuBar();
mb.setBackground(PANEL_BACKGROUND);
final JMenu serviceCombo = getActionsMenu();
updateMenus(null);
mb.add(serviceCombo);
buttonPanel.add(mb, BorderLayout.EAST);
infoPanel = new JPanel();
infoPanel.setBackground(PANEL_BACKGROUND);
infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));
infoPanel.add(buttonPanel);
infoPanel.add(Box.createVerticalGlue());
infoPanel.setMinimumSize(new Dimension(
Tools.getDefaultInt("HostBrowser.ResourceInfoArea.Width"),
Tools.getDefaultInt("HostBrowser.ResourceInfoArea.Height")
));
infoPanel.setPreferredSize(new Dimension(
Tools.getDefaultInt("HostBrowser.ResourceInfoArea.Width"),
Tools.getDefaultInt("HostBrowser.ResourceInfoArea.Height")
));
return infoPanel;
}
/**
* Creates popup menu for heartbeat order and colocation dependencies.
* These are the edges in the graph.
*/
public final List<UpdatableItem> createPopup() {
final List<UpdatableItem> items = new ArrayList<UpdatableItem>();
final HbConnectionInfo thisClass = this;
final MyMenuItem removeEdgeItem = new MyMenuItem(
Tools.getString("ClusterBrowser.Hb.RemoveEdge"),
REMOVE_ICON,
Tools.getString("ClusterBrowser.Hb.RemoveEdge.ToolTip")
) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
return true;
}
public void action() {
heartbeatGraph.removeConnection(thisClass);
}
};
registerMenuItem(removeEdgeItem);
items.add(removeEdgeItem);
/* remove/add order */
final MyMenuItem removeOrderItem =
new MyMenuItem(Tools.getString("ClusterBrowser.Hb.RemoveOrder"),
REMOVE_ICON,
Tools.getString("ClusterBrowser.Hb.RemoveOrder.ToolTip"),
Tools.getString("ClusterBrowser.Hb.AddOrder"),
null,
Tools.getString("ClusterBrowser.Hb.AddOrder.ToolTip")) {
private static final long serialVersionUID = 1L;
public boolean predicate() {
return heartbeatGraph.isOrder(thisClass);
}
public boolean enablePredicate() {
return true;
}
public void action() {
if (this.getText().equals(Tools.getString(
"ClusterBrowser.Hb.RemoveOrder"))) {
heartbeatGraph.removeOrder(thisClass);
} else {
heartbeatGraph.addOrder(thisClass);
}
}
};
registerMenuItem(removeOrderItem);
items.add(removeOrderItem);
/* remove/add colocation */
final MyMenuItem removeColocationItem =
new MyMenuItem(
Tools.getString("ClusterBrowser.Hb.RemoveColocation"),
REMOVE_ICON,
Tools.getString(
"ClusterBrowser.Hb.RemoveColocation.ToolTip"),
Tools.getString("ClusterBrowser.Hb.AddColocation"),
null,
Tools.getString(
"ClusterBrowser.Hb.AddColocation.ToolTip")
) {
private static final long serialVersionUID = 1L;
public boolean predicate() {
//return edgeIsColocationList.contains(edge);
return heartbeatGraph.isColocation(thisClass);
}
public boolean enablePredicate() {
return true;
}
public void action() {
if (this.getText().equals(Tools.getString(
"ClusterBrowser.Hb.RemoveColocation"))) {
heartbeatGraph.removeColocation(thisClass);
} else {
heartbeatGraph.addColocation(thisClass);
}
}
};
registerMenuItem(removeColocationItem);
items.add(removeColocationItem);
/* reverse order */
final MyMenuItem reverseOrderItem =
new MyMenuItem(
Tools.getString("ClusterBrowser.Hb.ReverseOrder"),
null,
Tools.getString("ClusterBrowser.Hb.ReverseOrder.ToolTip")) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
return heartbeatGraph.isOrder(thisClass);
}
public void action() {
heartbeatGraph.removeOrder(thisClass);
ServiceInfo t = serviceInfo;
serviceInfo = serviceInfoParent;
serviceInfoParent = t;
heartbeatGraph.addOrder(thisClass);
}
};
registerMenuItem(reverseOrderItem);
items.add(reverseOrderItem);
return items;
}
}
/**
* This class provides drbd info. For one it shows the editable global
* drbd config, but if a drbd block device is selected it forwards to the
* block device info, which is defined in HostBrowser.java.
*/
public class DrbdInfo extends EditableInfo {
/** Selected block device. */
private BlockDevInfo selectedBD = null;
/** Cache for the info panel. */
private JComponent infoPanel = null;
/**
* Prepares a new <code>DrbdInfo</code> object.
*
* @param name
* name that will be shown in the tree
*/
public DrbdInfo(final String name) {
super(name);
setResource(new Resource(name));
drbdGraph.setDrbdInfo(this);
initApplyButton();
}
/**
* Returns menu drbd icon.
*/
public final ImageIcon getMenuIcon() {
return null;
}
/**
* Sets selected block device.
*/
public final void setSelectedNode(final BlockDevInfo bdi) {
this.selectedBD = bdi;
}
/**
* Gets combo box for paremeter in te global config. usage-count is
* disabled.
*/
protected final GuiComboBox getParamComboBox(final String param,
final String prefix,
final int width) {
final GuiComboBox cb = super.getParamComboBox(param, prefix, width);
if ("usage-count".equals(param)) {
cb.setEnabled(false);
}
return cb;
}
/**
* Creates drbd config.
*/
public final void createDrbdConfig()
throws Exceptions.DrbdConfigException {
final StringBuffer config = new StringBuffer(160);
config.append("## generated by drbd-gui ");
config.append(Tools.getRelease());
config.append("\n\n");
final StringBuffer global = new StringBuffer(80);
final String[] params = drbdXML.getGlobalParams();
global.append("global {\n");
for (String param : params) {
if ("usage-count".equals(param)) {
final String value = "yes";
global.append("\t\t");
global.append(param);
global.append('\t');
global.append(Tools.escapeConfig(value));
global.append(";\n");
} else {
String value = getResource().getValue(param);
if (value == null && "usage-count".equals(param)) {
value = "yes";
}
if (value == null) {
continue;
}
if (!value.equals(drbdXML.getParamDefault(param))) {
global.append("\t\t");
global.append(param);
global.append('\t');
global.append(Tools.escapeConfig(value));
global.append(";\n");
}
}
}
global.append("}\n");
if (global.length() > 0) {
config.append(global);
}
final Host[] hosts = cluster.getHostsArray();
for (Host host : hosts) {
final StringBuffer resConfig = new StringBuffer("");
final Enumeration drbdResources = drbdNode.children();
while (drbdResources.hasMoreElements()) {
DefaultMutableTreeNode n =
(DefaultMutableTreeNode) drbdResources.nextElement();
final DrbdResourceInfo drbdRes =
(DrbdResourceInfo) n.getUserObject();
if (drbdRes.resourceInHost(host)) {
resConfig.append('\n');
try {
resConfig.append(drbdRes.drbdResourceConfig());
} catch (Exceptions.DrbdConfigException dce) {
throw dce;
}
}
}
host.getSSH().createConfig(config.toString()
+ resConfig.toString(),
"drbd.conf",
"/etc/",
"0600");
//DRBD.adjust(host, "all"); // it can't be here
}
}
/**
* Returns lsit of all parameters as an array.
*/
public final String[] getParametersFromXML() {
return drbdXML.getGlobalParams();
}
/**
* Checks parameter's new value if it is correct.
*/
protected final boolean checkParam(final String param,
final String newValue) {
return drbdXML.checkParam(param, newValue);
}
/**
* Returns default value of the parameter.
*/
protected final String getParamDefault(final String param) {
return drbdXML.getParamDefault(param);
}
/**
* Possible choices for pulldown menus, or null if it is not a pull
* down menu.
*/
protected final Object[] getParamPossibleChoices(final String param) {
return drbdXML.getPossibleChoices(param);
}
/**
* Returns paramter short description, for user visible text.
*/
protected final String getParamShortDesc(final String param) {
return drbdXML.getParamShortDesc(param);
}
/**
* Returns parameter long description, for tool tips.
*/
protected final String getParamLongDesc(final String param) {
return drbdXML.getParamLongDesc(param);
}
/**
* Returns section to which this parameter belongs.
* This is used for grouping in the info panel.
*/
protected final String getSection(final String param) {
return drbdXML.getSection(param);
}
/**
* Returns whether the parameter is required.
*/
protected final boolean isRequired(final String param) {
return drbdXML.isRequired(param);
}
/**
* Returns whether the parameter is of the integer type.
*/
protected final boolean isInteger(final String param) {
return drbdXML.isInteger(param);
}
/**
* Returns whether the parameter is of the time type.
*/
protected final boolean isTimeType(final String param) {
/* not required */
return false;
}
/**
* Returns true if unit has prefix.
*/
protected final boolean hasUnitPrefix(final String param) {
return drbdXML.hasUnitPrefix(param);
}
/**
* Returns long name of the unit, for user visible uses.
*/
protected final String getUnitLong(final String param) {
return drbdXML.getUnitLong(param);
}
/**
* Returns the default unit of the parameter.
*/
protected final String getDefaultUnit(final String param) {
return drbdXML.getDefaultUnit(param);
}
/**
* Returns whether the parameter is check box.
*/
protected final boolean isCheckBox(final String param) {
final String type = drbdXML.getParamType(param);
if (type == null) {
return false;
}
if (DRBD_RES_BOOL_TYPE_NAME.equals(type)) {
return true;
}
return false;
}
/**
* Returns parameter type, boolean etc.
*/
protected final String getParamType(final String param) {
return drbdXML.getParamType(param);
}
/**
* Applies changes made in the info panel by user.
*/
public final void apply() {
final String[] params = getParametersFromXML();
SwingUtilities.invokeLater(new Runnable() {
public void run() {
applyButton.setEnabled(false);
}
});
storeComboBoxValues(params);
}
/**
* Returns info panel for drbd. If a block device was selected, its
* info panel is shown.
*/
public final JComponent getInfoPanel() {
if (selectedBD != null) { /* block device is not in drbd */
return selectedBD.getInfoPanel();
}
if (infoPanel != null) {
return infoPanel;
}
final JPanel mainPanel = new JPanel();
if (drbdXML == null) {
mainPanel.add(new JLabel("drbd info not available"));
return mainPanel;
}
mainPanel.setBackground(PANEL_BACKGROUND);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));
final JPanel buttonPanel = new JPanel(new BorderLayout());
buttonPanel.setBackground(STATUS_BACKGROUND);
buttonPanel.setMinimumSize(new Dimension(0, 50));
buttonPanel.setPreferredSize(new Dimension(0, 50));
buttonPanel.setMaximumSize(new Dimension(Short.MAX_VALUE, 50));
final JPanel optionsPanel = new JPanel();
optionsPanel.setBackground(PANEL_BACKGROUND);
optionsPanel.setLayout(new BoxLayout(optionsPanel,
BoxLayout.Y_AXIS));
optionsPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
final JPanel extraOptionsPanel = new JPanel();
extraOptionsPanel.setBackground(EXTRA_PANEL_BACKGROUND);
extraOptionsPanel.setLayout(new BoxLayout(extraOptionsPanel,
BoxLayout.Y_AXIS));
extraOptionsPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
mainPanel.add(buttonPanel);
/* expert mode */
buttonPanel.add(Tools.expertModeButton(extraOptionsPanel),
BorderLayout.WEST);
/* Actions */
final JMenuBar mb = new JMenuBar();
mb.setBackground(PANEL_BACKGROUND);
final JMenu serviceCombo = getActionsMenu();
updateMenus(null);
mb.add(serviceCombo);
buttonPanel.add(mb, BorderLayout.EAST);
final String[] params = getParametersFromXML();
addParams(optionsPanel,
extraOptionsPanel,
params,
Tools.getDefaultInt("ClusterBrowser.DrbdResLabelWidth"),
Tools.getDefaultInt("ClusterBrowser.DrbdResFieldWidth")
);
applyButton.addActionListener(
new ActionListener() {
public void actionPerformed(final ActionEvent e) {
Thread thread = new Thread(new Runnable() {
public void run() {
hbStatusLock();
apply();
hbStatusUnlock();
}
});
thread.start();
}
}
);
/* apply button */
addApplyButton(mainPanel);
applyButton.setEnabled(checkResourceFields(null, params));
mainPanel.add(optionsPanel);
mainPanel.add(extraOptionsPanel);
infoPanel = new JPanel();
infoPanel.setBackground(PANEL_BACKGROUND);
infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));
infoPanel.add(buttonPanel);
infoPanel.add(new JScrollPane(mainPanel));
infoPanel.add(Box.createVerticalGlue());
return infoPanel;
}
/**
* Clears info panel cache.
* TODO: should select something.
*/
public final boolean selectAutomaticallyInTreeMenu() {
return infoPanel == null;
}
/**
* Returns drbd graph in a panel.
*/
public final JPanel getGraphicalView() {
if (selectedBD != null) {
drbdGraph.pickBlockDevice(selectedBD);
}
return drbdGraph.getGraphPanel();
}
/**
* Selects and highlights this node. This function is overwritten
* because block devices don't have here their own node, but
* views change depending on selectedNode variable.
*/
public final void selectMyself() {
if (selectedBD == null || !selectedBD.getBlockDevice().isDrbd()) {
reload(getNode());
nodeChanged(getNode());
} else {
reload(selectedBD.getNode());
nodeChanged(selectedBD.getNode());
}
}
/**
* Returns new drbd resource index, the one that is not used .
*/
private int getNewDrbdResourceIndex() {
final Iterator it = drbdResHash.keySet().iterator();
int index = -1;
while (it.hasNext()) {
final String name = (String) it.next();
// TODO: should not assume r0
final Pattern p = Pattern.compile("^" + "r" + "(\\d+)$");
final Matcher m = p.matcher(name);
if (m.matches()) {
final int i = Integer.parseInt(m.group(1));
if (i > index) {
index = i;
}
}
}
return index + 1;
}
/**
* Adds drbd resource. If resource name and drbd device are null.
* They will be created with first unused index. E.g. r0, r1 ...
* /dev/drbd0, /dev/drbd1 ... etc.
*
* @param name
* resource name.
* @param drbdDevStr
* drbd device like /dev/drbd0
* @param bd1
* block device
* @param bd2
* block device
* @param interactive
* whether dialog box will be displayed
*/
public final void addDrbdResource(String name,
String drbdDevStr,
final BlockDevInfo bd1,
final BlockDevInfo bd2,
final boolean interactive) {
DrbdResourceInfo dri;
if (bd1 == null || bd2 == null) {
return;
}
if (name == null && drbdDevStr == null) {
int index = getNewDrbdResourceIndex();
name = "r" + Integer.toString(index);
drbdDevStr = "/dev/drbd" + Integer.toString(index);
/* search for next available drbd device */
while (drbdDevHash.containsKey(drbdDevStr)) {
index++;
drbdDevStr = "/dev/drbd" + Integer.toString(index);
}
dri = new DrbdResourceInfo(name, drbdDevStr, bd1, bd2);
} else {
dri = new DrbdResourceInfo(name, drbdDevStr, bd1, bd2);
final String[] sections = drbdXML.getSections();
for (String section : sections) {
final String[] params = drbdXML.getSectionParams(section);
for (String param : params) {
String value =
drbdXML.getConfigValue(name, section, param);
if ("".equals(value)) {
value = drbdXML.getParamDefault(param);
}
dri.getDrbdResource().setValue(param, value);
}
}
dri.getDrbdResource().setCommited(true);
}
/* We want next port number on both devices to be the same,
* although other port numbers may not be the same on both. */
final int viPort1 = bd1.getNextVIPort();
final int viPort2 = bd2.getNextVIPort();
final int viPort;
if (viPort1 > viPort2) {
viPort = viPort1;
} else {
viPort = viPort2;
}
bd1.setDefaultVIPort(viPort + 1);
bd2.setDefaultVIPort(viPort + 1);
dri.getDrbdResource().setDefaultValue(DRBD_RES_PARAM_NAME,
name);
dri.getDrbdResource().setDefaultValue(DRBD_RES_PARAM_DEV,
drbdDevStr);
drbdResHash.put(name, dri);
drbdDevHash.put(drbdDevStr, dri);
if (bd1 != null) {
bd1.setDrbd(true);
bd1.setDrbdResourceInfo(dri);
bd1.setInfoPanel(null); /* reload panel */
bd1.selectMyself();
}
if (bd2 != null) {
bd2.setDrbd(true);
bd2.setDrbdResourceInfo(dri);
bd2.setInfoPanel(null); /* reload panel */
bd2.selectMyself();
}
final DefaultMutableTreeNode drbdResourceNode =
new DefaultMutableTreeNode(dri);
dri.setNode(drbdResourceNode);
drbdNode.add(drbdResourceNode);
final DefaultMutableTreeNode drbdBDNode1 =
new DefaultMutableTreeNode(bd1);
bd1.setNode(drbdBDNode1);
final DefaultMutableTreeNode drbdBDNode2 =
new DefaultMutableTreeNode(bd2);
bd2.setNode(drbdBDNode2);
drbdResourceNode.add(drbdBDNode1);
drbdResourceNode.add(drbdBDNode2);
//reload(getNode());
//reload(drbdResourceNode);
drbdGraph.addDrbdResource(dri, bd1, bd2);
final DrbdResourceInfo driF = dri;
if (interactive) {
final Thread thread = new Thread(
new Runnable() {
public void run() {
AddDrbdConfigDialog adrd
= new AddDrbdConfigDialog(driF);
adrd.showDialogs();
if (adrd.isCanceled()) {
driF.removeMyselfNoConfirm();
return;
}
updateCommonBlockDevices();
drbdXML.update(bd1.getHost());
drbdXML.update(bd2.getHost());
resetFilesystems();
} });
thread.start();
} else {
resetFilesystems();
}
}
}
/**
* This class holds all hosts that are added to the GUI as opposite to all
* hosts in a cluster.
*/
private class AllHostsInfo extends Info {
/** infoPanel cache. */
private JPanel infoPanel = null;
/**
* Creates a new AllHostsInfo instance.
*/
public AllHostsInfo() {
super(Tools.getString("ClusterBrowser.AllHosts"));
}
/**
* Returns info panel of all hosts menu item. If a host is selected,
* its tab is selected.
*/
public final JComponent getInfoPanel() {
if (infoPanel != null) {
return infoPanel;
}
infoPanel = new JPanel();
infoPanel.setLayout(new BoxLayout(infoPanel, BoxLayout.Y_AXIS));
infoPanel.setBackground(PANEL_BACKGROUND);
final JPanel bPanel =
new JPanel(new BorderLayout());
bPanel.setMaximumSize(new Dimension(10000, 60));
bPanel.setBackground(STATUS_BACKGROUND);
final JMenuBar mb = new JMenuBar();
mb.setBackground(PANEL_BACKGROUND);
final JMenu actionsMenu = getActionsMenu();
updateMenus(null);
mb.add(actionsMenu);
bPanel.add(mb, BorderLayout.EAST);
infoPanel.add(bPanel);
return infoPanel;
}
/**
* Creates the popup for all hosts.
*/
public final List<UpdatableItem> createPopup() {
final List<UpdatableItem>items = new ArrayList<UpdatableItem>();
/* host wizard */
final MyMenuItem newHostWizardItem =
new MyMenuItem(Tools.getString("EmptyBrowser.NewHostWizard"),
HOST_ICON,
null) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
return true;
}
public void action() {
final AddHostDialog dialog = new AddHostDialog();
dialog.showDialogs();
}
};
items.add(newHostWizardItem);
registerMenuItem(newHostWizardItem);
Tools.getGUIData().registerAddHostButton(newHostWizardItem);
return items;
}
}
}
| true | true | public List<UpdatableItem> createPopup() {
final List<UpdatableItem> items = new ArrayList<UpdatableItem>();
/* remove service */
final MyMenuItem removeMenuItem = new MyMenuItem(
Tools.getString(
"ClusterBrowser.Hb.RemoveService"),
REMOVE_ICON) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
// TODO: if it was migrated
return !getService().isRemoved();
}
public void action() {
removeMyself();
heartbeatGraph.getVisualizationViewer().repaint();
}
};
items.add((UpdatableItem) removeMenuItem);
registerMenuItem((UpdatableItem) removeMenuItem);
if (groupInfo == null) {
/* add new group and dependency*/
final MyMenuItem addGroupMenuItem =
new MyMenuItem(Tools.getString(
"ClusterBrowser.Hb.AddDependentGroup"),
null,
null) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
return !getService().isRemoved();
}
public void action() {
final StringInfo gi = new StringInfo(HB_GROUP_NAME,
HB_GROUP_NAME);
addServicePanel(heartbeatXML.getHbGroup(), getPos(), true);
heartbeatGraph.getVisualizationViewer().repaint();
}
};
items.add((UpdatableItem) addGroupMenuItem);
registerMenuItem((UpdatableItem) addGroupMenuItem);
/* add new service and dependency*/
final MyMenu addServiceMenuItem = new MyMenu(
Tools.getString(
"ClusterBrowser.Hb.AddDependency")) {
private static final long serialVersionUID = 1L;
public void update() {
super.update();
removeAll();
final Point2D pos = getPos();
final HeartbeatService fsService =
heartbeatXML.getHbService("Filesystem",
"ocf");
if (fsService != null) { /* just skip it, if it is not*/
final MyMenuItem fsMenuItem =
new MyMenuItem(fsService.getMenuName()) {
private static final long serialVersionUID = 1L;
public void action() {
getPopup().setVisible(false);
addServicePanel(fsService,
getPos(),
true);
heartbeatGraph.getVisualizationViewer().repaint();
}
};
fsMenuItem.setPos(pos);
add(fsMenuItem);
}
final HeartbeatService ipService =
heartbeatXML.getHbService("IPaddr2",
"ocf");
if (ipService != null) { /* just skip it, if it is not*/
final MyMenuItem ipMenuItem =
new MyMenuItem(ipService.getMenuName()) {
private static final long serialVersionUID = 1L;
public void action() {
getPopup().setVisible(false);
addServicePanel(ipService,
getPos(),
true);
heartbeatGraph.getVisualizationViewer().repaint();
}
};
ipMenuItem.setPos(pos);
add(ipMenuItem);
}
for (final String cl : HB_CLASSES) {
final MyMenu classItem =
new MyMenu(HB_CLASS_MENU.get(cl));
DefaultListModel m = new DefaultListModel();
//Point2D pos = getPos();
for (final HeartbeatService hbService : getAddServiceList(cl)) {
final MyMenuItem mmi =
new MyMenuItem(hbService.getMenuName()) {
private static final long serialVersionUID = 1L;
public void action() {
getPopup().setVisible(false);
addServicePanel(hbService,
getPos(),
true);
heartbeatGraph.getVisualizationViewer().repaint();
}
};
mmi.setPos(pos);
m.addElement(mmi);
}
classItem.add(Tools.getScrollingMenu(classItem, m));
add(classItem);
}
}
};
items.add((UpdatableItem) addServiceMenuItem);
registerMenuItem((UpdatableItem) addServiceMenuItem);
/* add existing service dependency*/
final ServiceInfo thisClass = this;
final MyMenu existingServiceMenuItem =
new MyMenu(
Tools.getString(
"ClusterBrowser.Hb.AddStartBefore")) {
private static final long serialVersionUID = 1L;
public void update() {
super.update();
removeAll();
DefaultListModel m = new DefaultListModel();
for (final ServiceInfo asi : getExistingServiceList(thisClass)) {
final MyMenuItem mmi =
new MyMenuItem(asi.toString()) {
private static final long serialVersionUID = 1L;
public void action() {
final Thread thread = new Thread(
new Runnable() {
public void run() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
getPopup().setVisible(false);
}
});
addServicePanel(asi, null, true);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
repaint();
}
});
}
});
thread.start();
}
};
m.addElement(mmi);
}
add(Tools.getScrollingMenu(this, m));
}
};
items.add((UpdatableItem) existingServiceMenuItem);
registerMenuItem((UpdatableItem) existingServiceMenuItem);
} else { /* group service */
final MyMenuItem moveUpMenuItem =
new MyMenuItem(Tools.getString(
"ClusterBrowser.Hb.ResGrpMoveUp"),
null, // upIcon,
null) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
// TODO: don't if it is up
return getService().isAvailable();
}
public void action() {
moveGroupResUp();
}
};
items.add(moveUpMenuItem);
registerMenuItem(moveUpMenuItem);
/* move down */
final MyMenuItem moveDownMenuItem =
new MyMenuItem(Tools.getString(
"ClusterBrowser.Hb.ResGrpMoveDown"),
null, // TODO: downIcon,
null) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
// TODO: don't if it is down
return getService().isAvailable();
}
public void action() {
moveGroupResDown();
}
};
items.add(moveDownMenuItem);
registerMenuItem(moveDownMenuItem);
}
/* start resource */
final MyMenuItem startMenuItem =
new MyMenuItem(
Tools.getString("ClusterBrowser.Hb.StartResource"),
START_ICON,
Tools.getString("ClusterBrowser.Hb.StartResource.ToolTip")
) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
return getService().isAvailable() && !isStarted();
}
public void action() {
startResource();
}
};
items.add((UpdatableItem) startMenuItem);
registerMenuItem((UpdatableItem) startMenuItem);
/* stop resource */
final MyMenuItem stopMenuItem =
new MyMenuItem(
Tools.getString("ClusterBrowser.Hb.StopResource"),
STOP_ICON,
Tools.getString("ClusterBrowser.Hb.StopResource.ToolTip")
) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
return getService().isAvailable() && !isStopped();
}
public void action() {
stopResource();
}
};
items.add((UpdatableItem) stopMenuItem);
registerMenuItem((UpdatableItem) stopMenuItem);
/* manage resource */
final MyMenuItem manageMenuItem =
new MyMenuItem(
Tools.getString("ClusterBrowser.Hb.ManageResource"),
START_ICON, // TODO: icons
Tools.getString("ClusterBrowser.Hb.ManageResource.ToolTip"),
Tools.getString("ClusterBrowser.Hb.UnmanageResource"),
STOP_ICON, // TODO: icons
Tools.getString("ClusterBrowser.Hb.UnmanageResource.ToolTip")
) {
private static final long serialVersionUID = 1L;
public boolean predicate() {
return !isManaged();
}
public boolean enablePredicate() {
return getService().isAvailable();
}
public void action() {
if (this.getText().equals(Tools.getString(
"ClusterBrowser.Hb.ManageResource"))) {
setManaged(true);
} else {
setManaged(false);
}
}
};
items.add((UpdatableItem) manageMenuItem);
registerMenuItem((UpdatableItem) manageMenuItem);
/* migrate resource */
for (final String hostName : getHostNames()) {
final MyMenuItem migrateMenuItem =
new MyMenuItem(
Tools.getString(
"ClusterBrowser.Hb.MigrateResource")
+ " " + hostName,
MIGRATE_ICON,
Tools.getString(
"ClusterBrowser.Hb.MigrateResource.ToolTip"),
Tools.getString(
"ClusterBrowser.Hb.MigrateResource")
+ " " + hostName + " (inactive)",
MIGRATE_ICON,
Tools.getString(
"ClusterBrowser.Hb.MigrateResource.ToolTip")
) {
private static final long serialVersionUID = 1L;
public boolean predicate() {
return isActiveNode(hostName);
}
public boolean enablePredicate() {
String runningOnNode = getRunningOnNode();
if (runningOnNode != null) {
runningOnNode = runningOnNode.toLowerCase();
}
return getService().isAvailable()
&& !hostName.toLowerCase().equals(
runningOnNode)
&& isActiveNode(hostName);
}
public void action() {
migrateResource(hostName);
}
};
items.add((UpdatableItem) migrateMenuItem);
registerMenuItem((UpdatableItem) migrateMenuItem);
}
/* unmigrate resource */
final MyMenuItem unmigrateMenuItem =
new MyMenuItem(Tools.getString(
"ClusterBrowser.Hb.UnmigrateResource")) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
// TODO: if it was migrated
return getService().isAvailable();
}
public void action() {
unmigrateResource();
}
};
items.add((UpdatableItem) unmigrateMenuItem);
registerMenuItem((UpdatableItem) unmigrateMenuItem);
/* clean up resource */
final MyMenuItem cleanupMenuItem =
new MyMenuItem(Tools.getString(
"ClusterBrowser.Hb.CleanUpResource")) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
return getService().isAvailable();
}
public void action() {
cleanupResource();
}
};
items.add((UpdatableItem) cleanupMenuItem);
registerMenuItem((UpdatableItem) cleanupMenuItem);
/* view log */
final MyMenuItem viewLogMenu = new MyMenuItem(
Tools.getString("ClusterBrowser.Hb.ViewServiceLog"),
null,
null) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
return !getService().isNew();
}
public void action() {
final Thread thread = new Thread(
new Runnable() {
public void run() {
ServiceLogs l =
new ServiceLogs(getCluster(),
getService().getHeartbeatId());
l.showDialog();
}
});
thread.start();
}
};
registerMenuItem(viewLogMenu);
items.add(viewLogMenu);
return items;
}
| public List<UpdatableItem> createPopup() {
final List<UpdatableItem> items = new ArrayList<UpdatableItem>();
/* remove service */
final MyMenuItem removeMenuItem = new MyMenuItem(
Tools.getString(
"ClusterBrowser.Hb.RemoveService"),
REMOVE_ICON) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
// TODO: if it was migrated
return !getService().isRemoved();
}
public void action() {
removeMyself();
heartbeatGraph.getVisualizationViewer().repaint();
}
};
items.add((UpdatableItem) removeMenuItem);
registerMenuItem((UpdatableItem) removeMenuItem);
if (groupInfo == null) {
/* add new group and dependency*/
final MyMenuItem addGroupMenuItem =
new MyMenuItem(Tools.getString(
"ClusterBrowser.Hb.AddDependentGroup"),
null,
null) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
return !getService().isRemoved();
}
public void action() {
final StringInfo gi = new StringInfo(HB_GROUP_NAME,
HB_GROUP_NAME);
addServicePanel(heartbeatXML.getHbGroup(), getPos(), true);
heartbeatGraph.getVisualizationViewer().repaint();
}
};
items.add((UpdatableItem) addGroupMenuItem);
registerMenuItem((UpdatableItem) addGroupMenuItem);
/* add new service and dependency*/
final MyMenu addServiceMenuItem = new MyMenu(
Tools.getString(
"ClusterBrowser.Hb.AddDependency")) {
private static final long serialVersionUID = 1L;
public void update() {
super.update();
removeAll();
final Point2D pos = getPos();
final HeartbeatService fsService =
heartbeatXML.getHbService("Filesystem",
"ocf");
if (fsService != null) { /* just skip it, if it is not*/
final MyMenuItem fsMenuItem =
new MyMenuItem(fsService.getMenuName()) {
private static final long serialVersionUID = 1L;
public void action() {
getPopup().setVisible(false);
addServicePanel(fsService,
getPos(),
true);
heartbeatGraph.getVisualizationViewer().repaint();
}
};
fsMenuItem.setPos(pos);
add(fsMenuItem);
}
final HeartbeatService ipService =
heartbeatXML.getHbService("IPaddr2",
"ocf");
if (ipService != null) { /* just skip it, if it is not*/
final MyMenuItem ipMenuItem =
new MyMenuItem(ipService.getMenuName()) {
private static final long serialVersionUID = 1L;
public void action() {
getPopup().setVisible(false);
addServicePanel(ipService,
getPos(),
true);
heartbeatGraph.getVisualizationViewer().repaint();
}
};
ipMenuItem.setPos(pos);
add(ipMenuItem);
}
for (final String cl : HB_CLASSES) {
final MyMenu classItem =
new MyMenu(HB_CLASS_MENU.get(cl));
DefaultListModel m = new DefaultListModel();
//Point2D pos = getPos();
for (final HeartbeatService hbService : getAddServiceList(cl)) {
final MyMenuItem mmi =
new MyMenuItem(hbService.getMenuName()) {
private static final long serialVersionUID = 1L;
public void action() {
getPopup().setVisible(false);
addServicePanel(hbService,
getPos(),
true);
heartbeatGraph.getVisualizationViewer().repaint();
}
};
mmi.setPos(pos);
m.addElement(mmi);
}
classItem.add(Tools.getScrollingMenu(classItem, m));
add(classItem);
}
}
};
items.add((UpdatableItem) addServiceMenuItem);
registerMenuItem((UpdatableItem) addServiceMenuItem);
/* add existing service dependency*/
final ServiceInfo thisClass = this;
final MyMenu existingServiceMenuItem =
new MyMenu(
Tools.getString(
"ClusterBrowser.Hb.AddStartBefore")) {
private static final long serialVersionUID = 1L;
public void update() {
super.update();
removeAll();
DefaultListModel m = new DefaultListModel();
for (final ServiceInfo asi : getExistingServiceList(thisClass)) {
if (asi.getGroupInfo() != null) {
/* skip services that are in group. */
continue;
}
final MyMenuItem mmi =
new MyMenuItem(asi.toString()) {
private static final long serialVersionUID = 1L;
public void action() {
final Thread thread = new Thread(
new Runnable() {
public void run() {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
getPopup().setVisible(false);
}
});
addServicePanel(asi, null, true);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
repaint();
}
});
}
});
thread.start();
}
};
m.addElement(mmi);
}
add(Tools.getScrollingMenu(this, m));
}
};
items.add((UpdatableItem) existingServiceMenuItem);
registerMenuItem((UpdatableItem) existingServiceMenuItem);
} else { /* group service */
final MyMenuItem moveUpMenuItem =
new MyMenuItem(Tools.getString(
"ClusterBrowser.Hb.ResGrpMoveUp"),
null, // upIcon,
null) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
// TODO: don't if it is up
return getService().isAvailable();
}
public void action() {
moveGroupResUp();
}
};
items.add(moveUpMenuItem);
registerMenuItem(moveUpMenuItem);
/* move down */
final MyMenuItem moveDownMenuItem =
new MyMenuItem(Tools.getString(
"ClusterBrowser.Hb.ResGrpMoveDown"),
null, // TODO: downIcon,
null) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
// TODO: don't if it is down
return getService().isAvailable();
}
public void action() {
moveGroupResDown();
}
};
items.add(moveDownMenuItem);
registerMenuItem(moveDownMenuItem);
}
/* start resource */
final MyMenuItem startMenuItem =
new MyMenuItem(
Tools.getString("ClusterBrowser.Hb.StartResource"),
START_ICON,
Tools.getString("ClusterBrowser.Hb.StartResource.ToolTip")
) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
return getService().isAvailable() && !isStarted();
}
public void action() {
startResource();
}
};
items.add((UpdatableItem) startMenuItem);
registerMenuItem((UpdatableItem) startMenuItem);
/* stop resource */
final MyMenuItem stopMenuItem =
new MyMenuItem(
Tools.getString("ClusterBrowser.Hb.StopResource"),
STOP_ICON,
Tools.getString("ClusterBrowser.Hb.StopResource.ToolTip")
) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
return getService().isAvailable() && !isStopped();
}
public void action() {
stopResource();
}
};
items.add((UpdatableItem) stopMenuItem);
registerMenuItem((UpdatableItem) stopMenuItem);
/* manage resource */
final MyMenuItem manageMenuItem =
new MyMenuItem(
Tools.getString("ClusterBrowser.Hb.ManageResource"),
START_ICON, // TODO: icons
Tools.getString("ClusterBrowser.Hb.ManageResource.ToolTip"),
Tools.getString("ClusterBrowser.Hb.UnmanageResource"),
STOP_ICON, // TODO: icons
Tools.getString("ClusterBrowser.Hb.UnmanageResource.ToolTip")
) {
private static final long serialVersionUID = 1L;
public boolean predicate() {
return !isManaged();
}
public boolean enablePredicate() {
return getService().isAvailable();
}
public void action() {
if (this.getText().equals(Tools.getString(
"ClusterBrowser.Hb.ManageResource"))) {
setManaged(true);
} else {
setManaged(false);
}
}
};
items.add((UpdatableItem) manageMenuItem);
registerMenuItem((UpdatableItem) manageMenuItem);
/* migrate resource */
for (final String hostName : getHostNames()) {
final MyMenuItem migrateMenuItem =
new MyMenuItem(
Tools.getString(
"ClusterBrowser.Hb.MigrateResource")
+ " " + hostName,
MIGRATE_ICON,
Tools.getString(
"ClusterBrowser.Hb.MigrateResource.ToolTip"),
Tools.getString(
"ClusterBrowser.Hb.MigrateResource")
+ " " + hostName + " (inactive)",
MIGRATE_ICON,
Tools.getString(
"ClusterBrowser.Hb.MigrateResource.ToolTip")
) {
private static final long serialVersionUID = 1L;
public boolean predicate() {
return isActiveNode(hostName);
}
public boolean enablePredicate() {
String runningOnNode = getRunningOnNode();
if (runningOnNode != null) {
runningOnNode = runningOnNode.toLowerCase();
}
return getService().isAvailable()
&& !hostName.toLowerCase().equals(
runningOnNode)
&& isActiveNode(hostName);
}
public void action() {
migrateResource(hostName);
}
};
items.add((UpdatableItem) migrateMenuItem);
registerMenuItem((UpdatableItem) migrateMenuItem);
}
/* unmigrate resource */
final MyMenuItem unmigrateMenuItem =
new MyMenuItem(Tools.getString(
"ClusterBrowser.Hb.UnmigrateResource")) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
// TODO: if it was migrated
return getService().isAvailable();
}
public void action() {
unmigrateResource();
}
};
items.add((UpdatableItem) unmigrateMenuItem);
registerMenuItem((UpdatableItem) unmigrateMenuItem);
/* clean up resource */
final MyMenuItem cleanupMenuItem =
new MyMenuItem(Tools.getString(
"ClusterBrowser.Hb.CleanUpResource")) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
return getService().isAvailable();
}
public void action() {
cleanupResource();
}
};
items.add((UpdatableItem) cleanupMenuItem);
registerMenuItem((UpdatableItem) cleanupMenuItem);
/* view log */
final MyMenuItem viewLogMenu = new MyMenuItem(
Tools.getString("ClusterBrowser.Hb.ViewServiceLog"),
null,
null) {
private static final long serialVersionUID = 1L;
public boolean enablePredicate() {
return !getService().isNew();
}
public void action() {
final Thread thread = new Thread(
new Runnable() {
public void run() {
ServiceLogs l =
new ServiceLogs(getCluster(),
getService().getHeartbeatId());
l.showDialog();
}
});
thread.start();
}
};
registerMenuItem(viewLogMenu);
items.add(viewLogMenu);
return items;
}
|
diff --git a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestVersion.java b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestVersion.java
index 3106e02fa..291936928 100644
--- a/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestVersion.java
+++ b/openjpa-persistence-jdbc/src/test/java/org/apache/openjpa/persistence/jdbc/annotations/TestVersion.java
@@ -1,195 +1,195 @@
/*
* 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.openjpa.persistence.jdbc.annotations;
import javax.persistence.EntityManager;
import org.apache.openjpa.jdbc.conf.JDBCConfiguration;
import org.apache.openjpa.jdbc.meta.ClassMapping;
import org.apache.openjpa.jdbc.meta.strats.NoneVersionStrategy;
import org.apache.openjpa.persistence.test.SingleEMFTestCase;
/**
* Test for opt-lock
*
* @author Steve Kim
*/
public class TestVersion extends SingleEMFTestCase {
public void setUp() {
setUp(AnnoTest1.class, AnnoTest2.class, AnnoTest3.class, Flat1.class,
EmbedOwner.class, EmbedValue.class, CLEAR_TABLES);
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
AnnoTest1 test1 = new AnnoTest1();
test1.setPk(new Long(5));
test1.setBasic(50);
test1.setTransient(500);
em.persist(test1);
AnnoTest2 test2 = new AnnoTest2();
test2.setPk1(5);
test2.setPk2("bar");
test2.setBasic("50");
em.persist(test2);
AnnoTest3 test3 = new AnnoTest3();
test3.setPk(new Long(3));
test3.setBasic2(50);
em.persist(test3);
em.getTransaction().commit();
em.close();
}
public void testVersionNumeric() {
EntityManager em1 = emf.createEntityManager();
em1.getTransaction().begin();
EntityManager em2 = emf.createEntityManager();
em2.getTransaction().begin();
AnnoTest1 pc1 = em1.find(AnnoTest1.class, new Long(5));
AnnoTest1 pc2 = em2.find(AnnoTest1.class, new Long(5));
assertEquals(1, pc1.getVersion());
assertEquals(1, pc2.getVersion());
assertEquals(0, pc1.getTransient());
pc1.setBasic(75);
pc2.setBasic(75);
em1.getTransaction().commit();
em1.close();
em1 = emf.createEntityManager();
pc1 = em1.find(AnnoTest1.class, new Long(5));
assertEquals(2, pc1.getVersion());
em1.close();
try {
em2.getTransaction().commit();
fail("Optimistic fail");
} catch (Exception e) {
} finally {
em2.close();
}
}
public void testVersionTimestamp() {
// ensure that some time has passed
// since the records were created
try {
- Thread.sleep(50);
+ Thread.sleep(5000);
}
catch (InterruptedException e) {
// do nothing
}
EntityManager em1 = emf.createEntityManager();
em1.getTransaction().begin();
EntityManager em2 = emf.createEntityManager();
em2.getTransaction().begin();
AnnoTest2 pc1 = em1.find(AnnoTest2.class,
new AnnoTest2.Oid(5, "bar"));
AnnoTest2 pc2 = em2.find(AnnoTest2.class,
new AnnoTest2.Oid(5, "bar"));
assertNotNull(pc1.getVersion());
assertEquals(pc1.getVersion(), pc2.getVersion());
pc1.setBasic("75");
pc2.setBasic("75");
em1.getTransaction().commit();
em1.close();
em1 = emf.createEntityManager();
pc1 = em1.find(AnnoTest2.class,
new AnnoTest2.Oid(5, "bar"));
java.util.Date pc1Version = pc1.getVersion();
java.util.Date pc2Version = pc2.getVersion();
assertTrue(pc1Version.compareTo(pc2Version) > 0);
em1.close();
try {
em2.getTransaction().commit();
fail("Optimistic fail");
} catch (Exception e) {
} finally {
em2.close();
}
}
public void testVersionSubclass() {
EntityManager em1 = emf.createEntityManager();
em1.getTransaction().begin();
EntityManager em2 = emf.createEntityManager();
em2.getTransaction().begin();
AnnoTest3 pc1 = em1.find(AnnoTest3.class, new Long(3));
AnnoTest3 pc2 = em2.find(AnnoTest3.class, new Long(3));
assertEquals(1, pc1.getVersion());
assertEquals(1, pc2.getVersion());
pc1.setBasic2(75);
pc2.setBasic2(75);
em1.getTransaction().commit();
em1.close();
em1 = emf.createEntityManager();
pc1 = em1.find(AnnoTest3.class, new Long(3));
assertEquals(2, pc1.getVersion());
em1.close();
try {
em2.getTransaction().commit();
fail("Optimistic fail");
} catch (Exception e) {
} finally {
em2.close();
}
}
public void testVersionNoChange() {
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
AnnoTest1 pc = em.find(AnnoTest1.class, new Long(5));
assertEquals(1, pc.getVersion());
assertEquals(0, pc.getTransient());
pc.setTransient(750);
em.getTransaction().commit();
em.close();
em = emf.createEntityManager();
pc = em.find(AnnoTest1.class, new Long(5));
assertEquals(1, pc.getVersion());
assertEquals(0, pc.getTransient());
em.close();
}
public void testNoDefaultVersionWithoutFieldOrColumn() {
ClassMapping cls = ((JDBCConfiguration) emf.getConfiguration()).
getMappingRepositoryInstance().getMapping(EmbedOwner.class,
null, true);
assertEquals(NoneVersionStrategy.getInstance(),
cls.getVersion().getStrategy());
assertEquals(0, cls.getVersion().getColumns().length);
}
public void testVersionWithField() {
ClassMapping cls = ((JDBCConfiguration) emf.getConfiguration()).
getMappingRepositoryInstance().getMapping(AnnoTest1.class,
null, true);
assertTrue(NoneVersionStrategy.getInstance() !=
cls.getVersion().getStrategy());
assertEquals(1, cls.getVersion().getColumns().length);
}
}
| true | true | public void testVersionTimestamp() {
// ensure that some time has passed
// since the records were created
try {
Thread.sleep(50);
}
catch (InterruptedException e) {
// do nothing
}
EntityManager em1 = emf.createEntityManager();
em1.getTransaction().begin();
EntityManager em2 = emf.createEntityManager();
em2.getTransaction().begin();
AnnoTest2 pc1 = em1.find(AnnoTest2.class,
new AnnoTest2.Oid(5, "bar"));
AnnoTest2 pc2 = em2.find(AnnoTest2.class,
new AnnoTest2.Oid(5, "bar"));
assertNotNull(pc1.getVersion());
assertEquals(pc1.getVersion(), pc2.getVersion());
pc1.setBasic("75");
pc2.setBasic("75");
em1.getTransaction().commit();
em1.close();
em1 = emf.createEntityManager();
pc1 = em1.find(AnnoTest2.class,
new AnnoTest2.Oid(5, "bar"));
java.util.Date pc1Version = pc1.getVersion();
java.util.Date pc2Version = pc2.getVersion();
assertTrue(pc1Version.compareTo(pc2Version) > 0);
em1.close();
try {
em2.getTransaction().commit();
fail("Optimistic fail");
} catch (Exception e) {
} finally {
em2.close();
}
}
| public void testVersionTimestamp() {
// ensure that some time has passed
// since the records were created
try {
Thread.sleep(5000);
}
catch (InterruptedException e) {
// do nothing
}
EntityManager em1 = emf.createEntityManager();
em1.getTransaction().begin();
EntityManager em2 = emf.createEntityManager();
em2.getTransaction().begin();
AnnoTest2 pc1 = em1.find(AnnoTest2.class,
new AnnoTest2.Oid(5, "bar"));
AnnoTest2 pc2 = em2.find(AnnoTest2.class,
new AnnoTest2.Oid(5, "bar"));
assertNotNull(pc1.getVersion());
assertEquals(pc1.getVersion(), pc2.getVersion());
pc1.setBasic("75");
pc2.setBasic("75");
em1.getTransaction().commit();
em1.close();
em1 = emf.createEntityManager();
pc1 = em1.find(AnnoTest2.class,
new AnnoTest2.Oid(5, "bar"));
java.util.Date pc1Version = pc1.getVersion();
java.util.Date pc2Version = pc2.getVersion();
assertTrue(pc1Version.compareTo(pc2Version) > 0);
em1.close();
try {
em2.getTransaction().commit();
fail("Optimistic fail");
} catch (Exception e) {
} finally {
em2.close();
}
}
|
diff --git a/src/main/java/hudson/plugins/clearcase/ClearToolExec.java b/src/main/java/hudson/plugins/clearcase/ClearToolExec.java
index c35b019..82c29c1 100755
--- a/src/main/java/hudson/plugins/clearcase/ClearToolExec.java
+++ b/src/main/java/hudson/plugins/clearcase/ClearToolExec.java
@@ -1,180 +1,180 @@
package hudson.plugins.clearcase;
import hudson.AbortException;
import hudson.FilePath;
import hudson.util.ArgumentListBuilder;
import hudson.util.VariableResolver;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public abstract class ClearToolExec implements ClearTool {
private transient Pattern viewListPattern;
protected ClearToolLauncher launcher;
protected VariableResolver variableResolver;
public ClearToolExec(VariableResolver variableResolver,
ClearToolLauncher launcher) {
this.variableResolver = variableResolver;
this.launcher = launcher;
}
public ClearToolLauncher getLauncher() {
return launcher;
}
protected abstract FilePath getRootViewPath(ClearToolLauncher launcher);
public Reader lshistory(String format, Date lastBuildDate, String viewName,
String branch, String[] viewPaths) throws IOException,
InterruptedException {
SimpleDateFormat formatter = new SimpleDateFormat("d-MMM.HH:mm:ss");
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add("lshistory");
cmd.add("-r");
cmd.add("-since", formatter.format(lastBuildDate).toLowerCase());
cmd.add("-fmt", format);
if ((branch != null) && (branch.length() > 0)) {
cmd.add("-branch", "brtype:" + branch);
}
cmd.add("-nco");
FilePath viewPath = getRootViewPath(launcher).child(viewName);
for (String path : viewPaths) {
- cmd.add(path.replace("\\n",""));
+ cmd.add(path.replace("\n",""));
}
Reader returnReader = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (launcher.run(cmd.toCommandArray(), null, baos, viewPath)) {
returnReader = new InputStreamReader(new ByteArrayInputStream(baos
.toByteArray()));
}
baos.close();
return returnReader;
}
public Reader lsactivity(String activity, String commandFormat,
String viewname) throws IOException, InterruptedException {
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add("lsactivity");
cmd.add("-fmt", commandFormat);
cmd.add(activity);
// changed the path from workspace to getRootViewPath to make Dynamic UCM work
FilePath viewPath = getRootViewPath(launcher).child(viewname);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
launcher.run(cmd.toCommandArray(), null, baos, viewPath);
InputStreamReader reader = new InputStreamReader(
new ByteArrayInputStream(baos.toByteArray()));
baos.close();
return reader;
}
public void mklabel(String viewName, String label) throws IOException,
InterruptedException {
throw new AbortException();
}
public List<String> lsview(boolean onlyActiveDynamicViews)
throws IOException, InterruptedException {
viewListPattern = getListPattern();
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add("lsview");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (launcher.run(cmd.toCommandArray(), null, baos, null)) {
return parseListOutput(new InputStreamReader(
new ByteArrayInputStream(baos.toByteArray())),
onlyActiveDynamicViews);
}
return new ArrayList<String>();
}
public List<String> lsvob(boolean onlyMOunted) throws IOException,
InterruptedException {
viewListPattern = getListPattern();
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add("lsvob");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (launcher.run(cmd.toCommandArray(), null, baos, null)) {
return parseListOutput(new InputStreamReader(
new ByteArrayInputStream(baos.toByteArray())), onlyMOunted);
}
return new ArrayList<String>();
}
public String catcs(String viewName) throws IOException,
InterruptedException {
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add("catcs");
cmd.add("-tag", viewName);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
String retString = "";
if (launcher.run(cmd.toCommandArray(), null, baos, null)) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
new ByteArrayInputStream(baos.toByteArray())));
String line = reader.readLine();
StringBuilder builder = new StringBuilder();
while (line != null) {
if (builder.length() > 0) {
builder.append("\n");
}
builder.append(line);
line = reader.readLine();
}
reader.close();
retString = builder.toString();
}
baos.close();
return retString;
}
private List<String> parseListOutput(Reader consoleReader,
boolean onlyStarMarked) throws IOException {
List<String> views = new ArrayList<String>();
BufferedReader reader = new BufferedReader(consoleReader);
String line = reader.readLine();
while (line != null) {
Matcher matcher = viewListPattern.matcher(line);
if (matcher.find() && matcher.groupCount() == 3) {
if ((!onlyStarMarked)
|| (onlyStarMarked && matcher.group(1).equals("*"))) {
String vob = matcher.group(2);
int pos = Math.max(vob.lastIndexOf('\\'), vob
.lastIndexOf('/'));
if (pos != -1) {
vob = vob.substring(pos + 1);
}
views.add(vob);
}
}
line = reader.readLine();
}
reader.close();
return views;
}
private Pattern getListPattern() {
if (viewListPattern == null) {
viewListPattern = Pattern.compile("(.)\\s*(\\S*)\\s*(\\S*)");
}
return viewListPattern;
}
}
| true | true | public Reader lshistory(String format, Date lastBuildDate, String viewName,
String branch, String[] viewPaths) throws IOException,
InterruptedException {
SimpleDateFormat formatter = new SimpleDateFormat("d-MMM.HH:mm:ss");
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add("lshistory");
cmd.add("-r");
cmd.add("-since", formatter.format(lastBuildDate).toLowerCase());
cmd.add("-fmt", format);
if ((branch != null) && (branch.length() > 0)) {
cmd.add("-branch", "brtype:" + branch);
}
cmd.add("-nco");
FilePath viewPath = getRootViewPath(launcher).child(viewName);
for (String path : viewPaths) {
cmd.add(path.replace("\\n",""));
}
Reader returnReader = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (launcher.run(cmd.toCommandArray(), null, baos, viewPath)) {
returnReader = new InputStreamReader(new ByteArrayInputStream(baos
.toByteArray()));
}
baos.close();
return returnReader;
}
| public Reader lshistory(String format, Date lastBuildDate, String viewName,
String branch, String[] viewPaths) throws IOException,
InterruptedException {
SimpleDateFormat formatter = new SimpleDateFormat("d-MMM.HH:mm:ss");
ArgumentListBuilder cmd = new ArgumentListBuilder();
cmd.add("lshistory");
cmd.add("-r");
cmd.add("-since", formatter.format(lastBuildDate).toLowerCase());
cmd.add("-fmt", format);
if ((branch != null) && (branch.length() > 0)) {
cmd.add("-branch", "brtype:" + branch);
}
cmd.add("-nco");
FilePath viewPath = getRootViewPath(launcher).child(viewName);
for (String path : viewPaths) {
cmd.add(path.replace("\n",""));
}
Reader returnReader = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (launcher.run(cmd.toCommandArray(), null, baos, viewPath)) {
returnReader = new InputStreamReader(new ByteArrayInputStream(baos
.toByteArray()));
}
baos.close();
return returnReader;
}
|
diff --git a/src/edacc/model/ConfigurationScenarioDAO.java b/src/edacc/model/ConfigurationScenarioDAO.java
index 633f8c5..2bb7c5f 100755
--- a/src/edacc/model/ConfigurationScenarioDAO.java
+++ b/src/edacc/model/ConfigurationScenarioDAO.java
@@ -1,154 +1,154 @@
package edacc.model;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;
public class ConfigurationScenarioDAO {
private final static String table = "ConfigurationScenario";
private final static String table_params = "ConfigurationScenario_has_Parameters";
public static void save(ConfigurationScenario cs) throws SQLException {
boolean autocommit = DatabaseConnector.getInstance().getConn().getAutoCommit();
try {
DatabaseConnector.getInstance().getConn().setAutoCommit(false);
if (cs.isNew()) {
PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement("INSERT INTO ConfigurationScenario (SolverBinaries_idSolverBinary, Experiment_idExperiment) VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS);
st.setInt(1, cs.getIdSolverBinary());
st.setInt(2, cs.getIdExperiment());
st.executeUpdate();
ResultSet generatedKeys = st.getGeneratedKeys();
if (generatedKeys.next()) {
cs.setId(generatedKeys.getInt(1));
}
generatedKeys.close();
st.close();
} else if (cs.isModified()) {
PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement("UPDATE ConfigurationScenario SET SolverBinaries_idSolverBinary = ? WHERE Experiment_idExperiment = ?");
st.setInt(1, cs.getIdSolverBinary());
st.setInt(2, cs.getIdExperiment());
st.executeUpdate();
st.close();
}
cs.setSaved();
Statement st = DatabaseConnector.getInstance().getConn().createStatement();
st.executeUpdate("DELETE FROM ConfigurationScenario_has_Parameters WHERE ConfigurationScenario_idConfigurationScenario = " + cs.getId());
st.close();
PreparedStatement ps = DatabaseConnector.getInstance().getConn().prepareStatement("INSERT INTO ConfigurationScenario_has_Parameters (ConfigurationScenario_idConfigurationScenario, Parameters_idParameter, configurable, fixedValue) VALUES (?, ?, ?, ?)");
for (ConfigurationScenarioParameter param : cs.getParameters()) {
ps.setInt(1, cs.getId());
param.setIdConfigurationScenario(cs.getId());
ps.setInt(2, param.getIdParameter());
ps.setBoolean(3, param.isConfigurable());
ps.setString(4, param.getFixedValue());
ps.addBatch();
param.setSaved();
}
ps.executeBatch();
ps.close();
if (cs.getCourse() != null && !cs.getCourse().isSaved()) {
PreparedStatement st2 = DatabaseConnector.getInstance().getConn().prepareStatement("INSERT INTO Course (ConfigurationScenario_idConfigurationScenario, Instances_idInstance, seed, `order`) VALUES (?, ?, ?, ?)");
for (int i = cs.getCourse().getModifiedIndex(); i < cs.getCourse().getLength(); i++) {
st2.setInt(1, cs.getId());
InstanceSeed is = cs.getCourse().get(i);
st2.setInt(2, is.instance.getId());
st2.setInt(3, is.seed);
st2.setInt(4, i);
st2.addBatch();
}
st2.executeBatch();
st2.close();
if (cs.getCourse().getInitialLength() == 0) {
Statement stmnt = DatabaseConnector.getInstance().getConn().createStatement();
stmnt.executeUpdate("UPDATE ConfigurationScenario SET initial_course_length = " + cs.getCourse().getLength() + " WHERE idConfigurationScenario = " + cs.getId());
stmnt.close();
cs.getCourse().setInitialLength(cs.getCourse().getLength());
}
cs.getCourse().setSaved();
- } else {
+ } else if (cs.getCourse() == null) {
cs.setCourse(new Course());
}
} catch (Exception ex) {
DatabaseConnector.getInstance().getConn().rollback();
if (ex instanceof SQLException) {
throw (SQLException) ex;
}
} finally {
DatabaseConnector.getInstance().getConn().setAutoCommit(autocommit);
}
}
private static ConfigurationScenario getConfigurationScenarioFromResultSet(ResultSet rs) throws SQLException {
ConfigurationScenario cs = new ConfigurationScenario();
cs.setId(rs.getInt("idConfigurationScenario"));
cs.setIdExperiment(rs.getInt("Experiment_idExperiment"));
cs.setIdSolverBinary(rs.getInt("SolverBinaries_idSolverBinary"));
return cs;
}
public static ConfigurationScenario getConfigurationScenarioByExperimentId(int idExperiment) throws SQLException {
PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement("SELECT idConfigurationScenario, SolverBinaries_idSolverBinary, Experiment_idExperiment, idSolver, initial_course_length FROM " + table + " JOIN SolverBinaries ON SolverBinaries.idSolverBinary=SolverBinaries_idSolverBinary WHERE Experiment_idExperiment=?");
st.setInt(1, idExperiment);
ResultSet rs = st.executeQuery();
ConfigurationScenario cs = null;
int idSolver;
int initialCourseLength;
if (rs.next()) {
cs = getConfigurationScenarioFromResultSet(rs);
cs.setSaved();
idSolver = rs.getInt("idSolver");
initialCourseLength = rs.getInt("initial_course_length");
rs.close();
st.close();
} else {
rs.close();
st.close();
return null;
}
Map<Integer, Parameter> solver_parameters = new HashMap<Integer, Parameter>();
for (Parameter p : ParameterDAO.getParameterFromSolverId(idSolver)) {
solver_parameters.put(p.getId(), p);
}
PreparedStatement st2 = DatabaseConnector.getInstance().getConn().prepareStatement("SELECT * FROM " + table_params + " WHERE ConfigurationScenario_idConfigurationScenario=?");
st2.setInt(1, cs.getId());
ResultSet rs2 = st2.executeQuery();
while (rs2.next()) {
ConfigurationScenarioParameter csp = new ConfigurationScenarioParameter();
csp.setIdConfigurationScenario(cs.getId());
csp.setFixedValue(rs2.getString("fixedValue"));
csp.setIdParameter(rs2.getInt("Parameters_idParameter"));
csp.setConfigurable(rs2.getBoolean("configurable"));
csp.setParameter(solver_parameters.get(rs2.getInt("Parameters_idParameter")));
csp.setSaved();
cs.getParameters().add(csp);
}
rs2.close();
st2.close();
if (initialCourseLength > 0) {
PreparedStatement st3 = DatabaseConnector.getInstance().getConn().prepareStatement("SELECT ConfigurationScenario_idConfigurationScenario, Instances_idInstance, seed, `order` FROM Course WHERE ConfigurationScenario_idConfigurationScenario = ? ORDER BY `order` ASC");
st3.setInt(1, cs.getId());
ResultSet rs3 = st3.executeQuery();
Course course = new Course();
course.setInitialLength(initialCourseLength);
while (rs3.next()) {
course.add(new InstanceSeed(InstanceDAO.getById(rs3.getInt("Instances_idInstance")), rs3.getInt("seed")));
}
course.setSaved();
cs.setCourse(course);
} else {
cs.setCourse(new Course());
}
return cs;
}
public static boolean configurationScenarioParameterIsSaved(ConfigurationScenarioParameter param) {
return param.isSaved();
}
}
| true | true | public static void save(ConfigurationScenario cs) throws SQLException {
boolean autocommit = DatabaseConnector.getInstance().getConn().getAutoCommit();
try {
DatabaseConnector.getInstance().getConn().setAutoCommit(false);
if (cs.isNew()) {
PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement("INSERT INTO ConfigurationScenario (SolverBinaries_idSolverBinary, Experiment_idExperiment) VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS);
st.setInt(1, cs.getIdSolverBinary());
st.setInt(2, cs.getIdExperiment());
st.executeUpdate();
ResultSet generatedKeys = st.getGeneratedKeys();
if (generatedKeys.next()) {
cs.setId(generatedKeys.getInt(1));
}
generatedKeys.close();
st.close();
} else if (cs.isModified()) {
PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement("UPDATE ConfigurationScenario SET SolverBinaries_idSolverBinary = ? WHERE Experiment_idExperiment = ?");
st.setInt(1, cs.getIdSolverBinary());
st.setInt(2, cs.getIdExperiment());
st.executeUpdate();
st.close();
}
cs.setSaved();
Statement st = DatabaseConnector.getInstance().getConn().createStatement();
st.executeUpdate("DELETE FROM ConfigurationScenario_has_Parameters WHERE ConfigurationScenario_idConfigurationScenario = " + cs.getId());
st.close();
PreparedStatement ps = DatabaseConnector.getInstance().getConn().prepareStatement("INSERT INTO ConfigurationScenario_has_Parameters (ConfigurationScenario_idConfigurationScenario, Parameters_idParameter, configurable, fixedValue) VALUES (?, ?, ?, ?)");
for (ConfigurationScenarioParameter param : cs.getParameters()) {
ps.setInt(1, cs.getId());
param.setIdConfigurationScenario(cs.getId());
ps.setInt(2, param.getIdParameter());
ps.setBoolean(3, param.isConfigurable());
ps.setString(4, param.getFixedValue());
ps.addBatch();
param.setSaved();
}
ps.executeBatch();
ps.close();
if (cs.getCourse() != null && !cs.getCourse().isSaved()) {
PreparedStatement st2 = DatabaseConnector.getInstance().getConn().prepareStatement("INSERT INTO Course (ConfigurationScenario_idConfigurationScenario, Instances_idInstance, seed, `order`) VALUES (?, ?, ?, ?)");
for (int i = cs.getCourse().getModifiedIndex(); i < cs.getCourse().getLength(); i++) {
st2.setInt(1, cs.getId());
InstanceSeed is = cs.getCourse().get(i);
st2.setInt(2, is.instance.getId());
st2.setInt(3, is.seed);
st2.setInt(4, i);
st2.addBatch();
}
st2.executeBatch();
st2.close();
if (cs.getCourse().getInitialLength() == 0) {
Statement stmnt = DatabaseConnector.getInstance().getConn().createStatement();
stmnt.executeUpdate("UPDATE ConfigurationScenario SET initial_course_length = " + cs.getCourse().getLength() + " WHERE idConfigurationScenario = " + cs.getId());
stmnt.close();
cs.getCourse().setInitialLength(cs.getCourse().getLength());
}
cs.getCourse().setSaved();
} else {
cs.setCourse(new Course());
}
} catch (Exception ex) {
DatabaseConnector.getInstance().getConn().rollback();
if (ex instanceof SQLException) {
throw (SQLException) ex;
}
} finally {
DatabaseConnector.getInstance().getConn().setAutoCommit(autocommit);
}
}
| public static void save(ConfigurationScenario cs) throws SQLException {
boolean autocommit = DatabaseConnector.getInstance().getConn().getAutoCommit();
try {
DatabaseConnector.getInstance().getConn().setAutoCommit(false);
if (cs.isNew()) {
PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement("INSERT INTO ConfigurationScenario (SolverBinaries_idSolverBinary, Experiment_idExperiment) VALUES (?, ?)", Statement.RETURN_GENERATED_KEYS);
st.setInt(1, cs.getIdSolverBinary());
st.setInt(2, cs.getIdExperiment());
st.executeUpdate();
ResultSet generatedKeys = st.getGeneratedKeys();
if (generatedKeys.next()) {
cs.setId(generatedKeys.getInt(1));
}
generatedKeys.close();
st.close();
} else if (cs.isModified()) {
PreparedStatement st = DatabaseConnector.getInstance().getConn().prepareStatement("UPDATE ConfigurationScenario SET SolverBinaries_idSolverBinary = ? WHERE Experiment_idExperiment = ?");
st.setInt(1, cs.getIdSolverBinary());
st.setInt(2, cs.getIdExperiment());
st.executeUpdate();
st.close();
}
cs.setSaved();
Statement st = DatabaseConnector.getInstance().getConn().createStatement();
st.executeUpdate("DELETE FROM ConfigurationScenario_has_Parameters WHERE ConfigurationScenario_idConfigurationScenario = " + cs.getId());
st.close();
PreparedStatement ps = DatabaseConnector.getInstance().getConn().prepareStatement("INSERT INTO ConfigurationScenario_has_Parameters (ConfigurationScenario_idConfigurationScenario, Parameters_idParameter, configurable, fixedValue) VALUES (?, ?, ?, ?)");
for (ConfigurationScenarioParameter param : cs.getParameters()) {
ps.setInt(1, cs.getId());
param.setIdConfigurationScenario(cs.getId());
ps.setInt(2, param.getIdParameter());
ps.setBoolean(3, param.isConfigurable());
ps.setString(4, param.getFixedValue());
ps.addBatch();
param.setSaved();
}
ps.executeBatch();
ps.close();
if (cs.getCourse() != null && !cs.getCourse().isSaved()) {
PreparedStatement st2 = DatabaseConnector.getInstance().getConn().prepareStatement("INSERT INTO Course (ConfigurationScenario_idConfigurationScenario, Instances_idInstance, seed, `order`) VALUES (?, ?, ?, ?)");
for (int i = cs.getCourse().getModifiedIndex(); i < cs.getCourse().getLength(); i++) {
st2.setInt(1, cs.getId());
InstanceSeed is = cs.getCourse().get(i);
st2.setInt(2, is.instance.getId());
st2.setInt(3, is.seed);
st2.setInt(4, i);
st2.addBatch();
}
st2.executeBatch();
st2.close();
if (cs.getCourse().getInitialLength() == 0) {
Statement stmnt = DatabaseConnector.getInstance().getConn().createStatement();
stmnt.executeUpdate("UPDATE ConfigurationScenario SET initial_course_length = " + cs.getCourse().getLength() + " WHERE idConfigurationScenario = " + cs.getId());
stmnt.close();
cs.getCourse().setInitialLength(cs.getCourse().getLength());
}
cs.getCourse().setSaved();
} else if (cs.getCourse() == null) {
cs.setCourse(new Course());
}
} catch (Exception ex) {
DatabaseConnector.getInstance().getConn().rollback();
if (ex instanceof SQLException) {
throw (SQLException) ex;
}
} finally {
DatabaseConnector.getInstance().getConn().setAutoCommit(autocommit);
}
}
|
diff --git a/src/main/java/com/objectstyle/db/migration/kit/MigrationsRunner.java b/src/main/java/com/objectstyle/db/migration/kit/MigrationsRunner.java
index bbf8952..3cc0da0 100644
--- a/src/main/java/com/objectstyle/db/migration/kit/MigrationsRunner.java
+++ b/src/main/java/com/objectstyle/db/migration/kit/MigrationsRunner.java
@@ -1,40 +1,40 @@
package com.objectstyle.db.migration.kit;
import com.carbonfive.db.jdbc.DatabaseType;
import com.carbonfive.db.migration.DriverManagerMigrationManager;
import com.carbonfive.db.migration.MigrationResolver;
import com.carbonfive.db.migration.ResourceMigrationResolver;
public class MigrationsRunner {
private static final String[] DEFAULT_MIGRATION_PATHS = {"/db/migrations"};
public static void main(String[] args) {
DriverManagerMigrationManager migrationManager = createMigrationManager();
for (String path : getMigrationPaths()) {
MigrationResolver migrationResolver = new ResourceMigrationResolver(path);
migrationManager.setMigrationResolver(migrationResolver);
migrationManager.migrate();
}
}
private static DriverManagerMigrationManager createMigrationManager() {
String driver = System.getProperty("driver");
String url = System.getProperty("url");
String username = System.getProperty("username");
String password = System.getProperty("password");
return new DriverManagerMigrationManager(driver, url, username, password, DatabaseType.MYSQL);
}
private static String[] getMigrationPaths() {
String[] migrationPaths = DEFAULT_MIGRATION_PATHS;
String migrationPathsStr = System.getProperty("paths");
- if (migrationPaths != null) {
+ if (migrationPathsStr != null) {
migrationPaths = migrationPathsStr.split(":");
for (int i = 0; i < migrationPaths.length; i++) {
String path = "classpath:" + migrationPaths[i].trim();
migrationPaths[i] = path;
}
}
return migrationPaths;
}
}
| true | true | private static String[] getMigrationPaths() {
String[] migrationPaths = DEFAULT_MIGRATION_PATHS;
String migrationPathsStr = System.getProperty("paths");
if (migrationPaths != null) {
migrationPaths = migrationPathsStr.split(":");
for (int i = 0; i < migrationPaths.length; i++) {
String path = "classpath:" + migrationPaths[i].trim();
migrationPaths[i] = path;
}
}
return migrationPaths;
}
| private static String[] getMigrationPaths() {
String[] migrationPaths = DEFAULT_MIGRATION_PATHS;
String migrationPathsStr = System.getProperty("paths");
if (migrationPathsStr != null) {
migrationPaths = migrationPathsStr.split(":");
for (int i = 0; i < migrationPaths.length; i++) {
String path = "classpath:" + migrationPaths[i].trim();
migrationPaths[i] = path;
}
}
return migrationPaths;
}
|
diff --git a/src/net/cactii/flash2/FlashDevice.java b/src/net/cactii/flash2/FlashDevice.java
index 96d3770..75c7eb3 100644
--- a/src/net/cactii/flash2/FlashDevice.java
+++ b/src/net/cactii/flash2/FlashDevice.java
@@ -1,135 +1,137 @@
package net.cactii.flash2;
import android.os.Build;
import java.io.FileWriter;
import java.io.IOException;
import android.hardware.Camera;
import net.cactii.flash2.R;
import android.content.Context;
import android.util.Log;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import java.io.File;
public class FlashDevice {
private static final String MSG_TAG = "TorchDevice";
/* New variables, init'ed by resource items */
private static int mValueOn;
private static int mValueHigh;
private static int mValueDeathRay;
private static String mFlashDevice;
private static boolean mUseCameraInterface;
private WakeLock mWakeLock;
public static final int STROBE = -1;
public static final int OFF = 0;
public static final int ON = 1;
public static final int HIGH = 128;
public static final int DEATH_RAY = 3;
private static FlashDevice instance;
private FileWriter mWriter = null;
private int mFlashMode = OFF;
private Camera mCamera = null;
private Camera.Parameters mParams;
private FlashDevice(Context context) {
this.mValueOn = context.getResources().getInteger(R.integer.valueOn);
this.mValueHigh = context.getResources().getInteger(R.integer.valueHigh);
this.mValueDeathRay = context.getResources().getInteger(R.integer.valueDeathRay);
this.mFlashDevice = context.getResources().getString(R.string.flashDevice);
this.mUseCameraInterface = context.getResources().getBoolean(R.bool.useCameraInterface);
if (this.mUseCameraInterface) {
PowerManager pm
= (PowerManager) context.getSystemService(Context.POWER_SERVICE);
this.mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "Torch");
}
}
public static synchronized FlashDevice instance(Context context) {
if (instance == null) {
instance = new FlashDevice(context);
}
return instance;
}
public synchronized void setFlashMode(int mode) {
try {
int value = mode;
switch (mode) {
case STROBE:
value = OFF;
break;
case DEATH_RAY:
if (mValueDeathRay >= 0) {
value = mValueDeathRay;
} else if (mValueHigh >= 0) {
value = mValueHigh;
} else {
value = 0;
Log.d(MSG_TAG,"Broken device configuration");
}
break;
case ON:
if (mValueOn >= 0) {
value = mValueOn;
} else {
value = 0;
Log.d(MSG_TAG,"Broken device configuration");
}
break;
}
if (mUseCameraInterface) {
if (mCamera == null) {
mCamera = Camera.open();
}
if (value == OFF) {
mParams = mCamera.getParameters();
mParams.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
mCamera.setParameters(mParams);
if (mode != STROBE) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
if (mWakeLock.isHeld())
mWakeLock.release();
} else {
mParams = mCamera.getParameters();
mParams.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(mParams);
- mWakeLock.acquire(); // we don't want to go to sleep while cam is up
+ if (!mWakeLock.isHeld()) { // only get the wakelock if we don't have it already
+ mWakeLock.acquire(); // we don't want to go to sleep while cam is up
+ }
if (mFlashMode != STROBE) {
mCamera.startPreview();
}
}
} else {
if (mWriter == null) {
mWriter = new FileWriter(mFlashDevice);
}
mWriter.write(String.valueOf(value));
mWriter.flush();
if (mode == OFF) {
mWriter.close();
mWriter = null;
}
}
mFlashMode = mode;
} catch (IOException e) {
throw new RuntimeException("Can't open flash device", e);
}
}
public synchronized int getFlashMode() {
return mFlashMode;
}
}
| true | true | public synchronized void setFlashMode(int mode) {
try {
int value = mode;
switch (mode) {
case STROBE:
value = OFF;
break;
case DEATH_RAY:
if (mValueDeathRay >= 0) {
value = mValueDeathRay;
} else if (mValueHigh >= 0) {
value = mValueHigh;
} else {
value = 0;
Log.d(MSG_TAG,"Broken device configuration");
}
break;
case ON:
if (mValueOn >= 0) {
value = mValueOn;
} else {
value = 0;
Log.d(MSG_TAG,"Broken device configuration");
}
break;
}
if (mUseCameraInterface) {
if (mCamera == null) {
mCamera = Camera.open();
}
if (value == OFF) {
mParams = mCamera.getParameters();
mParams.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
mCamera.setParameters(mParams);
if (mode != STROBE) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
if (mWakeLock.isHeld())
mWakeLock.release();
} else {
mParams = mCamera.getParameters();
mParams.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(mParams);
mWakeLock.acquire(); // we don't want to go to sleep while cam is up
if (mFlashMode != STROBE) {
mCamera.startPreview();
}
}
} else {
if (mWriter == null) {
mWriter = new FileWriter(mFlashDevice);
}
mWriter.write(String.valueOf(value));
mWriter.flush();
if (mode == OFF) {
mWriter.close();
mWriter = null;
}
}
mFlashMode = mode;
} catch (IOException e) {
throw new RuntimeException("Can't open flash device", e);
}
}
| public synchronized void setFlashMode(int mode) {
try {
int value = mode;
switch (mode) {
case STROBE:
value = OFF;
break;
case DEATH_RAY:
if (mValueDeathRay >= 0) {
value = mValueDeathRay;
} else if (mValueHigh >= 0) {
value = mValueHigh;
} else {
value = 0;
Log.d(MSG_TAG,"Broken device configuration");
}
break;
case ON:
if (mValueOn >= 0) {
value = mValueOn;
} else {
value = 0;
Log.d(MSG_TAG,"Broken device configuration");
}
break;
}
if (mUseCameraInterface) {
if (mCamera == null) {
mCamera = Camera.open();
}
if (value == OFF) {
mParams = mCamera.getParameters();
mParams.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
mCamera.setParameters(mParams);
if (mode != STROBE) {
mCamera.stopPreview();
mCamera.release();
mCamera = null;
}
if (mWakeLock.isHeld())
mWakeLock.release();
} else {
mParams = mCamera.getParameters();
mParams.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
mCamera.setParameters(mParams);
if (!mWakeLock.isHeld()) { // only get the wakelock if we don't have it already
mWakeLock.acquire(); // we don't want to go to sleep while cam is up
}
if (mFlashMode != STROBE) {
mCamera.startPreview();
}
}
} else {
if (mWriter == null) {
mWriter = new FileWriter(mFlashDevice);
}
mWriter.write(String.valueOf(value));
mWriter.flush();
if (mode == OFF) {
mWriter.close();
mWriter = null;
}
}
mFlashMode = mode;
} catch (IOException e) {
throw new RuntimeException("Can't open flash device", e);
}
}
|
diff --git a/core/src/visad/trunk/DelaunayWatson.java b/core/src/visad/trunk/DelaunayWatson.java
index c81bdd187..f5122ef43 100644
--- a/core/src/visad/trunk/DelaunayWatson.java
+++ b/core/src/visad/trunk/DelaunayWatson.java
@@ -1,367 +1,367 @@
//
// DelaunayWatson.java
//
/*
VisAD system for interactive analysis and visualization of numerical
data. Copyright (C) 1996 - 2006 Bill Hibbard, Curtis Rueden, Tom
Rink, Dave Glowacki, Steve Emmerson, Tom Whittaker, Don Murray, and
Tommy Jasmin.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 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
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place - Suite 330, Boston,
MA 02111-1307, USA
*/
package visad;
import java.util.*;
/* The Delaunay triangulation/tetrahedralization algorithm in this class is
* originally from nnsort.c by David F. Watson:
*
* nnsort() finds the Delaunay triangulation of the two- or three-component
* vectors in 'data_list' and returns a list of simplex vertices in
* 'vertices' with the corresponding circumcentre and squared radius in the
* rows of 'circentres'. nnsort() also can be used to find the ordered
* convex hull of the two- or three-component vectors in 'data_list' and
* returns a list of (d-1)-facet vertices in 'vertices' (dummy filename for
* 'circentres' must be used).
* nnsort() was written by Dave Watson and uses the algorithm described in -
* Watson, D.F., 1981, Computing the n-dimensional Delaunay tessellation
* with application to Voronoi polytopes:
* The Computer J., 24(2), p. 167-172.
*
* additional information about this algorithm can be found in -
* CONTOURING: A guide to the analysis and display of spatial data,
* by David F. Watson, Pergamon Press, 1992, ISBN 0 08 040286 0
* */
/**
DelaunayWatson represents an O(N^2) method with low overhead
to find the Delaunay triangulation or tetrahedralization of
a set of samples of R^2 or R^3.<P>
*/
public class DelaunayWatson extends Delaunay {
private static final float BIGNUM = (float) 1E37;
private static final float EPSILON = 0.00001f;
// temporary storage size factor
private static final int TSIZE = 75;
// factor (>=1) for radius of control points
private static final float RANGE = 10.0f;
/**
* construct a Delaunay triangulation of the points in the
* samples array using Watson's algorithm
* @param samples locations of points for topology - dimensioned
* float[dimension][number_of_points]
* @throws VisADException a VisAD error occurred
*/
public DelaunayWatson(float[][] samples) throws VisADException {
int dim = samples.length;
int nrs = samples[0].length;
float xx, yy, bgs;
int i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i11;
int[] ii = new int[3];
int dm, dim1, nts, tsz;
float[][] mxy = new float[2][dim];
for (i0=0; i0<dim; i0++) mxy[0][i0] = - (mxy[1][i0] = BIGNUM);
dim1 = dim + 1;
float[][] wrk = new float[dim][dim1];
for (i0=0; i0<dim; i0++) for (i1=0; i1<dim1; i1++) wrk[i0][i1] = -RANGE;
for (i0=0; i0<dim; i0++) wrk[i0][i0] = RANGE * (3 * dim - 1);
float[][] pts = new float[nrs + dim1][dim];
for (i0=0; i0<nrs; i0++) {
if (dim < 3) {
pts[i0][0] = samples[0][i0];
pts[i0][1] = samples[1][i0];
}
else {
pts[i0][0] = samples[0][i0];
pts[i0][1] = samples[1][i0];
pts[i0][2] = samples[2][i0];
}
// compute bounding box
for (i1=0; i1<dim; i1++) {
if (mxy[0][i1] < pts[i0][i1]) mxy[0][i1] = pts[i0][i1]; // max
if (mxy[1][i1] > pts[i0][i1]) mxy[1][i1] = pts[i0][i1]; // min
}
}
for (bgs=0, i0=0; i0<dim; i0++) {
mxy[0][i0] -= mxy[1][i0];
if (bgs < mxy[0][i0]) bgs = mxy[0][i0];
}
// now bgs = largest range
// add random perturbations to points
bgs *= EPSILON;
Random rand = new Random(367);
for (i0=0; i0<nrs; i0++) for (i1=0; i1<dim; i1++) {
// random numbers [0, 1]
- pts[i0][i1] += bgs * (0.5 - rand.nextDouble() / 0x7fffffff);
+ pts[i0][i1] += bgs * (0.5 - rand.nextDouble());
}
for (i0=0; i0<dim1; i0++) for (i1=0; i1<dim; i1++) {
pts[nrs+i0][i1] = mxy[1][i1] + wrk[i1][i0] * mxy[0][i1];
}
for (i1=1, i0=2; i0<dim1; i0++) i1 *= i0;
tsz = TSIZE * i1;
int[][] tmp = new int[tsz + 1][dim];
// storage allocation - increase value of `i1' for 3D if necessary
i1 *= (nrs + 50 * i1);
/* WLH 4 Nov 97 */
if (dim == 3) i1 *= 10;
/* end WLH 4 Nov 97 */
int[] id = new int[i1];
for (i0=0; i0<i1; i0++) id[i0] = i0;
int[][] a3s = new int[i1][dim1];
float[][] ccr = new float[i1][dim1];
for (a3s[0][0]=nrs, i0=1; i0<dim1; i0++) a3s[0][i0] = a3s[0][i0-1] + 1;
for (ccr[0][dim]=BIGNUM, i0=0; i0<dim; i0++) ccr[0][i0] = 0;
nts = i4 = 1;
dm = dim - 1;
for (i0=0; i0<nrs; i0++) {
i1 = i7 = -1;
i9 = 0;
Loop3:
for (i11=0; i11<nts; i11++) {
i1++;
while (a3s[i1][0] < 0) i1++;
xx = ccr[i1][dim];
for (i2=0; i2<dim; i2++) {
xx -= (pts[i0][i2] - ccr[i1][i2]) * (pts[i0][i2] - ccr[i1][i2]);
if (xx<0) continue Loop3;
}
i9--;
i4--;
id[i4] = i1;
Loop2:
for (i2=0; i2<dim1; i2++) {
ii[0] = 0;
if (ii[0] == i2) ii[0]++;
for (i3=1; i3<dim; i3++) {
ii[i3] = ii[i3-1] + 1;
if (ii[i3] == i2) ii[i3]++;
}
if (i7>dm) {
i8 = i7;
Loop1:
for (i3=0; i3<=i8; i3++) {
for (i5=0; i5<dim; i5++) {
if (a3s[i1][ii[i5]] != tmp[i3][i5]) continue Loop1;
}
for (i6=0; i6<dim; i6++) tmp[i3][i6] = tmp[i8][i6];
i7--;
continue Loop2;
}
}
if (++i7 > tsz) {
int newtsz = 2 * tsz;
int[][] newtmp = new int[newtsz + 1][dim];
System.arraycopy(tmp, 0, newtmp, 0, tsz);
tsz = newtsz;
tmp = newtmp;
// WLH 23 july 97
// throw new VisADException(
// "DelaunayWatson: Temporary storage exceeded");
}
for (i3=0; i3<dim; i3++) tmp[i7][i3] = a3s[i1][ii[i3]];
}
a3s[i1][0] = -1;
}
for (i1=0; i1<=i7; i1++) {
for (i2=0; i2<dim; i2++) {
for (wrk[i2][dim]=0, i3=0; i3<dim; i3++) {
wrk[i2][i3] = pts[tmp[i1][i2]][i3] - pts[i0][i3];
wrk[i2][dim] += wrk[i2][i3] * (pts[tmp[i1][i2]][i3]
+ pts[i0][i3]) / 2;
}
}
if (dim < 3) {
xx = wrk[0][0] * wrk[1][1] - wrk[1][0] * wrk[0][1];
ccr[id[i4]][0] = (wrk[0][2] * wrk[1][1]
- wrk[1][2] * wrk[0][1]) / xx;
ccr[id[i4]][1] = (wrk[0][0] * wrk[1][2]
- wrk[1][0] * wrk[0][2]) / xx;
}
else {
xx = (wrk[0][0] * (wrk[1][1] * wrk[2][2] - wrk[2][1] * wrk[1][2]))
- (wrk[0][1] * (wrk[1][0] * wrk[2][2] - wrk[2][0] * wrk[1][2]))
+ (wrk[0][2] * (wrk[1][0] * wrk[2][1] - wrk[2][0] * wrk[1][1]));
ccr[id[i4]][0] = ((wrk[0][3] * (wrk[1][1] * wrk[2][2]
- wrk[2][1] * wrk[1][2]))
- (wrk[0][1] * (wrk[1][3] * wrk[2][2]
- wrk[2][3] * wrk[1][2]))
+ (wrk[0][2] * (wrk[1][3] * wrk[2][1]
- wrk[2][3] * wrk[1][1]))) / xx;
ccr[id[i4]][1] = ((wrk[0][0] * (wrk[1][3] * wrk[2][2]
- wrk[2][3] * wrk[1][2]))
- (wrk[0][3] * (wrk[1][0] * wrk[2][2]
- wrk[2][0] * wrk[1][2]))
+ (wrk[0][2] * (wrk[1][0] * wrk[2][3]
- wrk[2][0] * wrk[1][3]))) / xx;
ccr[id[i4]][2] = ((wrk[0][0] * (wrk[1][1] * wrk[2][3]
- wrk[2][1] * wrk[1][3]))
- (wrk[0][1] * (wrk[1][0] * wrk[2][3]
- wrk[2][0] * wrk[1][3]))
+ (wrk[0][3] * (wrk[1][0] * wrk[2][1]
- wrk[2][0] * wrk[1][1]))) / xx;
}
for (ccr[id[i4]][dim]=0, i2=0; i2<dim; i2++) {
ccr[id[i4]][dim] += (pts[i0][i2] - ccr[id[i4]][i2])
* (pts[i0][i2] - ccr[id[i4]][i2]);
a3s[id[i4]][i2] = tmp[i1][i2];
}
a3s[id[i4]][dim] = i0;
i4++;
i9++;
}
nts += i9;
}
/* OUTPUT is in a3s ARRAY
needed output is:
Tri - array of pointers from triangles or tetrahedra to their
corresponding vertices
Vertices - array of pointers from vertices to their
corresponding triangles or tetrahedra
Walk - array of pointers from triangles or tetrahedra to neighboring
triangles or tetrahedra
Edges - array of pointers from each triangle or tetrahedron's edges
to their corresponding triangles or tetrahedra
helpers:
nverts - number of triangles or tetrahedra per vertex
*/
// compute number of triangles or tetrahedra
int[] nverts = new int[nrs];
for (int i=0; i<nrs; i++) nverts[i] = 0;
int ntris = 0;
i0 = -1;
for (i11=0; i11<nts; i11++) {
i0++;
while (a3s[i0][0] < 0) i0++;
if (a3s[i0][0] < nrs) {
ntris++;
if (dim < 3) {
nverts[a3s[i0][0]]++;
nverts[a3s[i0][1]]++;
nverts[a3s[i0][2]]++;
}
else {
nverts[a3s[i0][0]]++;
nverts[a3s[i0][1]]++;
nverts[a3s[i0][2]]++;
nverts[a3s[i0][3]]++;
}
}
}
Vertices = new int[nrs][];
for (int i=0; i<nrs; i++) Vertices[i] = new int[nverts[i]];
for (int i=0; i<nrs; i++) nverts[i] = 0;
// build Tri & Vertices components
Tri = new int[ntris][dim1];
int a, b, c, d;
int itri = 0;
i0 = -1;
for (i11=0; i11<nts; i11++) {
i0++;
while (a3s[i0][0] < 0) i0++;
if (a3s[i0][0] < nrs) {
if (dim < 3) {
a = a3s[i0][0];
b = a3s[i0][1];
c = a3s[i0][2];
Vertices[a][nverts[a]] = itri;
nverts[a]++;
Vertices[b][nverts[b]] = itri;
nverts[b]++;
Vertices[c][nverts[c]] = itri;
nverts[c]++;
Tri[itri][0] = a;
Tri[itri][1] = b;
Tri[itri][2] = c;
}
else {
a = a3s[i0][0];
b = a3s[i0][1];
c = a3s[i0][2];
d = a3s[i0][3];
Vertices[a][nverts[a]] = itri;
nverts[a]++;
Vertices[b][nverts[b]] = itri;
nverts[b]++;
Vertices[c][nverts[c]] = itri;
nverts[c]++;
Vertices[d][nverts[d]] = itri;
nverts[d]++;
Tri[itri][0] = a;
Tri[itri][1] = b;
Tri[itri][2] = c;
Tri[itri][3] = d;
}
itri++;
}
}
// call more generic method for constructing Walk and Edges arrays
finish_triang(samples);
}
/*
DO NOT DELETE THIS COMMENTED CODE
IT CONTAINS ALGORITHM DETAILS NOT CAST INTO JAVA (YET?)
i0 = -1;
for (i11=0; i11<nts; i11++) {
i0++;
while (a3s[i0][0] < 0) i0++;
if (a3s[i0][0] < nrs) {
for (i1=0; i1<dim; i1++) for (i2=0; i2<dim; i2++) {
wrk[i1][i2] = pts[a3s[i0][i1]][i2] - pts[a3s[i0][dim]][i2];
}
if (dim < 3) {
xx = wrk[0][0] * wrk[1][1] - wrk[0][1] * wrk[1][0];
if (fabs(xx) > EPSILON) {
if (xx < 0)
fprintf(afile,"%d %d %d\n",a3s[i0][0],a3s[i0][2],a3s[i0][1]);
else fprintf(afile,"%d %d %d\n",a3s[i0][0],a3s[i0][1],a3s[i0][2]);
fprintf(bfile,"%e %e %e\n",ccr[i0][0],ccr[i0][1],ccr[i0][2]);
}
}
else {
xx = ((wrk[0][0] * (wrk[1][1] * wrk[2][2] - wrk[2][1] * wrk[1][2]))
- (wrk[0][1] * (wrk[1][0] * wrk[2][2] - wrk[2][0] * wrk[1][2]))
+ (wrk[0][2] * (wrk[1][0] * wrk[2][1] - wrk[2][0] * wrk[1][1])));
if (fabs(xx) > EPSILON) {
if (xx < 0)
fprintf(afile,"%d %d %d %d\n",
a3s[i0][0],a3s[i0][1],a3s[i0][3],a3s[i0][2]);
else fprintf(afile,"%d %d %d %d\n",
a3s[i0][0],a3s[i0][1],a3s[i0][2],a3s[i0][3]);
fprintf(bfile,"%e %e %e %e\n",
ccr[i0][0],ccr[i0][1],ccr[i0][2],ccr[i0][3]);
}
}
}
}
*/
}
| true | true | public DelaunayWatson(float[][] samples) throws VisADException {
int dim = samples.length;
int nrs = samples[0].length;
float xx, yy, bgs;
int i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i11;
int[] ii = new int[3];
int dm, dim1, nts, tsz;
float[][] mxy = new float[2][dim];
for (i0=0; i0<dim; i0++) mxy[0][i0] = - (mxy[1][i0] = BIGNUM);
dim1 = dim + 1;
float[][] wrk = new float[dim][dim1];
for (i0=0; i0<dim; i0++) for (i1=0; i1<dim1; i1++) wrk[i0][i1] = -RANGE;
for (i0=0; i0<dim; i0++) wrk[i0][i0] = RANGE * (3 * dim - 1);
float[][] pts = new float[nrs + dim1][dim];
for (i0=0; i0<nrs; i0++) {
if (dim < 3) {
pts[i0][0] = samples[0][i0];
pts[i0][1] = samples[1][i0];
}
else {
pts[i0][0] = samples[0][i0];
pts[i0][1] = samples[1][i0];
pts[i0][2] = samples[2][i0];
}
// compute bounding box
for (i1=0; i1<dim; i1++) {
if (mxy[0][i1] < pts[i0][i1]) mxy[0][i1] = pts[i0][i1]; // max
if (mxy[1][i1] > pts[i0][i1]) mxy[1][i1] = pts[i0][i1]; // min
}
}
for (bgs=0, i0=0; i0<dim; i0++) {
mxy[0][i0] -= mxy[1][i0];
if (bgs < mxy[0][i0]) bgs = mxy[0][i0];
}
// now bgs = largest range
// add random perturbations to points
bgs *= EPSILON;
Random rand = new Random(367);
for (i0=0; i0<nrs; i0++) for (i1=0; i1<dim; i1++) {
// random numbers [0, 1]
pts[i0][i1] += bgs * (0.5 - rand.nextDouble() / 0x7fffffff);
}
for (i0=0; i0<dim1; i0++) for (i1=0; i1<dim; i1++) {
pts[nrs+i0][i1] = mxy[1][i1] + wrk[i1][i0] * mxy[0][i1];
}
for (i1=1, i0=2; i0<dim1; i0++) i1 *= i0;
tsz = TSIZE * i1;
int[][] tmp = new int[tsz + 1][dim];
// storage allocation - increase value of `i1' for 3D if necessary
i1 *= (nrs + 50 * i1);
/* WLH 4 Nov 97 */
if (dim == 3) i1 *= 10;
/* end WLH 4 Nov 97 */
int[] id = new int[i1];
for (i0=0; i0<i1; i0++) id[i0] = i0;
int[][] a3s = new int[i1][dim1];
float[][] ccr = new float[i1][dim1];
for (a3s[0][0]=nrs, i0=1; i0<dim1; i0++) a3s[0][i0] = a3s[0][i0-1] + 1;
for (ccr[0][dim]=BIGNUM, i0=0; i0<dim; i0++) ccr[0][i0] = 0;
nts = i4 = 1;
dm = dim - 1;
for (i0=0; i0<nrs; i0++) {
i1 = i7 = -1;
i9 = 0;
Loop3:
for (i11=0; i11<nts; i11++) {
i1++;
while (a3s[i1][0] < 0) i1++;
xx = ccr[i1][dim];
for (i2=0; i2<dim; i2++) {
xx -= (pts[i0][i2] - ccr[i1][i2]) * (pts[i0][i2] - ccr[i1][i2]);
if (xx<0) continue Loop3;
}
i9--;
i4--;
id[i4] = i1;
Loop2:
for (i2=0; i2<dim1; i2++) {
ii[0] = 0;
if (ii[0] == i2) ii[0]++;
for (i3=1; i3<dim; i3++) {
ii[i3] = ii[i3-1] + 1;
if (ii[i3] == i2) ii[i3]++;
}
if (i7>dm) {
i8 = i7;
Loop1:
for (i3=0; i3<=i8; i3++) {
for (i5=0; i5<dim; i5++) {
if (a3s[i1][ii[i5]] != tmp[i3][i5]) continue Loop1;
}
for (i6=0; i6<dim; i6++) tmp[i3][i6] = tmp[i8][i6];
i7--;
continue Loop2;
}
}
if (++i7 > tsz) {
int newtsz = 2 * tsz;
int[][] newtmp = new int[newtsz + 1][dim];
System.arraycopy(tmp, 0, newtmp, 0, tsz);
tsz = newtsz;
tmp = newtmp;
// WLH 23 july 97
// throw new VisADException(
// "DelaunayWatson: Temporary storage exceeded");
}
for (i3=0; i3<dim; i3++) tmp[i7][i3] = a3s[i1][ii[i3]];
}
a3s[i1][0] = -1;
}
for (i1=0; i1<=i7; i1++) {
for (i2=0; i2<dim; i2++) {
for (wrk[i2][dim]=0, i3=0; i3<dim; i3++) {
wrk[i2][i3] = pts[tmp[i1][i2]][i3] - pts[i0][i3];
wrk[i2][dim] += wrk[i2][i3] * (pts[tmp[i1][i2]][i3]
+ pts[i0][i3]) / 2;
}
}
if (dim < 3) {
xx = wrk[0][0] * wrk[1][1] - wrk[1][0] * wrk[0][1];
ccr[id[i4]][0] = (wrk[0][2] * wrk[1][1]
- wrk[1][2] * wrk[0][1]) / xx;
ccr[id[i4]][1] = (wrk[0][0] * wrk[1][2]
- wrk[1][0] * wrk[0][2]) / xx;
}
else {
xx = (wrk[0][0] * (wrk[1][1] * wrk[2][2] - wrk[2][1] * wrk[1][2]))
- (wrk[0][1] * (wrk[1][0] * wrk[2][2] - wrk[2][0] * wrk[1][2]))
+ (wrk[0][2] * (wrk[1][0] * wrk[2][1] - wrk[2][0] * wrk[1][1]));
ccr[id[i4]][0] = ((wrk[0][3] * (wrk[1][1] * wrk[2][2]
- wrk[2][1] * wrk[1][2]))
- (wrk[0][1] * (wrk[1][3] * wrk[2][2]
- wrk[2][3] * wrk[1][2]))
+ (wrk[0][2] * (wrk[1][3] * wrk[2][1]
- wrk[2][3] * wrk[1][1]))) / xx;
ccr[id[i4]][1] = ((wrk[0][0] * (wrk[1][3] * wrk[2][2]
- wrk[2][3] * wrk[1][2]))
- (wrk[0][3] * (wrk[1][0] * wrk[2][2]
- wrk[2][0] * wrk[1][2]))
+ (wrk[0][2] * (wrk[1][0] * wrk[2][3]
- wrk[2][0] * wrk[1][3]))) / xx;
ccr[id[i4]][2] = ((wrk[0][0] * (wrk[1][1] * wrk[2][3]
- wrk[2][1] * wrk[1][3]))
- (wrk[0][1] * (wrk[1][0] * wrk[2][3]
- wrk[2][0] * wrk[1][3]))
+ (wrk[0][3] * (wrk[1][0] * wrk[2][1]
- wrk[2][0] * wrk[1][1]))) / xx;
}
for (ccr[id[i4]][dim]=0, i2=0; i2<dim; i2++) {
ccr[id[i4]][dim] += (pts[i0][i2] - ccr[id[i4]][i2])
* (pts[i0][i2] - ccr[id[i4]][i2]);
a3s[id[i4]][i2] = tmp[i1][i2];
}
a3s[id[i4]][dim] = i0;
i4++;
i9++;
}
nts += i9;
}
/* OUTPUT is in a3s ARRAY
needed output is:
Tri - array of pointers from triangles or tetrahedra to their
corresponding vertices
Vertices - array of pointers from vertices to their
corresponding triangles or tetrahedra
Walk - array of pointers from triangles or tetrahedra to neighboring
triangles or tetrahedra
Edges - array of pointers from each triangle or tetrahedron's edges
to their corresponding triangles or tetrahedra
helpers:
nverts - number of triangles or tetrahedra per vertex
*/
// compute number of triangles or tetrahedra
int[] nverts = new int[nrs];
for (int i=0; i<nrs; i++) nverts[i] = 0;
int ntris = 0;
i0 = -1;
for (i11=0; i11<nts; i11++) {
i0++;
while (a3s[i0][0] < 0) i0++;
if (a3s[i0][0] < nrs) {
ntris++;
if (dim < 3) {
nverts[a3s[i0][0]]++;
nverts[a3s[i0][1]]++;
nverts[a3s[i0][2]]++;
}
else {
nverts[a3s[i0][0]]++;
nverts[a3s[i0][1]]++;
nverts[a3s[i0][2]]++;
nverts[a3s[i0][3]]++;
}
}
}
Vertices = new int[nrs][];
for (int i=0; i<nrs; i++) Vertices[i] = new int[nverts[i]];
for (int i=0; i<nrs; i++) nverts[i] = 0;
// build Tri & Vertices components
Tri = new int[ntris][dim1];
int a, b, c, d;
int itri = 0;
i0 = -1;
for (i11=0; i11<nts; i11++) {
i0++;
while (a3s[i0][0] < 0) i0++;
if (a3s[i0][0] < nrs) {
if (dim < 3) {
a = a3s[i0][0];
b = a3s[i0][1];
c = a3s[i0][2];
Vertices[a][nverts[a]] = itri;
nverts[a]++;
Vertices[b][nverts[b]] = itri;
nverts[b]++;
Vertices[c][nverts[c]] = itri;
nverts[c]++;
Tri[itri][0] = a;
Tri[itri][1] = b;
Tri[itri][2] = c;
}
else {
a = a3s[i0][0];
b = a3s[i0][1];
c = a3s[i0][2];
d = a3s[i0][3];
Vertices[a][nverts[a]] = itri;
nverts[a]++;
Vertices[b][nverts[b]] = itri;
nverts[b]++;
Vertices[c][nverts[c]] = itri;
nverts[c]++;
Vertices[d][nverts[d]] = itri;
nverts[d]++;
Tri[itri][0] = a;
Tri[itri][1] = b;
Tri[itri][2] = c;
Tri[itri][3] = d;
}
itri++;
}
}
// call more generic method for constructing Walk and Edges arrays
finish_triang(samples);
}
| public DelaunayWatson(float[][] samples) throws VisADException {
int dim = samples.length;
int nrs = samples[0].length;
float xx, yy, bgs;
int i0, i1, i2, i3, i4, i5, i6, i7, i8, i9, i11;
int[] ii = new int[3];
int dm, dim1, nts, tsz;
float[][] mxy = new float[2][dim];
for (i0=0; i0<dim; i0++) mxy[0][i0] = - (mxy[1][i0] = BIGNUM);
dim1 = dim + 1;
float[][] wrk = new float[dim][dim1];
for (i0=0; i0<dim; i0++) for (i1=0; i1<dim1; i1++) wrk[i0][i1] = -RANGE;
for (i0=0; i0<dim; i0++) wrk[i0][i0] = RANGE * (3 * dim - 1);
float[][] pts = new float[nrs + dim1][dim];
for (i0=0; i0<nrs; i0++) {
if (dim < 3) {
pts[i0][0] = samples[0][i0];
pts[i0][1] = samples[1][i0];
}
else {
pts[i0][0] = samples[0][i0];
pts[i0][1] = samples[1][i0];
pts[i0][2] = samples[2][i0];
}
// compute bounding box
for (i1=0; i1<dim; i1++) {
if (mxy[0][i1] < pts[i0][i1]) mxy[0][i1] = pts[i0][i1]; // max
if (mxy[1][i1] > pts[i0][i1]) mxy[1][i1] = pts[i0][i1]; // min
}
}
for (bgs=0, i0=0; i0<dim; i0++) {
mxy[0][i0] -= mxy[1][i0];
if (bgs < mxy[0][i0]) bgs = mxy[0][i0];
}
// now bgs = largest range
// add random perturbations to points
bgs *= EPSILON;
Random rand = new Random(367);
for (i0=0; i0<nrs; i0++) for (i1=0; i1<dim; i1++) {
// random numbers [0, 1]
pts[i0][i1] += bgs * (0.5 - rand.nextDouble());
}
for (i0=0; i0<dim1; i0++) for (i1=0; i1<dim; i1++) {
pts[nrs+i0][i1] = mxy[1][i1] + wrk[i1][i0] * mxy[0][i1];
}
for (i1=1, i0=2; i0<dim1; i0++) i1 *= i0;
tsz = TSIZE * i1;
int[][] tmp = new int[tsz + 1][dim];
// storage allocation - increase value of `i1' for 3D if necessary
i1 *= (nrs + 50 * i1);
/* WLH 4 Nov 97 */
if (dim == 3) i1 *= 10;
/* end WLH 4 Nov 97 */
int[] id = new int[i1];
for (i0=0; i0<i1; i0++) id[i0] = i0;
int[][] a3s = new int[i1][dim1];
float[][] ccr = new float[i1][dim1];
for (a3s[0][0]=nrs, i0=1; i0<dim1; i0++) a3s[0][i0] = a3s[0][i0-1] + 1;
for (ccr[0][dim]=BIGNUM, i0=0; i0<dim; i0++) ccr[0][i0] = 0;
nts = i4 = 1;
dm = dim - 1;
for (i0=0; i0<nrs; i0++) {
i1 = i7 = -1;
i9 = 0;
Loop3:
for (i11=0; i11<nts; i11++) {
i1++;
while (a3s[i1][0] < 0) i1++;
xx = ccr[i1][dim];
for (i2=0; i2<dim; i2++) {
xx -= (pts[i0][i2] - ccr[i1][i2]) * (pts[i0][i2] - ccr[i1][i2]);
if (xx<0) continue Loop3;
}
i9--;
i4--;
id[i4] = i1;
Loop2:
for (i2=0; i2<dim1; i2++) {
ii[0] = 0;
if (ii[0] == i2) ii[0]++;
for (i3=1; i3<dim; i3++) {
ii[i3] = ii[i3-1] + 1;
if (ii[i3] == i2) ii[i3]++;
}
if (i7>dm) {
i8 = i7;
Loop1:
for (i3=0; i3<=i8; i3++) {
for (i5=0; i5<dim; i5++) {
if (a3s[i1][ii[i5]] != tmp[i3][i5]) continue Loop1;
}
for (i6=0; i6<dim; i6++) tmp[i3][i6] = tmp[i8][i6];
i7--;
continue Loop2;
}
}
if (++i7 > tsz) {
int newtsz = 2 * tsz;
int[][] newtmp = new int[newtsz + 1][dim];
System.arraycopy(tmp, 0, newtmp, 0, tsz);
tsz = newtsz;
tmp = newtmp;
// WLH 23 july 97
// throw new VisADException(
// "DelaunayWatson: Temporary storage exceeded");
}
for (i3=0; i3<dim; i3++) tmp[i7][i3] = a3s[i1][ii[i3]];
}
a3s[i1][0] = -1;
}
for (i1=0; i1<=i7; i1++) {
for (i2=0; i2<dim; i2++) {
for (wrk[i2][dim]=0, i3=0; i3<dim; i3++) {
wrk[i2][i3] = pts[tmp[i1][i2]][i3] - pts[i0][i3];
wrk[i2][dim] += wrk[i2][i3] * (pts[tmp[i1][i2]][i3]
+ pts[i0][i3]) / 2;
}
}
if (dim < 3) {
xx = wrk[0][0] * wrk[1][1] - wrk[1][0] * wrk[0][1];
ccr[id[i4]][0] = (wrk[0][2] * wrk[1][1]
- wrk[1][2] * wrk[0][1]) / xx;
ccr[id[i4]][1] = (wrk[0][0] * wrk[1][2]
- wrk[1][0] * wrk[0][2]) / xx;
}
else {
xx = (wrk[0][0] * (wrk[1][1] * wrk[2][2] - wrk[2][1] * wrk[1][2]))
- (wrk[0][1] * (wrk[1][0] * wrk[2][2] - wrk[2][0] * wrk[1][2]))
+ (wrk[0][2] * (wrk[1][0] * wrk[2][1] - wrk[2][0] * wrk[1][1]));
ccr[id[i4]][0] = ((wrk[0][3] * (wrk[1][1] * wrk[2][2]
- wrk[2][1] * wrk[1][2]))
- (wrk[0][1] * (wrk[1][3] * wrk[2][2]
- wrk[2][3] * wrk[1][2]))
+ (wrk[0][2] * (wrk[1][3] * wrk[2][1]
- wrk[2][3] * wrk[1][1]))) / xx;
ccr[id[i4]][1] = ((wrk[0][0] * (wrk[1][3] * wrk[2][2]
- wrk[2][3] * wrk[1][2]))
- (wrk[0][3] * (wrk[1][0] * wrk[2][2]
- wrk[2][0] * wrk[1][2]))
+ (wrk[0][2] * (wrk[1][0] * wrk[2][3]
- wrk[2][0] * wrk[1][3]))) / xx;
ccr[id[i4]][2] = ((wrk[0][0] * (wrk[1][1] * wrk[2][3]
- wrk[2][1] * wrk[1][3]))
- (wrk[0][1] * (wrk[1][0] * wrk[2][3]
- wrk[2][0] * wrk[1][3]))
+ (wrk[0][3] * (wrk[1][0] * wrk[2][1]
- wrk[2][0] * wrk[1][1]))) / xx;
}
for (ccr[id[i4]][dim]=0, i2=0; i2<dim; i2++) {
ccr[id[i4]][dim] += (pts[i0][i2] - ccr[id[i4]][i2])
* (pts[i0][i2] - ccr[id[i4]][i2]);
a3s[id[i4]][i2] = tmp[i1][i2];
}
a3s[id[i4]][dim] = i0;
i4++;
i9++;
}
nts += i9;
}
/* OUTPUT is in a3s ARRAY
needed output is:
Tri - array of pointers from triangles or tetrahedra to their
corresponding vertices
Vertices - array of pointers from vertices to their
corresponding triangles or tetrahedra
Walk - array of pointers from triangles or tetrahedra to neighboring
triangles or tetrahedra
Edges - array of pointers from each triangle or tetrahedron's edges
to their corresponding triangles or tetrahedra
helpers:
nverts - number of triangles or tetrahedra per vertex
*/
// compute number of triangles or tetrahedra
int[] nverts = new int[nrs];
for (int i=0; i<nrs; i++) nverts[i] = 0;
int ntris = 0;
i0 = -1;
for (i11=0; i11<nts; i11++) {
i0++;
while (a3s[i0][0] < 0) i0++;
if (a3s[i0][0] < nrs) {
ntris++;
if (dim < 3) {
nverts[a3s[i0][0]]++;
nverts[a3s[i0][1]]++;
nverts[a3s[i0][2]]++;
}
else {
nverts[a3s[i0][0]]++;
nverts[a3s[i0][1]]++;
nverts[a3s[i0][2]]++;
nverts[a3s[i0][3]]++;
}
}
}
Vertices = new int[nrs][];
for (int i=0; i<nrs; i++) Vertices[i] = new int[nverts[i]];
for (int i=0; i<nrs; i++) nverts[i] = 0;
// build Tri & Vertices components
Tri = new int[ntris][dim1];
int a, b, c, d;
int itri = 0;
i0 = -1;
for (i11=0; i11<nts; i11++) {
i0++;
while (a3s[i0][0] < 0) i0++;
if (a3s[i0][0] < nrs) {
if (dim < 3) {
a = a3s[i0][0];
b = a3s[i0][1];
c = a3s[i0][2];
Vertices[a][nverts[a]] = itri;
nverts[a]++;
Vertices[b][nverts[b]] = itri;
nverts[b]++;
Vertices[c][nverts[c]] = itri;
nverts[c]++;
Tri[itri][0] = a;
Tri[itri][1] = b;
Tri[itri][2] = c;
}
else {
a = a3s[i0][0];
b = a3s[i0][1];
c = a3s[i0][2];
d = a3s[i0][3];
Vertices[a][nverts[a]] = itri;
nverts[a]++;
Vertices[b][nverts[b]] = itri;
nverts[b]++;
Vertices[c][nverts[c]] = itri;
nverts[c]++;
Vertices[d][nverts[d]] = itri;
nverts[d]++;
Tri[itri][0] = a;
Tri[itri][1] = b;
Tri[itri][2] = c;
Tri[itri][3] = d;
}
itri++;
}
}
// call more generic method for constructing Walk and Edges arrays
finish_triang(samples);
}
|
diff --git a/src/com/amd/myhomework/adapters/SimpleListAdapter.java b/src/com/amd/myhomework/adapters/SimpleListAdapter.java
index 4e23381..f89ee7d 100644
--- a/src/com/amd/myhomework/adapters/SimpleListAdapter.java
+++ b/src/com/amd/myhomework/adapters/SimpleListAdapter.java
@@ -1,65 +1,65 @@
package com.amd.myhomework.adapters;
import java.util.List;
import android.content.Context;
import android.graphics.Color;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.amd.myhomework.R;
import com.amd.myhomework.models.MyHomeworkModel;
/**
* This list adapter can be used for homework, or for classes or any list that simply
* want to display a simple text view with a colored background
* @author Josh Ault
*
*/
public class SimpleListAdapter<T extends MyHomeworkModel> extends BaseAdapter {
List<T> items;
Context context;
int borderColor, backgroundColor;
public SimpleListAdapter(Context context, List<T> items) {
this.items = items;
this.context = context;
}
@Override
public int getCount() {
return items.size();
}
@Override
public Object getItem(int position) {
return items.get(position);
}
@Override
public long getItemId(int position) {
return 0;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = vi.inflate(R.layout.adapter_item, null);
MyHomeworkModel model = items.get(position);
TextView txtGroup = (TextView) view.findViewById(R.id.adapter_item_lbl_name);
txtGroup.setText(model.getName());
- view.setBackgroundColor(Color.argb(60, Color.red(model.getColor()), Color.green(model.getColor()), Color.blue(model.getColor())));
+ view.setBackgroundColor(model.getColor());
- view.findViewById(R.id.adapter_item_transparent).setBackgroundColor(model.getColor());
+ view.findViewById(R.id.adapter_item_transparent).setBackgroundColor(Color.argb(60, Color.red(model.getColor()), Color.green(model.getColor()), Color.blue(model.getColor())));
return view;
}
}
| false | true | public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = vi.inflate(R.layout.adapter_item, null);
MyHomeworkModel model = items.get(position);
TextView txtGroup = (TextView) view.findViewById(R.id.adapter_item_lbl_name);
txtGroup.setText(model.getName());
view.setBackgroundColor(Color.argb(60, Color.red(model.getColor()), Color.green(model.getColor()), Color.blue(model.getColor())));
view.findViewById(R.id.adapter_item_transparent).setBackgroundColor(model.getColor());
return view;
}
| public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = vi.inflate(R.layout.adapter_item, null);
MyHomeworkModel model = items.get(position);
TextView txtGroup = (TextView) view.findViewById(R.id.adapter_item_lbl_name);
txtGroup.setText(model.getName());
view.setBackgroundColor(model.getColor());
view.findViewById(R.id.adapter_item_transparent).setBackgroundColor(Color.argb(60, Color.red(model.getColor()), Color.green(model.getColor()), Color.blue(model.getColor())));
return view;
}
|
diff --git a/src/edu/mines/alterego/CharacterDBHelper.java b/src/edu/mines/alterego/CharacterDBHelper.java
index 9c85d4e..bedd98b 100644
--- a/src/edu/mines/alterego/CharacterDBHelper.java
+++ b/src/edu/mines/alterego/CharacterDBHelper.java
@@ -1,118 +1,118 @@
package edu.mines.alterego;
import android.content.Context;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.Cursor;
import android.util.Log;
import android.util.Pair;
import android.widget.ListView;
import java.util.Date;
import java.util.ArrayList;
/**
* <h1>SQLite Database Adapter (helper as Google/Android calls it)</h1>
*
* Offers many static functions that can be used to update or view game-statistics in the database
* The API follows the general rule of first aquiring the database via 'getWritable/ReadableDatabase',
* then using the static functions defined in this class to interact with the database.
*
* @author: Matt Buland
*/
public class CharacterDBHelper extends SQLiteOpenHelper {
private static final String DB_NAME = "";
private static final int DB_VERSION = 1;
public CharacterDBHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
}
/**
* For an SQLiteOpenHelper, the onCreate method is called if and only if
* the database-name in question does not already exist. Theoretically,
* this should only happen once ever, and after the one time, updates
* will be applied for schema updates.
*/
@Override
public void onCreate(SQLiteDatabase database) {
/*
* Game table: Base unifying game_id construct
* The game is used to reference
*/
database.execSQL("CREATE TABLE IF NOT EXISTS game ( " +
"game_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"name TEXT," +
")");
database.execSQL("CREATE TABLE IF NOT EXISTS character ( " +
"character_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"game_id INTEGER," +
"name TEXT," +
"description TEXT," +
"FOREIGN KEY(game_id) REFERECES game(game_id)" +
")");
database.execSQL("CREATE TABLE IF NOT EXISTS inventory_item ( "+
"inventory_item_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"character_id INTEGER," +
"FOREIGN KEY(character_id) REFERECES character(character_id)" +
")");
database.execSQL("CREATE TABLE IF NOT EXISTS character_stat ( " +
"character_stat_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"character_id INTEGER," +
"stat_value INTEGER," +
"stat_name INTEGER," +
"description/usage/etc INTEGER," +
"category_id INTEGER," +
"FOREIGN KEY(character_id) REFERECES character(character_id)" +
"FOREIGN KEY(category_id) REFERECES category(category_id)" +
")");
database.execSQL("CREATE TABLE IF NOT EXISTS item_stat ( " +
"item_stat_id INTEGER PRIMARY KEY AUTOINCREMENT," +
- "entity_id INTEGER," +
+ "inventory_item_id INTEGER," +
"stat_value INTEGER," +
"stat_name INTEGER," +
"description/usage/etc INTEGER," +
"category_id INTEGER," +
"FOREIGN KEY(category_id) REFERECES category(category_id)" +
"FOREIGN KEY(inventory_item_id) REFERECES inventory_item(inventory_item_id)" +
")");
database.execSQL("CREATE TABLE IF NOT EXISTS category ( " +
"category_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"category_name TEXT" +
")");
database.execSQL("CREATE TABLE IF NOT EXISTS note ( " +
"note_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"game_id INTEGER," +
"note TEXT" +
"FOREIGN KEY(game_id) REFERECES game(game_id)" +
")");
/* Example DDL from Matt's Quidditch scoring app
database.execSQL("CREATE TABLE IF NOT EXISTS score ( " +
"score_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"score_datetime INTEGER, " +
"team_id INTEGER, " + // team_id is a number identifying the team. In this first revision, it will be 0 or 1 for left and right
"amount INTEGER, " +
"snitch INTEGER, " +
"game_id INTEGER, " +
"FOREIGN KEY(game_id) REFERENCES game(game_id) )");
*/
}
@Override
public void onUpgrade(SQLiteDatabase database, int oldVersion, int newVersion) {
// Do nothing.
}
}
| true | true | public void onCreate(SQLiteDatabase database) {
/*
* Game table: Base unifying game_id construct
* The game is used to reference
*/
database.execSQL("CREATE TABLE IF NOT EXISTS game ( " +
"game_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"name TEXT," +
")");
database.execSQL("CREATE TABLE IF NOT EXISTS character ( " +
"character_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"game_id INTEGER," +
"name TEXT," +
"description TEXT," +
"FOREIGN KEY(game_id) REFERECES game(game_id)" +
")");
database.execSQL("CREATE TABLE IF NOT EXISTS inventory_item ( "+
"inventory_item_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"character_id INTEGER," +
"FOREIGN KEY(character_id) REFERECES character(character_id)" +
")");
database.execSQL("CREATE TABLE IF NOT EXISTS character_stat ( " +
"character_stat_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"character_id INTEGER," +
"stat_value INTEGER," +
"stat_name INTEGER," +
"description/usage/etc INTEGER," +
"category_id INTEGER," +
"FOREIGN KEY(character_id) REFERECES character(character_id)" +
"FOREIGN KEY(category_id) REFERECES category(category_id)" +
")");
database.execSQL("CREATE TABLE IF NOT EXISTS item_stat ( " +
"item_stat_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"entity_id INTEGER," +
"stat_value INTEGER," +
"stat_name INTEGER," +
"description/usage/etc INTEGER," +
"category_id INTEGER," +
"FOREIGN KEY(category_id) REFERECES category(category_id)" +
"FOREIGN KEY(inventory_item_id) REFERECES inventory_item(inventory_item_id)" +
")");
database.execSQL("CREATE TABLE IF NOT EXISTS category ( " +
"category_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"category_name TEXT" +
")");
database.execSQL("CREATE TABLE IF NOT EXISTS note ( " +
"note_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"game_id INTEGER," +
"note TEXT" +
"FOREIGN KEY(game_id) REFERECES game(game_id)" +
")");
/* Example DDL from Matt's Quidditch scoring app
database.execSQL("CREATE TABLE IF NOT EXISTS score ( " +
"score_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"score_datetime INTEGER, " +
"team_id INTEGER, " + // team_id is a number identifying the team. In this first revision, it will be 0 or 1 for left and right
"amount INTEGER, " +
"snitch INTEGER, " +
"game_id INTEGER, " +
"FOREIGN KEY(game_id) REFERENCES game(game_id) )");
*/
}
| public void onCreate(SQLiteDatabase database) {
/*
* Game table: Base unifying game_id construct
* The game is used to reference
*/
database.execSQL("CREATE TABLE IF NOT EXISTS game ( " +
"game_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"name TEXT," +
")");
database.execSQL("CREATE TABLE IF NOT EXISTS character ( " +
"character_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"game_id INTEGER," +
"name TEXT," +
"description TEXT," +
"FOREIGN KEY(game_id) REFERECES game(game_id)" +
")");
database.execSQL("CREATE TABLE IF NOT EXISTS inventory_item ( "+
"inventory_item_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"character_id INTEGER," +
"FOREIGN KEY(character_id) REFERECES character(character_id)" +
")");
database.execSQL("CREATE TABLE IF NOT EXISTS character_stat ( " +
"character_stat_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"character_id INTEGER," +
"stat_value INTEGER," +
"stat_name INTEGER," +
"description/usage/etc INTEGER," +
"category_id INTEGER," +
"FOREIGN KEY(character_id) REFERECES character(character_id)" +
"FOREIGN KEY(category_id) REFERECES category(category_id)" +
")");
database.execSQL("CREATE TABLE IF NOT EXISTS item_stat ( " +
"item_stat_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"inventory_item_id INTEGER," +
"stat_value INTEGER," +
"stat_name INTEGER," +
"description/usage/etc INTEGER," +
"category_id INTEGER," +
"FOREIGN KEY(category_id) REFERECES category(category_id)" +
"FOREIGN KEY(inventory_item_id) REFERECES inventory_item(inventory_item_id)" +
")");
database.execSQL("CREATE TABLE IF NOT EXISTS category ( " +
"category_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"category_name TEXT" +
")");
database.execSQL("CREATE TABLE IF NOT EXISTS note ( " +
"note_id INTEGER PRIMARY KEY AUTOINCREMENT," +
"game_id INTEGER," +
"note TEXT" +
"FOREIGN KEY(game_id) REFERECES game(game_id)" +
")");
/* Example DDL from Matt's Quidditch scoring app
database.execSQL("CREATE TABLE IF NOT EXISTS score ( " +
"score_id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"score_datetime INTEGER, " +
"team_id INTEGER, " + // team_id is a number identifying the team. In this first revision, it will be 0 or 1 for left and right
"amount INTEGER, " +
"snitch INTEGER, " +
"game_id INTEGER, " +
"FOREIGN KEY(game_id) REFERENCES game(game_id) )");
*/
}
|
diff --git a/sphinx4/edu/cmu/sphinx/frontend/DataProcessor.java b/sphinx4/edu/cmu/sphinx/frontend/DataProcessor.java
index e390d99db..9f6decc6b 100644
--- a/sphinx4/edu/cmu/sphinx/frontend/DataProcessor.java
+++ b/sphinx4/edu/cmu/sphinx/frontend/DataProcessor.java
@@ -1,228 +1,230 @@
/*
* Copyright 1999-2002 Carnegie Mellon University.
* Portions Copyright 2002 Sun Microsystems, Inc.
* Portions Copyright 2002 Mitsubishi Electronic Research Laboratories.
* All Rights Reserved. Use is subject to license terms.
*
* See the file "license.terms" for information on usage and
* redistribution of this file, and for a DISCLAIMER OF ALL
* WARRANTIES.
*
*/
package edu.cmu.sphinx.frontend;
import edu.cmu.sphinx.util.SphinxProperties;
import edu.cmu.sphinx.util.Timer;
import java.io.IOException;
/**
* DataProcessor contains the common elements of all frontend data
* processors, namely the name, context, timers, SphinxProperties,
* and dumping. It also contains the acoustic properties object from
* which acoustic model properties can be queried.
*/
public abstract class DataProcessor {
/**
* The name of this DataProcessor.
*/
private String name;
/**
* The context of this DataProcessor.
*/
private String context;
/**
* A Timer for timing processing.
*/
private Timer timer;
/**
* Indicates whether to dump the processed Data
*/
private boolean dump = false;
/**
* The SphinxProperties used by this DataProcessor
*/
private SphinxProperties sphinxProperties;
// true if processing Data objects within an Utterance
private boolean inUtterance;
/**
* Constructs a default DataProcessor
*/
public DataProcessor() {}
/**
* Constructs a DataProcessor with the given name and context.
*
* @param name the name of this DataProcessor
* @param context the context of this DataProcessor
*/
public DataProcessor(String name, String context) {
initialize(name, context, null);
}
/**
* Constructs a DataProcessor of the given name and at the given context.
*
* @param name the name of this DataProcessor
* @param context the context of this DataProcessor
* @param sphinxProperties the sphinx properties used
*/
public DataProcessor(String name, String context,
SphinxProperties sphinxProperties) {
initialize(name, context, sphinxProperties);
}
/**
* Initializes this DataProcessor.
*
* @param name the name of this DataProcessor
* @param context the context of this DataProcessor
* @param sphinxProperties the SphinxProperties to use
*/
public void initialize(String name, String context,
SphinxProperties sphinxProperties) {
this.name = name;
this.context = context;
this.sphinxProperties = sphinxProperties;
this.timer = Timer.getTimer(context, name);
}
/**
* Returns the name of this DataProcessor.
*
* @return the name of this DataProcessor
*/
public final String getName() {
return name;
}
/**
* Returns the context of this DataProcessor.
*
* @return the context of this DataProcessor
*/
public final String getContext() {
return context;
}
/**
* Returns the SphinxProperties used by this DataProcessor.
*
* @return the SphinxProperties
*/
public final SphinxProperties getSphinxProperties() {
if (sphinxProperties != null) {
return sphinxProperties;
} else {
return SphinxProperties.getSphinxProperties(getContext());
}
}
/**
* Sets the SphinxProperties to use.
*
* @param sphinxProperties the SphinxProperties to use
*/
public void setSphinxProperties(SphinxProperties sphinxProperties) {
this.sphinxProperties = sphinxProperties;
}
/**
* Returns the Timer for metrics collection purposes.
*
* @return the Timer
*/
public final Timer getTimer() {
return timer;
}
/**
* Determine whether to dump the output for debug purposes.
*
* @return true to dump, false to not dump
*/
public final boolean getDump() {
return this.dump;
}
/**
* Set whether we should dump the output for debug purposes.
*
* @param dump true to dump the output; false otherwise
*/
public void setDump(boolean dump) {
this.dump = dump;
}
/**
* Returns the name of this DataProcessor.
*
* @return the name of this DataProcessor
*/
public String toString() {
return name;
}
/**
* Does sanity check on whether the Signals UTTERANCE_START and
* UTTERANCE_END are in sequence. Throws an Error if:
* <ol>
* <li> We have not received an UTTERANCE_START Signal before
* receiving an Signal/Data.
* <li> We received an UTTERANCE_START after an UTTERANCE_START
* without an intervening UTTERANCE_END;
* </ol>
*
* @throws Error if the UTTERANCE_START and UTTERANCE_END signals
* are not in sequence
*/
protected void signalCheck(Data data) {
if (!inUtterance) {
if (data != null) {
if (data.hasSignal(Signal.UTTERANCE_START)) {
inUtterance = true;
+ } else if (data.hasSignal(Signal.UTTERANCE_END)) {
+ throw new Error(getName() + ": too many UTTERANCE_END.");
} else {
throw new Error(getName() + ": no UTTERANCE_START");
}
}
} else {
if (data == null) {
throw new Error
(getName() + ": unexpected return of null Data");
} else if (data.hasSignal(Signal.UTTERANCE_END)) {
inUtterance = false;
} else if (data.hasSignal(Signal.UTTERANCE_START)) {
throw new Error(getName() + ": too many UTTERANCE_START");
}
}
}
}
| true | true | protected void signalCheck(Data data) {
if (!inUtterance) {
if (data != null) {
if (data.hasSignal(Signal.UTTERANCE_START)) {
inUtterance = true;
} else {
throw new Error(getName() + ": no UTTERANCE_START");
}
}
} else {
if (data == null) {
throw new Error
(getName() + ": unexpected return of null Data");
} else if (data.hasSignal(Signal.UTTERANCE_END)) {
inUtterance = false;
} else if (data.hasSignal(Signal.UTTERANCE_START)) {
throw new Error(getName() + ": too many UTTERANCE_START");
}
}
}
| protected void signalCheck(Data data) {
if (!inUtterance) {
if (data != null) {
if (data.hasSignal(Signal.UTTERANCE_START)) {
inUtterance = true;
} else if (data.hasSignal(Signal.UTTERANCE_END)) {
throw new Error(getName() + ": too many UTTERANCE_END.");
} else {
throw new Error(getName() + ": no UTTERANCE_START");
}
}
} else {
if (data == null) {
throw new Error
(getName() + ": unexpected return of null Data");
} else if (data.hasSignal(Signal.UTTERANCE_END)) {
inUtterance = false;
} else if (data.hasSignal(Signal.UTTERANCE_START)) {
throw new Error(getName() + ": too many UTTERANCE_START");
}
}
}
|
diff --git a/src/Map.java b/src/Map.java
index f348595..bf5ab26 100644
--- a/src/Map.java
+++ b/src/Map.java
@@ -1,77 +1,77 @@
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
public class Map {
private Tile[][] map;
private File inputfile;
private Scanner scan;
private int xDimension;
private int yDimension;
private Character character;
private SpriteSheet worldSprites;
private ArrayList<MoveTile> movingTiles = new ArrayList<MoveTile>();
public static final int TILE_DEPTH = 5;
public static final int BLOCK_SIZE = 32;
public Map(String filename) {
worldSprites = new SpriteSheet("images/platformTiles.gif");
inputfile = new File(filename);
try {
scan = new Scanner(inputfile);
xDimension = scan.nextInt();
yDimension = scan.nextInt();
map = new Tile[xDimension][yDimension];
readmap();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public Tile[][] getMap(){return map;}
private void readmap() {
while(scan.hasNext()){
for(int j = 0; j< yDimension; j++){
for(int i = 0; i< xDimension; i++){
int item = scan.nextInt();
if(item==17){
character = new Character(i*BLOCK_SIZE,j*BLOCK_SIZE);
map[i][j] = new BackgroundTile(BLOCK_SIZE,BLOCK_SIZE,i*BLOCK_SIZE,j*BLOCK_SIZE,TILE_DEPTH,new ImageWrapper(0, BLOCK_SIZE, BLOCK_SIZE,worldSprites));
}else if(item<0){
map[i][j] = new DestTile(BLOCK_SIZE, BLOCK_SIZE, i*BLOCK_SIZE, j*BLOCK_SIZE, TILE_DEPTH,
new ImageWrapper(item*-1, BLOCK_SIZE, BLOCK_SIZE, worldSprites),
new ImageWrapper(0, BLOCK_SIZE, BLOCK_SIZE, worldSprites));
}else if(item>17){
map[i][j] = new BackgroundTile(BLOCK_SIZE, BLOCK_SIZE, i*BLOCK_SIZE, j*BLOCK_SIZE,
TILE_DEPTH, new ImageWrapper(item, BLOCK_SIZE, BLOCK_SIZE, worldSprites));
movingTiles.add(new MoveTile(BLOCK_SIZE, BLOCK_SIZE, i*BLOCK_SIZE, j*BLOCK_SIZE,
- TILE_DEPTH, new ImageWrapper(item-18, BLOCK_SIZE, BLOCK_SIZE, worldSprites),
- true, 10, 200, 8));
+ TILE_DEPTH, new ImageWrapper(item-17, BLOCK_SIZE, BLOCK_SIZE, worldSprites),
+ true, 10, 200, 8)); //minus 17 as dont want acces to moving background tiles
}else{
ImageWrapper imgwrap = new ImageWrapper(item, BLOCK_SIZE, BLOCK_SIZE, worldSprites);
if(item==0)
map[i][j] = new BackgroundTile(BLOCK_SIZE, BLOCK_SIZE, i*BLOCK_SIZE, j*BLOCK_SIZE, TILE_DEPTH, imgwrap);
else
map[i][j] = new FloorTile(BLOCK_SIZE,BLOCK_SIZE,i*BLOCK_SIZE,j*BLOCK_SIZE,TILE_DEPTH,imgwrap);
}
}
}
}
}
public Character getCharacter() {
return character;
}
public ArrayList<MoveTile> movingTiles(){
return this.movingTiles;
}
}
| true | true | private void readmap() {
while(scan.hasNext()){
for(int j = 0; j< yDimension; j++){
for(int i = 0; i< xDimension; i++){
int item = scan.nextInt();
if(item==17){
character = new Character(i*BLOCK_SIZE,j*BLOCK_SIZE);
map[i][j] = new BackgroundTile(BLOCK_SIZE,BLOCK_SIZE,i*BLOCK_SIZE,j*BLOCK_SIZE,TILE_DEPTH,new ImageWrapper(0, BLOCK_SIZE, BLOCK_SIZE,worldSprites));
}else if(item<0){
map[i][j] = new DestTile(BLOCK_SIZE, BLOCK_SIZE, i*BLOCK_SIZE, j*BLOCK_SIZE, TILE_DEPTH,
new ImageWrapper(item*-1, BLOCK_SIZE, BLOCK_SIZE, worldSprites),
new ImageWrapper(0, BLOCK_SIZE, BLOCK_SIZE, worldSprites));
}else if(item>17){
map[i][j] = new BackgroundTile(BLOCK_SIZE, BLOCK_SIZE, i*BLOCK_SIZE, j*BLOCK_SIZE,
TILE_DEPTH, new ImageWrapper(item, BLOCK_SIZE, BLOCK_SIZE, worldSprites));
movingTiles.add(new MoveTile(BLOCK_SIZE, BLOCK_SIZE, i*BLOCK_SIZE, j*BLOCK_SIZE,
TILE_DEPTH, new ImageWrapper(item-18, BLOCK_SIZE, BLOCK_SIZE, worldSprites),
true, 10, 200, 8));
}else{
ImageWrapper imgwrap = new ImageWrapper(item, BLOCK_SIZE, BLOCK_SIZE, worldSprites);
if(item==0)
map[i][j] = new BackgroundTile(BLOCK_SIZE, BLOCK_SIZE, i*BLOCK_SIZE, j*BLOCK_SIZE, TILE_DEPTH, imgwrap);
else
map[i][j] = new FloorTile(BLOCK_SIZE,BLOCK_SIZE,i*BLOCK_SIZE,j*BLOCK_SIZE,TILE_DEPTH,imgwrap);
}
}
}
}
}
| private void readmap() {
while(scan.hasNext()){
for(int j = 0; j< yDimension; j++){
for(int i = 0; i< xDimension; i++){
int item = scan.nextInt();
if(item==17){
character = new Character(i*BLOCK_SIZE,j*BLOCK_SIZE);
map[i][j] = new BackgroundTile(BLOCK_SIZE,BLOCK_SIZE,i*BLOCK_SIZE,j*BLOCK_SIZE,TILE_DEPTH,new ImageWrapper(0, BLOCK_SIZE, BLOCK_SIZE,worldSprites));
}else if(item<0){
map[i][j] = new DestTile(BLOCK_SIZE, BLOCK_SIZE, i*BLOCK_SIZE, j*BLOCK_SIZE, TILE_DEPTH,
new ImageWrapper(item*-1, BLOCK_SIZE, BLOCK_SIZE, worldSprites),
new ImageWrapper(0, BLOCK_SIZE, BLOCK_SIZE, worldSprites));
}else if(item>17){
map[i][j] = new BackgroundTile(BLOCK_SIZE, BLOCK_SIZE, i*BLOCK_SIZE, j*BLOCK_SIZE,
TILE_DEPTH, new ImageWrapper(item, BLOCK_SIZE, BLOCK_SIZE, worldSprites));
movingTiles.add(new MoveTile(BLOCK_SIZE, BLOCK_SIZE, i*BLOCK_SIZE, j*BLOCK_SIZE,
TILE_DEPTH, new ImageWrapper(item-17, BLOCK_SIZE, BLOCK_SIZE, worldSprites),
true, 10, 200, 8)); //minus 17 as dont want acces to moving background tiles
}else{
ImageWrapper imgwrap = new ImageWrapper(item, BLOCK_SIZE, BLOCK_SIZE, worldSprites);
if(item==0)
map[i][j] = new BackgroundTile(BLOCK_SIZE, BLOCK_SIZE, i*BLOCK_SIZE, j*BLOCK_SIZE, TILE_DEPTH, imgwrap);
else
map[i][j] = new FloorTile(BLOCK_SIZE,BLOCK_SIZE,i*BLOCK_SIZE,j*BLOCK_SIZE,TILE_DEPTH,imgwrap);
}
}
}
}
}
|
diff --git a/src/me/mcandze/plugin/zeareas/area/Area2D.java b/src/me/mcandze/plugin/zeareas/area/Area2D.java
index 228349f..21487cf 100644
--- a/src/me/mcandze/plugin/zeareas/area/Area2D.java
+++ b/src/me/mcandze/plugin/zeareas/area/Area2D.java
@@ -1,82 +1,82 @@
package me.mcandze.plugin.zeareas.area;
import java.util.ArrayList;
import java.util.List;
import me.mcandze.plugin.zeareas.util.BlockLocation;
import org.bukkit.Location;
import org.bukkit.World;
/**
* A class for 2-dimensional areas.
* It simply ignores the Y-axis and creates a cuboid from sky to bedrock, limited by the Z and X axis.
* @author andreas
*
*/
public class Area2D extends CuboidArea{
private BlockLocation location1, location2;
private World world;
private double lowX, lowZ, highX, highZ;
private AreaOwner owner;
public Area2D(Location location1, Location location2){
this.location1 = BlockLocation.toBlockLocation(location1);
this.location2 = BlockLocation.toBlockLocation(location2);
this.world = location1.getWorld();
this.recalcMinimum();
this.owner = new OwnerServer();
}
public Area2D(Location location1, Location location2, AreaOwner owner){
this(location1, location2);
this.owner = owner;
}
@Override
public List<BlockLocation> getPoints() {
List<BlockLocation> toReturn = new ArrayList<BlockLocation>();
toReturn.add(location1);
toReturn.add(location2);
return toReturn;
}
@Override
public boolean isLocationInArea(BlockLocation location) {
double x = location.getX();
double z = location.getZ();
return location.getWorld().equals(this.world) && (x > lowX && x < highX && z > lowZ && z < highZ);
}
/**
* Re-calculates the furthermost points on the z and x axis for measurement.
*/
public void recalcMinimum(){
lowX = Math.min(location1.getX(), location2.getX());
lowZ = Math.min(location1.getZ(), location2.getZ());
highX = Math.max(location1.getX(), location2.getX());
highZ = Math.max(location1.getZ(), location2.getZ());
}
/**
* Get the World this area is located in.
* @return
*/
public World getWorld() {
return world;
}
@Override
public BlockLocation[] getCorners() {
BlockLocation[] list = new BlockLocation[4];
list[0] = this.location1;
list[1] = this.location2;
list[2] = new BlockLocation(Math.max(list[0].getX(), list[1].getX()),
Math.max(list[0].getZ(), list[1].getZ()),
list[0].getY(), list[0].getWorld());
list[3] = new BlockLocation(Math.min(list[0].getX(), list[1].getX()),
- Math.max(list[0].getZ(), list[1].getZ()),
+ Math.min(list[0].getZ(), list[1].getZ()),
list[0].getY(), list[0].getWorld());
return list;
}
}
| true | true | public BlockLocation[] getCorners() {
BlockLocation[] list = new BlockLocation[4];
list[0] = this.location1;
list[1] = this.location2;
list[2] = new BlockLocation(Math.max(list[0].getX(), list[1].getX()),
Math.max(list[0].getZ(), list[1].getZ()),
list[0].getY(), list[0].getWorld());
list[3] = new BlockLocation(Math.min(list[0].getX(), list[1].getX()),
Math.max(list[0].getZ(), list[1].getZ()),
list[0].getY(), list[0].getWorld());
return list;
}
| public BlockLocation[] getCorners() {
BlockLocation[] list = new BlockLocation[4];
list[0] = this.location1;
list[1] = this.location2;
list[2] = new BlockLocation(Math.max(list[0].getX(), list[1].getX()),
Math.max(list[0].getZ(), list[1].getZ()),
list[0].getY(), list[0].getWorld());
list[3] = new BlockLocation(Math.min(list[0].getX(), list[1].getX()),
Math.min(list[0].getZ(), list[1].getZ()),
list[0].getY(), list[0].getWorld());
return list;
}
|
diff --git a/source/RMG/jing/rxnSys/ReactionModelGenerator.java b/source/RMG/jing/rxnSys/ReactionModelGenerator.java
index 8b713a8c..ade45cd7 100644
--- a/source/RMG/jing/rxnSys/ReactionModelGenerator.java
+++ b/source/RMG/jing/rxnSys/ReactionModelGenerator.java
@@ -1,5238 +1,5242 @@
////////////////////////////////////////////////////////////////////////////////
//
// RMG - Reaction Mechanism Generator
//
// Copyright (c) 2002-2011 Prof. William H. Green ([email protected]) and the
// RMG Team ([email protected])
//
// 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 jing.rxnSys;
import java.io.*;
import jing.rxnSys.ReactionSystem;
import jing.rxn.*;
import jing.chem.*;
import java.util.*;
import jing.mathTool.UncertainDouble;
import jing.param.*;
import jing.chemUtil.*;
import jing.chemParser.*;
//## package jing::rxnSys
//----------------------------------------------------------------------------
// jing\rxnSys\ReactionModelGenerator.java
//----------------------------------------------------------------------------
//## class ReactionModelGenerator
public class ReactionModelGenerator {
protected LinkedList timeStep;
protected ReactionModel reactionModel;
protected String workingDirectory;
protected LinkedList reactionSystemList;
protected int paraInfor;
protected boolean error;
protected boolean sensitivity;
protected LinkedList species;
protected LinkedList initialStatusList;
protected double rtol;
protected static double atol;
protected PrimaryKineticLibrary primaryKineticLibrary;
protected ReactionLibrary ReactionLibrary;
protected ReactionModelEnlarger reactionModelEnlarger;
protected LinkedHashSet speciesSeed;
protected ReactionGenerator reactionGenerator;
protected LibraryReactionGenerator lrg;
protected LinkedList tempList;
protected LinkedList presList;
protected LinkedList validList;
protected LinkedList initList = new LinkedList();
protected LinkedList beginList = new LinkedList();
protected LinkedList endList = new LinkedList();
protected LinkedList lastTList = new LinkedList();
protected LinkedList currentTList = new LinkedList();
protected LinkedList lastPList = new LinkedList();
protected LinkedList currentPList = new LinkedList();
protected LinkedList conditionChangedList = new LinkedList();
protected LinkedList reactionChangedList = new LinkedList();
protected int numConversions;
protected String equationOfState;
// 24Jun2009 MRH: variable stores the first temperature encountered in the condition.txt file
// This temperature is used to select the "best" kinetics from the rxn library
protected static Temperature temp4BestKinetics;
protected static boolean useDiffusion;
protected static boolean useSolvation;
protected SeedMechanism seedMechanism = null;
protected PrimaryThermoLibrary primaryThermoLibrary;
protected PrimaryTransportLibrary primaryTransportLibrary;
protected PrimaryAbrahamLibrary primaryAbrahamLibrary;
protected static SolventData solvent;
protected SolventLibrary solventLibrary;
protected static double viscosity;
protected boolean readrestart = false;
protected boolean writerestart = false;
protected LinkedHashSet restartCoreSpcs = new LinkedHashSet();
protected LinkedHashSet restartEdgeSpcs = new LinkedHashSet();
protected LinkedHashSet restartCoreRxns = new LinkedHashSet();
protected LinkedHashSet restartEdgeRxns = new LinkedHashSet();
// Constructors
private HashSet specs = new HashSet();
//public static native long getCpuTime();
//static {System.loadLibrary("cpuTime");}
public static boolean rerunFame = false;
protected static double tolerance;//can be interpreted as "coreTol" (vs. edgeTol)
protected static double termTol;
protected static double edgeTol;
protected static int minSpeciesForPruning;
protected static int maxEdgeSpeciesAfterPruning;
public int limitingReactantID = 1;
public int numberOfEquivalenceRatios = 0;
//## operation ReactionModelGenerator()
public ReactionModelGenerator() {
workingDirectory = System.getProperty("RMG.workingDirectory");
}
//## operation initializeReactionSystem()
//10/24/07 gmagoon: changed name to initializeReactionSystems
public void initializeReactionSystems() throws InvalidSymbolException, IOException {
//#[ operation initializeReactionSystem()
try {
String initialConditionFile = System.getProperty("jing.rxnSys.ReactionModelGenerator.conditionFile");
if (initialConditionFile == null) {
Logger.critical("undefined system property: jing.rxnSys.ReactionModelGenerator.conditionFile");
System.exit(0);
}
//double sandeep = getCpuTime();
//System.out.println(getCpuTime()/1e9/60);
FileReader in = new FileReader(initialConditionFile);
BufferedReader reader = new BufferedReader(in);
//TemperatureModel temperatureModel = null;//10/27/07 gmagoon: commented out
//PressureModel pressureModel = null;//10/27/07 gmagoon: commented out
// ReactionModelEnlarger reactionModelEnlarger = null;//10/9/07 gmagoon: commented out: unneeded now and causes scope problems
FinishController finishController = null;
//DynamicSimulator dynamicSimulator = null;//10/27/07 gmagoon: commented out and replaced with following line
LinkedList dynamicSimulatorList = new LinkedList();
setPrimaryKineticLibrary(null);//10/14/07 gmagoon: changed to use setPrimaryReactionLibrary
double [] conversionSet = new double[50];
String line = ChemParser.readMeaningfulLine(reader, true);
/*if (line.startsWith("Restart")){
StringTokenizer st = new StringTokenizer(line);
String token = st.nextToken();
token = st.nextToken();
if (token.equalsIgnoreCase("true")) {
//Runtime.getRuntime().exec("cp Restart/allSpecies.txt Restart/allSpecies1.txt");
//Runtime.getRuntime().exec("echo >> allSpecies.txt");
restart = true;
}
else if (token.equalsIgnoreCase("false")) {
Runtime.getRuntime().exec("rm Restart/allSpecies.txt");
restart = false;
}
else throw new InvalidSymbolException("UnIdentified Symbol "+token+" after Restart:");
}
else throw new InvalidSymbolException("Can't find Restart!");*/
//line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Database")){//svp
line = ChemParser.readMeaningfulLine(reader, true);
}
else throw new InvalidSymbolException("Can't find database!");
// if (line.startsWith("PrimaryThermoLibrary")){//svp
// line = ChemParser.readMeaningfulLine(reader);
// }
// else throw new InvalidSymbolException("Can't find primary thermo library!");
/*
* Added by MRH on 15-Jun-2009
* Give user the option to change the maximum carbon, oxygen,
* and/or radical number for all species. These lines will be
* optional in the condition.txt file. Values are hard-
* coded into RMG (in ChemGraph.java), but any user-
* defined input will override these values.
*/
/*
* Moved from before InitialStatus to before PrimaryThermoLibary
* by MRH on 27-Oct-2009
* Overriding default values of maximum number of "X" per
* chemgraph should come before RMG attempts to make any
* chemgraph. The first instance RMG will attempt to make a
* chemgraph is in reading the primary thermo library.
*/
line = readMaxAtomTypes(line,reader);
// if (line.startsWith("MaxCarbonNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxCarbonNumberPerSpecies:"
// int maxCNum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxCarbonNumber(maxCNum);
// System.out.println("Note: Overriding RMG-defined MAX_CARBON_NUM with user-defined value: " + maxCNum);
// line = ChemParser.readMeaningfulLine(reader);
// }
// if (line.startsWith("MaxOxygenNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxOxygenNumberPerSpecies:"
// int maxONum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxOxygenNumber(maxONum);
// System.out.println("Note: Overriding RMG-defined MAX_OXYGEN_NUM with user-defined value: " + maxONum);
// line = ChemParser.readMeaningfulLine(reader);
// }
// if (line.startsWith("MaxRadicalNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxRadicalNumberPerSpecies:"
// int maxRadNum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxRadicalNumber(maxRadNum);
// System.out.println("Note: Overriding RMG-defined MAX_RADICAL_NUM with user-defined value: " + maxRadNum);
// line = ChemParser.readMeaningfulLine(reader);
// }
// if (line.startsWith("MaxSulfurNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxSulfurNumberPerSpecies:"
// int maxSNum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxSulfurNumber(maxSNum);
// System.out.println("Note: Overriding RMG-defined MAX_SULFUR_NUM with user-defined value: " + maxSNum);
// line = ChemParser.readMeaningfulLine(reader);
// }
// if (line.startsWith("MaxSiliconNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxSiliconNumberPerSpecies:"
// int maxSiNum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxSiliconNumber(maxSiNum);
// System.out.println("Note: Overriding RMG-defined MAX_SILICON_NUM with user-defined value: " + maxSiNum);
// line = ChemParser.readMeaningfulLine(reader);
// }
// if (line.startsWith("MaxHeavyAtom")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxHeavyAtomPerSpecies:"
// int maxHANum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxHeavyAtomNumber(maxHANum);
// System.out.println("Note: Overriding RMG-defined MAX_HEAVYATOM_NUM with user-defined value: " + maxHANum);
// line = ChemParser.readMeaningfulLine(reader);
// }
/*
* Read in the Primary Thermo Library
* MRH 7-Jul-2009
*/
if (line.startsWith("PrimaryThermoLibrary:")) {
/*
* MRH 27Feb2010:
* Changing the "read in Primary Thermo Library information" code
* into it's own method.
*
* Other modules (e.g. PopulateReactions) will be utilizing the exact code.
* Rather than copying and pasting code into other modules, just have
* everything call this new method: readAndMakePTL
*/
readAndMakePTL(reader);
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate PrimaryThermoLibrary field");
line = ChemParser.readMeaningfulLine(reader, true);
/*
* MRH 17-May-2010:
* Added primary transport library field
*/
if (line.toLowerCase().startsWith("primarytransportlibrary")) {
readAndMakePTransL(reader);
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate PrimaryTransportLibrary field.");
line = ChemParser.readMeaningfulLine(reader, true);
// Extra forbidden structures may be specified after the Primary Thermo Library
if (line.startsWith("ForbiddenStructures:")) {
readExtraForbiddenStructures(reader);
line = ChemParser.readMeaningfulLine(reader, true);
}
if (line.toLowerCase().startsWith("readrestart")) {
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken(); // "ReadRestart:"
tempString = st.nextToken();
if (tempString.toLowerCase().equals("yes")) {
readrestart = true;
readRestartSpecies();
readRestartReactions();
} else readrestart = false;
line = ChemParser.readMeaningfulLine(reader, true);
} else throw new InvalidSymbolException("Cannot locate ReadRestart field");
if (line.toLowerCase().startsWith("writerestart")) {
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken(); // "WriteRestart:"
tempString = st.nextToken();
if (tempString.toLowerCase().equals("yes"))
writerestart = true;
else writerestart = false;
line = ChemParser.readMeaningfulLine(reader, true);
} else throw new InvalidSymbolException("Cannot locate WriteRestart field");
// read temperature model
//gmagoon 10/23/07: modified to handle multiple temperatures; note that this requires different formatting of units in condition.txt
if (line.startsWith("TemperatureModel:")) {
createTModel(line);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String modelType = st.nextToken();
// //String t = st.nextToken();
// String unit = st.nextToken();
// unit = ChemParser.removeBrace(unit);
// if (modelType.equals("Constant")) {
// tempList = new LinkedList();
// //read first temperature
// double t = Double.parseDouble(st.nextToken());
// tempList.add(new ConstantTM(t, unit));
// Temperature temp = new Temperature(t, unit);//10/29/07 gmagoon: added this line and next two lines to set Global.lowTemperature and Global.highTemperature
// Global.lowTemperature = (Temperature)temp.clone();
// Global.highTemperature = (Temperature)temp.clone();
// //read remaining temperatures
// while (st.hasMoreTokens()) {
// t = Double.parseDouble(st.nextToken());
// tempList.add(new ConstantTM(t, unit));
// temp = new Temperature(t,unit);//10/29/07 gmagoon: added this line and next two "if" statements to set Global.lowTemperature and Global.highTemperature
// if(temp.getK() < Global.lowTemperature.getK())
// Global.lowTemperature = (Temperature)temp.clone();
// if(temp.getK() > Global.highTemperature.getK())
// Global.highTemperature = (Temperature)temp.clone();
// }
// // Global.temperature = new Temperature(t,unit);
// }
//10/23/07 gmagoon: commenting out; further updates needed to get this to work
//else if (modelType.equals("Curved")) {
// String t = st.nextToken();
// // add reading curved temperature function here
// temperatureModel = new CurvedTM(new LinkedList());
//}
// else {
// throw new InvalidSymbolException("condition.txt: Unknown TemperatureModel = " + modelType);
// }
}
else throw new InvalidSymbolException("condition.txt: can't find TemperatureModel!");
// read in pressure model
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("PressureModel:")) {
createPModel(line);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String modelType = st.nextToken();
// //String p = st.nextToken();
// String unit = st.nextToken();
// unit = ChemParser.removeBrace(unit);
// if (modelType.equals("Constant")) {
// presList = new LinkedList();
// //read first pressure
// double p = Double.parseDouble(st.nextToken());
// Pressure pres = new Pressure(p, unit);
// Global.lowPressure = (Pressure)pres.clone();
// Global.highPressure = (Pressure)pres.clone();
// presList.add(new ConstantPM(p, unit));
// //read remaining temperatures
// while (st.hasMoreTokens()) {
// p = Double.parseDouble(st.nextToken());
// presList.add(new ConstantPM(p, unit));
// pres = new Pressure(p, unit);
// if(pres.getBar() < Global.lowPressure.getBar())
// Global.lowPressure = (Pressure)pres.clone();
// if(pres.getBar() > Global.lowPressure.getBar())
// Global.highPressure = (Pressure)pres.clone();
// }
// //Global.pressure = new Pressure(p, unit);
// }
// //10/23/07 gmagoon: commenting out; further updates needed to get this to work
// //else if (modelType.equals("Curved")) {
// // // add reading curved pressure function here
// // pressureModel = new CurvedPM(new LinkedList());
// //}
// else {
// throw new InvalidSymbolException("condition.txt: Unknown PressureModel = " + modelType);
// }
}
else throw new InvalidSymbolException("condition.txt: can't find PressureModel!");
// after PressureModel comes an optional line EquationOfState
// if "EquationOfState: Liquid" is found then initial concentrations are assumed to be correct
// if it is ommited, then initial concentrations are normalised to ensure PV=NRT (ideal gas law)
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("EquationOfState")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String eosType = st.nextToken().toLowerCase();
if (eosType.equals("liquid")) {
equationOfState="Liquid";
Logger.info("Equation of state: Liquid. Relying on concentrations in input file to get density correct; not checking PV=NRT");
}
line = ChemParser.readMeaningfulLine(reader, true);
}
// Read in InChI generation
if (line.startsWith("InChIGeneration:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String inchiOnOff = st.nextToken().toLowerCase();
if (inchiOnOff.equals("on")) {
Species.useInChI = true;
} else if (inchiOnOff.equals("off")) {
Species.useInChI = false;
}
else throw new InvalidSymbolException("condition.txt: Unknown InChIGeneration flag: " + inchiOnOff);
line = ChemParser.readMeaningfulLine(reader, true);
}
// Read in Solvation effects
if (line.startsWith("Solvation:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String solvationOnOff = st.nextToken().toLowerCase();
if (solvationOnOff.equals("on")) {
setUseSolvation(true);
Species.useSolvation = true;
readAndMakePAL();
String solventname = st.nextToken().toLowerCase();
readAndMakeSL(solventname);
Logger.info(String.format(
"Using solvation corrections to thermochemsitry with solvent properties of %s",solventname));
} else if (solvationOnOff.startsWith("off")) {
setUseSolvation(false);
Species.useSolvation = false;
}
else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff);
line = ChemParser.readMeaningfulLine(reader, true);
}
// Read in Diffusion effects
// If 'Diffusion' is 'on' then override the settings made by the solvation flag and sets solvation 'on'
if (line.startsWith("Diffusion:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String diffusionOnOff = st.nextToken().toLowerCase();
if (diffusionOnOff.equals("on")) {
String viscosity_str = st.nextToken();
viscosity = Double.parseDouble(viscosity_str);
setUseDiffusion(true);
Logger.info(String.format(
"Using diffusion corrections to kinetics with solvent viscosity of %.3g Pa.s.",viscosity));
} else if (diffusionOnOff.equals("off")) {
setUseDiffusion(false);
}
else throw new InvalidSymbolException("condition.txt: Unknown diffusion flag: " + diffusionOnOff);
line = ChemParser.readMeaningfulLine(reader,true);//read in reactants or thermo line
}
/* AJ 12JULY2010:
* Right now we do not want RMG to throw an exception if it cannot find a diffusion flag
*/
//else throw new InvalidSymbolException("condition.txt: Cannot find diffusion flag.");
// Should have already read in reactants or thermo line into variable 'line'
// Read in optional QM thermo generation
if (line.startsWith("ThermoMethod:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String thermoMethod = st.nextToken().toLowerCase();
if (thermoMethod.equals("qm")) {
ChemGraph.useQM = true;
if(st.hasMoreTokens()){//override the default qmprogram ("both") if there are more; current options: "gaussian03" and "mopac" and of course, "both"
QMTP.qmprogram = st.nextToken().toLowerCase();
}
line=ChemParser.readMeaningfulLine(reader, true);
if(line.startsWith("QMForCyclicsOnly:")){
StringTokenizer st2 = new StringTokenizer(line);
String nameCyc = st2.nextToken();
String option = st2.nextToken().toLowerCase();
if (option.equals("on")) {
ChemGraph.useQMonCyclicsOnly = true;
}
}
else{
Logger.critical("condition.txt: Can't find 'QMForCyclicsOnly:' field");
System.exit(0);
}
line=ChemParser.readMeaningfulLine(reader, true);
if(line.startsWith("MaxRadNumForQM:")){
StringTokenizer st3 = new StringTokenizer(line);
String nameRadNum = st3.nextToken();
Global.maxRadNumForQM = Integer.parseInt(st3.nextToken());
}
else{
Logger.critical("condition.txt: Can't find 'MaxRadNumForQM:' field");
System.exit(0);
}
}//otherwise, the flag useQM will remain false by default and the traditional group additivity approach will be used
line = ChemParser.readMeaningfulLine(reader, true);//read in reactants
}
// // Read in Solvation effects
// if (line.startsWith("Solvation:")) {
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String solvationOnOff = st.nextToken().toLowerCase();
// if (solvationOnOff.equals("on")) {
// Species.useSolvation = true;
// } else if (solvationOnOff.equals("off")) {
// Species.useSolvation = false;
// }
// else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff);
// }
// else throw new InvalidSymbolException("condition.txt: Cannot find solvation flag.");
// read in reactants
//
//10/4/07 gmagoon: moved to initializeCoreEdgeReactionModel
//LinkedHashSet p_speciesSeed = new LinkedHashSet();//gmagoon 10/4/07: changed to p_speciesSeed
//setSpeciesSeed(p_speciesSeed);//gmagoon 10/4/07: added
LinkedHashMap speciesSet = new LinkedHashMap();
/*
* 7/Apr/2010: MRH
* Neither of these variables are utilized
*/
// LinkedHashMap speciesStatus = new LinkedHashMap();
// int speciesnum = 1;
//System.out.println(line);
if (line.startsWith("InitialStatus")) {
speciesSet = populateInitialStatusListWithReactiveSpecies(reader);
// line = ChemParser.readMeaningfulLine(reader);
// while (!line.equals("END")) {
// StringTokenizer st = new StringTokenizer(line);
// String index = st.nextToken();
// String name = null;
// if (!index.startsWith("(")) name = index;
// else name = st.nextToken();
// //if (restart) name += "("+speciesnum+")";
// // 24Jun2009: MRH
// // Check if the species name begins with a number.
// // If so, terminate the program and inform the user to choose
// // a different name. This is implemented so that the chem.inp
// // file generated will be valid when run in Chemkin
// try {
// int doesNameBeginWithNumber = Integer.parseInt(name.substring(0,1));
// System.out.println("\nA species name should not begin with a number." +
// " Please rename species: " + name + "\n");
// System.exit(0);
// } catch (NumberFormatException e) {
// // We're good
// }
// speciesnum ++;
// if (!(st.hasMoreTokens())) throw new InvalidSymbolException("Couldn't find concentration of species: "+name);
// String conc = st.nextToken();
// double concentration = Double.parseDouble(conc);
// String unit = st.nextToken();
// unit = ChemParser.removeBrace(unit);
// if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
// concentration /= 1000;
// unit = "mol/cm3";
// }
// else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
// concentration /= 1000000;
// unit = "mol/cm3";
// }
// else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
// concentration /= 6.022e23;
// }
// else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
// throw new InvalidUnitException("Species Concentration in condition.txt!");
// }
//
// //GJB to allow "unreactive" species that only follow user-defined library reactions.
// // They will not react according to RMG reaction families
// boolean IsReactive = true;
// boolean IsConstantConcentration = false;
// while (st.hasMoreTokens()) {
// String reactive = st.nextToken().trim();
// if (reactive.equalsIgnoreCase("unreactive"))
// IsReactive = false;
// if (reactive.equalsIgnoreCase("constantconcentration"))
// IsConstantConcentration=true;
// }
//
// Graph g = ChemParser.readChemGraph(reader);
// ChemGraph cg = null;
// try {
// cg = ChemGraph.make(g);
// }
// catch (ForbiddenStructureException e) {
// System.out.println("Forbidden Structure:\n" + e.getMessage());
// throw new InvalidSymbolException("A species in the input file has a forbidden structure.");
// }
// //System.out.println(name);
// Species species = Species.make(name,cg);
// species.setReactivity(IsReactive); // GJB
// species.setConstantConcentration(IsConstantConcentration);
// speciesSet.put(name, species);
// getSpeciesSeed().add(species);
// double flux = 0;
// int species_type = 1; // reacted species
// SpeciesStatus ss = new SpeciesStatus(species,species_type,concentration,flux);
// speciesStatus.put(species, ss);
// line = ChemParser.readMeaningfulLine(reader);
// }
// ReactionTime initial = new ReactionTime(0,"S");
// //10/23/07 gmagoon: modified for handling multiple temperature, pressure conditions; note: concentration within speciesStatus (and list of conversion values) should not need to be modified for each T,P since this is done within isTPCconsistent in ReactionSystem
// initialStatusList = new LinkedList();
// for (Iterator iter = tempList.iterator(); iter.hasNext(); ) {
// TemperatureModel tm = (TemperatureModel)iter.next();
// for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){
// PressureModel pm = (PressureModel)iter2.next();
// // LinkedHashMap speStat = (LinkedHashMap)speciesStatus.clone();//10/31/07 gmagoon: trying creating multiple instances of speciesStatus to address issues with concentration normalization (last normalization seems to apply to all)
// Set ks = speciesStatus.keySet();
// LinkedHashMap speStat = new LinkedHashMap();
// for (Iterator iter3 = ks.iterator(); iter3.hasNext();){//11/1/07 gmagoon: perform deep copy; (is there an easier or more elegant way to do this?)
// SpeciesStatus ssCopy = (SpeciesStatus)speciesStatus.get(iter3.next());
// speStat.put(ssCopy.getSpecies(),new SpeciesStatus(ssCopy.getSpecies(),ssCopy.getSpeciesType(),ssCopy.getConcentration(),ssCopy.getFlux()));
// }
// initialStatusList.add(new InitialStatus(speStat,tm.getTemperature(initial),pm.getPressure(initial)));
// }
// }
}
else throw new InvalidSymbolException("condition.txt: can't find InitialStatus!");
// read in inert gas concentration
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("InertGas:")) {
populateInitialStatusListWithInertSpecies(reader);
// line = ChemParser.readMeaningfulLine(reader);
// while (!line.equals("END")) {
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken().trim();
// String conc = st.nextToken();
// double inertConc = Double.parseDouble(conc);
// String unit = st.nextToken();
// unit = ChemParser.removeBrace(unit);
// if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
// inertConc /= 1000;
// unit = "mol/cm3";
// }
// else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
// inertConc /= 1000000;
// unit = "mol/cm3";
// }
// else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
// inertConc /= 6.022e23;
// unit = "mol/cm3";
// }
// else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
// throw new InvalidUnitException("Inert Gas Concentration not recognized: " + unit);
// }
//
// //SystemSnapshot.putInertGas(name,inertConc);
// for(Iterator iter=initialStatusList.iterator();iter.hasNext(); ){//6/23/09 gmagoon: needed to change this to accommodate non-static inertConc
// ((InitialStatus)iter.next()).putInertGas(name,inertConc);
// }
// line = ChemParser.readMeaningfulLine(reader);
// }
}
else throw new InvalidSymbolException("condition.txt: can't find Inert gas concentration!");
// read in spectroscopic data estimator
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("SpectroscopicDataEstimator:")) {
setSpectroscopicDataMode(line);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String sdeType = st.nextToken().toLowerCase();
// if (sdeType.equals("frequencygroups") || sdeType.equals("default")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
// }
// else if (sdeType.equals("therfit") || sdeType.equals("threefrequencymodel")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY;
// }
// else if (sdeType.equals("off") || sdeType.equals("none")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.OFF;
// }
// else throw new InvalidSymbolException("condition.txt: Unknown SpectroscopicDataEstimator = " + sdeType);
}
else throw new InvalidSymbolException("condition.txt: can't find SpectroscopicDataEstimator!");
// pressure dependence and related flags
line = ChemParser.readMeaningfulLine(reader, true);
if (line.toLowerCase().startsWith("pressuredependence:"))
line = setPressureDependenceOptions(line,reader);
else
throw new InvalidSymbolException("condition.txt: can't find PressureDependence flag!");
if (readrestart) if (PDepNetwork.generateNetworks) readPDepNetworks();
// include species (optional)
/*
*
* MRH 3-APR-2010:
* This if statement is no longer necessary and was causing an error
* when the PressureDependence field was set to "off"
*/
// if (!PDepRateConstant.getMode().name().equals("CHEBYSHEV") &&
// !PDepRateConstant.getMode().name().equals("PDEPARRHENIUS"))
// line = ChemParser.readMeaningfulLine(reader);
// read in finish controller
if (line.startsWith("FinishController")) {
line = ChemParser.readMeaningfulLine(reader, true);
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String goal = st.nextToken();
String type = st.nextToken();
TerminationTester tt;
if (type.startsWith("Conversion")) {
LinkedList spc = new LinkedList();
while (st.hasMoreTokens()) {
String name = st.nextToken();
Species spe = (Species)speciesSet.get(name);
if (spe == null) throw new InvalidConversionException("Unknown reactant in 'Goal Conversion' field of input file : " + name);
setLimitingReactantID(spe.getID());
String conv = st.nextToken();
double conversion;
try {
if (conv.endsWith("%")) {
conversion = Double.parseDouble(conv.substring(0,conv.length()-1))/100;
}
else {
conversion = Double.parseDouble(conv);
}
conversionSet[49] = conversion;
}
catch (NumberFormatException e) {
throw new NumberFormatException("wrong number format for conversion in initial condition file!");
}
SpeciesConversion sc = new SpeciesConversion(spe, conversion);
spc.add(sc);
}
tt = new ConversionTT(spc);
}
else if (type.startsWith("ReactionTime")) {
double time = Double.parseDouble(st.nextToken());
String unit = ChemParser.removeBrace(st.nextToken());
ReactionTime rt = new ReactionTime(time, unit);
tt = new ReactionTimeTT(rt);
}
else {
throw new InvalidSymbolException("condition.txt: Unknown FinishController = " + type);
}
line = ChemParser.readMeaningfulLine(reader, true);
st = new StringTokenizer(line, ":");
String temp = st.nextToken();
String tol = st.nextToken();
try {
if (tol.endsWith("%")) {
tolerance = Double.parseDouble(tol.substring(0,tol.length()-1))/100;
}
else {
tolerance = Double.parseDouble(tol);
}
}
catch (NumberFormatException e) {
throw new NumberFormatException("wrong number format for conversion in initial condition file!");
}
ValidityTester vt = null;
if (reactionModelEnlarger instanceof RateBasedRME) vt = new RateBasedVT(tolerance);
else if (reactionModelEnlarger instanceof RateBasedPDepRME) vt = new RateBasedPDepVT(tolerance);
else throw new InvalidReactionModelEnlargerException();
finishController = new FinishController(tt, vt);
}
else throw new InvalidSymbolException("condition.txt: can't find FinishController!");
// read in dynamic simulator
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("DynamicSimulator")) {
StringTokenizer st = new StringTokenizer(line,":");
String temp = st.nextToken();
String simulator = st.nextToken().trim();
//read in non-negative option if it exists: syntax would be something like this: "DynamicSimulator: DASSL: non-negative"
if (st.hasMoreTokens()){
if (st.nextToken().trim().toLowerCase().equals("non-negative")){
if(simulator.toLowerCase().equals("dassl")) JDAS.nonnegative = true;
else{
Logger.critical("Non-negative option is currently only supported for DASSL. Switch to DASSL solver or remove non-negative option.");
System.exit(0);
}
}
}
numConversions = 0;//5/6/08 gmagoon: moved declaration from initializeReactionSystem() to be an attribute so it can be accessed by modelGenerator()
//int numConversions = 0;
boolean autoflag = false;//5/2/08 gmagoon: updating the following if/else-if block to consider input where we want to check model validity within the ODE solver at each time step; this will be indicated by the use of a string beginning with "AUTO" after the "TimeStep" or "Conversions" line
// read in time step
line = ChemParser.readMeaningfulLine(reader, true);
- if (line.startsWith("TimeStep:") && finishController.terminationTester instanceof ReactionTimeTT) {
+ if (line.startsWith("TimeStep:")) {
+ if (!(finishController.terminationTester instanceof ReactionTimeTT))
+ throw new InvalidSymbolException("'TimeStep:' specified but finish controller goal is not reaction time.");
st = new StringTokenizer(line);
temp = st.nextToken();
while (st.hasMoreTokens()) {
temp = st.nextToken();
if (temp.startsWith("AUTO")){//note potential opportunity for making case insensitive by using: temp.toUpperCase().startsWith("AUTO")
autoflag=true;
}
else if (!autoflag){//use "else if" to make sure additional numbers are not read in case numbers are erroneously used following AUTO; note that there could still be a problem if numbers come before "AUTO"
double tStep = Double.parseDouble(temp);
String unit = "sec";
setTimeStep(new ReactionTime(tStep, unit));
}
}
((ReactionTimeTT)finishController.terminationTester).setTimeSteps(timeStep);
}
- else if (line.startsWith("Conversions:") && finishController.terminationTester instanceof ConversionTT){
+ else if (line.startsWith("Conversions:")){
+ if (!(finishController.terminationTester instanceof ConversionTT))
+ throw new InvalidSymbolException("'Conversions:' specified but finish controller goal is not conversion.");
st = new StringTokenizer(line);
temp = st.nextToken();
int i=0;
SpeciesConversion sc = (SpeciesConversion)((ConversionTT)finishController.terminationTester).speciesGoalConversionSet.get(0);
Species convSpecies = sc.species;
Iterator iter = ((InitialStatus)(initialStatusList.get(0))).getSpeciesStatus();//10/23/07 gmagoon: changed to use first element of initialStatusList, as subsequent operations should not be affected by which one is chosen
double initialConc = 0;
while (iter.hasNext()){
SpeciesStatus sps = (SpeciesStatus)iter.next();
if (sps.species.equals(convSpecies)) initialConc = sps.concentration;
}
while (st.hasMoreTokens()){
temp=st.nextToken();
if (temp.startsWith("AUTO")){
autoflag=true;
}
else if (!autoflag){
double conv = Double.parseDouble(temp);
conversionSet[i] = (1-conv) * initialConc;
i++;
}
}
conversionSet[i] = (1 - conversionSet[49])* initialConc;
numConversions = i+1;
}
- else throw new InvalidSymbolException("condition.txt: can't find time step for dynamic simulator!");
+ else throw new InvalidSymbolException("In condition file can't find 'TimeStep:' or 'Conversions:' for dynamic simulator.");
//
if (temp.startsWith("AUTOPRUNE")){//for the AUTOPRUNE case, read in additional lines for termTol and edgeTol
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("TerminationTolerance:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
termTol = Double.parseDouble(st.nextToken());
}
else {
Logger.critical("Cannot find TerminationTolerance in condition.txt");
System.exit(0);
}
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("PruningTolerance:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
edgeTol = Double.parseDouble(st.nextToken());
}
else {
Logger.critical("Cannot find PruningTolerance in condition.txt");
System.exit(0);
}
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("MinSpeciesForPruning:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
minSpeciesForPruning = Integer.parseInt(st.nextToken());
}
else {
Logger.critical("Cannot find MinSpeciesForPruning in condition.txt");
System.exit(0);
}
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("MaxEdgeSpeciesAfterPruning:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
maxEdgeSpeciesAfterPruning = Integer.parseInt(st.nextToken());
}
else {
Logger.critical("Cannot find MaxEdgeSpeciesAfterPruning in condition.txt");
System.exit(0);
}
//print header for pruning log (based on restart format)
BufferedWriter bw = null;
try {
File f = new File("Pruning/edgeReactions.txt");
bw = new BufferedWriter(new FileWriter("Pruning/edgeReactions.txt", true));
String EaUnits = ArrheniusKinetics.getEaUnits();
bw.write("UnitsOfEa: " + EaUnits);
bw.newLine();
} catch (FileNotFoundException ex) {
Logger.logStackTrace(ex);
} catch (IOException ex) {
Logger.logStackTrace(ex);
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
Logger.logStackTrace(ex);
}
}
}
else if (temp.startsWith("AUTO")){//in the non-autoprune case (i.e. original AUTO functionality), we set the new parameters to values that should reproduce original functionality
termTol = tolerance;
edgeTol = 0;
minSpeciesForPruning = 999999;//arbitrary high number (actually, the value here should not matter, since pruning should not be done)
maxEdgeSpeciesAfterPruning = 999999;
}
// read in atol
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Atol:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
atol = Double.parseDouble(st.nextToken());
}
else throw new InvalidSymbolException("condition.txt: can't find Atol for dynamic simulator!");
// read in rtol
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Rtol:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
String rel_tol = st.nextToken();
if (rel_tol.endsWith("%"))
rtol = Double.parseDouble(rel_tol.substring(0,rel_tol.length()-1));
else
rtol = Double.parseDouble(rel_tol);
}
else throw new InvalidSymbolException("condition.txt: can't find Rtol for dynamic simulator!");
if (simulator.equals("DASPK")) {
paraInfor = 0;//svp
// read in SA
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Error bars")) {//svp
st = new StringTokenizer(line,":");
temp = st.nextToken();
String sa = st.nextToken().trim();
if (sa.compareToIgnoreCase("on")==0) {
paraInfor = 1;
error = true;
}
else if (sa.compareToIgnoreCase("off")==0) {
paraInfor = 0;
error = false;
}
else throw new InvalidSymbolException("condition.txt: can't find error on/off information!");
}
else throw new InvalidSymbolException("condition.txt: can't find SA information!");
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Display sensitivity coefficients")){//svp
st = new StringTokenizer(line,":");
temp = st.nextToken();
String sa = st.nextToken().trim();
if (sa.compareToIgnoreCase("on")==0){
paraInfor = 1;
sensitivity = true;
}
else if (sa.compareToIgnoreCase("off")==0){
if (paraInfor != 1){
paraInfor = 0;
}
sensitivity = false;
}
else throw new InvalidSymbolException("condition.txt: can't find SA on/off information!");
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
//6/25/08 gmagoon: changed loop to use i index, and updated DASPK constructor to pass i (mirroring changes to DASSL
//6/25/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null?
for (int i = 0;i < initialStatusList.size();i++) {
dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i,finishController.getValidityTester(), autoflag, termTol, tolerance));
}
}
species = new LinkedList();
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Display sensitivity information") ){
line = ChemParser.readMeaningfulLine(reader, true);
Logger.info(line);
while (!line.equals("END")){
st = new StringTokenizer(line);
String name = st.nextToken();
if (name.toUpperCase().equals("ALL")) ReactionSystem.printAllSens = true; //gmagoon 12/22/09: if the line contains the word "all", turn on the flag to print out sensitivity information for everything
species.add(name);
line = ChemParser.readMeaningfulLine(reader, true);
}
}
}
else if (simulator.equals("DASSL")) {
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
// for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) {
// dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)iter.next()));
// }
//11/1/07 gmagoon: changed loop to use i index, and updated DASSL constructor to pass i
//5/5/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null?
for (int i = 0;i < initialStatusList.size();i++) {
dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i, finishController.getValidityTester(), autoflag, termTol, tolerance));
}
}
else if (simulator.equals("Chemkin")) {
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("ReactorType")) {
st = new StringTokenizer(line, ":");
temp = st.nextToken();
String reactorType = st.nextToken().trim();
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) {
//dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)iter.next()));
dynamicSimulatorList.add(new Chemkin(rtol, atol, reactorType));//11/4/07 gmagoon: fixing apparent cut/paste error
}
}
}
else throw new InvalidSymbolException("condition.txt: Unknown DynamicSimulator = " + simulator);
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList; note: although conversionSet should actually be different for each T,P condition, it will be modified in isTPCconsistent within ReactionSystem
for (Iterator iter = dynamicSimulatorList.iterator(); iter.hasNext(); ) {
double [] cs = conversionSet.clone();//11/1/07 gmagoon: trying to make sure multiple instances of conversionSet are used
((DynamicSimulator)(iter.next())).addConversion(cs, numConversions);
}
}
else throw new InvalidSymbolException("condition.txt: can't find DynamicSimulator!");
// read in reaction model enlarger
/* Read in the Primary Kinetic Library
* The user can specify as many PKLs,
* including none, as they like.
*/
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("PrimaryKineticLibrary:")) {
readAndMakePKL(reader);
} else throw new InvalidSymbolException("condition.txt: can't find PrimaryKineticLibrary");
// Reaction Library
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("ReactionLibrary:")) {
readAndMakeReactionLibrary(reader);
} else throw new InvalidSymbolException("condition.txt: can't find ReactionLibrary");
/*
* Added by MRH 12-Jun-2009
*
* The SeedMechanism acts almost exactly as the old
* PrimaryKineticLibrary did. Whatever is in the SeedMechanism
* will be placed in the core at the beginning of the simulation.
* The user can specify as many seed mechanisms as they like, with
* the priority (in the case of duplicates) given to the first
* instance. There is no on/off flag.
*/
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("SeedMechanism:")) {
line = ChemParser.readMeaningfulLine(reader, true);
while (!line.equals("END")) {
String name = extractLibraryName(line);
line = ChemParser.readMeaningfulLine(reader, true);
String[] tempString = line.split("Location: ");
String location = tempString[tempString.length-1].trim();
line = ChemParser.readMeaningfulLine(reader, true);
tempString = line.split("GenerateReactions: ");
String generateStr = tempString[tempString.length-1].trim();
boolean generate = true;
if (generateStr.equalsIgnoreCase("yes") ||
generateStr.equalsIgnoreCase("on") ||
generateStr.equalsIgnoreCase("true")){
generate = true;
Logger.info("Will generate cross-reactions between species in seed mechanism " + name);
} else if(generateStr.equalsIgnoreCase("no") ||
generateStr.equalsIgnoreCase("off") ||
generateStr.equalsIgnoreCase("false")) {
generate = false;
Logger.info("Will NOT initially generate cross-reactions between species in seed mechanism "+ name);
Logger.info("This may have unintended consequences");
}
else {
Logger.critical("Input file invalid");
Logger.critical("Please include a 'GenerateReactions: yes/no' line for seed mechanism "+name);
System.exit(0);
}
String path = System.getProperty("jing.rxn.ReactionLibrary.pathName");
path += "/" + location;
if (getSeedMechanism() == null)
setSeedMechanism(new SeedMechanism(name, path, generate, false));
else
getSeedMechanism().appendSeedMechanism(name, path, generate, false);
line = ChemParser.readMeaningfulLine(reader, true);
}
if (getSeedMechanism() != null) Logger.info("Seed Mechanisms in use: " + getSeedMechanism().getName());
else setSeedMechanism(null);
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate SeedMechanism field");
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("ChemkinUnits")) {
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Verbose:")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken();
String OnOff = st.nextToken().toLowerCase();
if (OnOff.equals("off")) {
ArrheniusKinetics.setVerbose(false);
} else if (OnOff.equals("on")) {
ArrheniusKinetics.setVerbose(true);
}
line = ChemParser.readMeaningfulLine(reader, true);
}
/*
* MRH 3MAR2010:
* Adding user option regarding chemkin file
*
* New field: If user would like the empty SMILES string
* printed with each species in the thermochemistry portion
* of the generated chem.inp file
*/
if (line.toUpperCase().startsWith("SMILES")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // Should be "SMILES:"
String OnOff = st.nextToken().toLowerCase();
if (OnOff.equals("off")) {
Chemkin.setSMILES(false);
} else if (OnOff.equals("on")) {
Chemkin.setSMILES(true);
/*
* MRH 9MAR2010:
* MRH decided not to generate an InChI for every new species
* during an RMG simulation (especially since it is not used
* for anything). Instead, they will only be generated in the
* post-processing, if the user asked for InChIs.
*/
//Species.useInChI = true;
}
line = ChemParser.readMeaningfulLine(reader, true);
}
if (line.startsWith("A")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // Should be "A:"
String units = st.nextToken();
if (units.equals("moles") || units.equals("molecules"))
ArrheniusKinetics.setAUnits(units);
else {
Logger.critical("Units for A were not recognized: " + units);
System.exit(0);
}
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate Chemkin units A field.");
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Ea")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // Should be "Ea:"
String units = st.nextToken();
if (units.equals("kcal/mol") || units.equals("cal/mol") ||
units.equals("kJ/mol") || units.equals("J/mol") || units.equals("Kelvins"))
ArrheniusKinetics.setEaUnits(units);
else {
Logger.critical("Units for Ea were not recognized: " + units);
System.exit(0);
}
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate Chemkin units Ea field.");
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate ChemkinUnits field.");
in.close();
//11/6/07 gmagoon: initializing temperatureArray and pressureArray before libraryReactionGenerator is initialized (initialization calls PDepNetwork and performs initializekLeak); UPDATE: moved after initialStatusList initialization (in case primaryKineticLibrary calls the similar pdep functions
// LinkedList temperatureArray = new LinkedList();
// LinkedList pressureArray = new LinkedList();
// Iterator iterIS = initialStatusList.iterator();
// for (Iterator iter = tempList.iterator(); iter.hasNext(); ) {
// TemperatureModel tm = (TemperatureModel)iter.next();
// for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){
// PressureModel pm = (PressureModel)iter2.next();
// InitialStatus is = (InitialStatus)iterIS.next();
// temperatureArray.add(tm.getTemperature(is.getTime()));
// pressureArray.add(pm.getPressure(is.getTime()));
// }
// }
// PDepNetwork.setTemperatureArray(temperatureArray);
// PDepNetwork.setPressureArray(pressureArray);
//10/4/07 gmagoon: moved to modelGeneration()
//ReactionGenerator p_reactionGenerator = new TemplateReactionGenerator();//10/4/07 gmagoon: changed to p_reactionGenerator from reactionGenerator
// setReactionGenerator(p_reactionGenerator);//10/4/07 gmagoon: added
/*
* MRH 12-Jun-2009
* A TemplateReactionGenerator now requires a Temperature be passed to it.
* This allows RMG to determine the "best" kinetic parameters to use
* in the mechanism generation. For now, I choose to pass the first
* temperature in the list of temperatures. RMG only outputs one mechanism,
* even for multiple temperature/pressure systems, so we can only have one
* set of kinetics.
*/
Temperature t = new Temperature(300,"K");
for (Iterator iter = tempList.iterator(); iter.hasNext();) {
TemperatureModel tm = (TemperatureModel)iter.next();
t = tm.getTemperature(new ReactionTime(0,"sec"));
setTemp4BestKinetics(t);
break;
}
setReactionGenerator(new TemplateReactionGenerator()); //11/4/07 gmagoon: moved from modelGeneration; mysteriously, moving this later moves "Father" lines up in output at runtime, immediately after condition file (as in original code); previously, these Father lines were just before "Can't read primary kinetic library files!"
lrg = new LibraryReactionGenerator(ReactionLibrary);//10/10/07 gmagoon: moved from modelGeneration (sequence lrg increases species id, and the different sequence was causing problems as main species id was 6 instead of 1); //10/31/07 gmagoon: restored this line from 10/10/07 backup: somehow it got lost along the way; 11/5/07 gmagoon: changed to use "lrg =" instead of setLibraryReactionGenerator
//10/24/07 gmagoon: updated to use multiple reactionSystem variables
reactionSystemList = new LinkedList();
// LinkedList temperatureArray = new LinkedList();//10/30/07 gmagoon: added temperatureArray variable for passing to PDepNetwork; 11/6/07 gmagoon: moved before initialization of lrg;
// LinkedList pressureArray = new LinkedList();//10/30/07 gmagoon: same for pressure;//UPDATE: commenting out: not needed if updateKLeak is done for one temperature/pressure at a time; 11/1-2/07 restored;11/6/07 gmagoon: moved before initialization of lrg;
Iterator iter3 = initialStatusList.iterator();
Iterator iter4 = dynamicSimulatorList.iterator();
int i = 0;//10/30/07 gmagoon: added
for (Iterator iter = tempList.iterator(); iter.hasNext(); ) {
TemperatureModel tm = (TemperatureModel)iter.next();
//InitialStatus is = (InitialStatus)iter3.next();//10/31/07 gmagoon: fixing apparent bug by moving these inside inner "for loop"
//DynamicSimulator ds = (DynamicSimulator)iter4.next();
for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){
PressureModel pm = (PressureModel)iter2.next();
for (int numConcList=0; numConcList<initialStatusList.size()/tempList.size()/presList.size(); ++numConcList) {
// InitialStatus is = (InitialStatus)iter3.next();//10/31/07 gmagoon: moved from outer "for loop""
InitialStatus is = (InitialStatus)initialStatusList.get(i); DynamicSimulator ds = (DynamicSimulator)iter4.next();
// temperatureArray.add(tm.getTemperature(is.getTime()));//10/30/07 gmagoon: added; //10/31/07 added .getTemperature(is.getTime()); 11/6/07 gmagoon: moved before initialization of lrg;
// pressureArray.add(pm.getPressure(is.getTime()));//10/30/07 gmagoon: added//UPDATE: commenting out: not needed if updateKLeak is done for one temperature/pressure at a time;11/1-2/07 restored with .getTemperature(is.getTime()) added;11/6/07 gmagoon: moved before initialization of lrg;
//11/1/07 gmagoon: trying to make a deep copy of terminationTester when it is instance of ConversionTT
//UPDATE: actually, I don't think this deep copy was necessary; original case with FinishController fc = new FinishController(finishController.getTerminationTester(), finishController.getValidityTester()) is probably OK; (in any case, this didn't do completetly deep copy (references to speciesConversion element in LinkedList were the same);
// TerminationTester termTestCopy;
// if (finishController.getTerminationTester() instanceof ConversionTT){
// ConversionTT termTest = (ConversionTT)finishController.getTerminationTester();
// LinkedList spcCopy = (LinkedList)(termTest.getSpeciesGoalConversionSetList().clone());
// termTestCopy = new ConversionTT(spcCopy);
// }
// else{
// termTestCopy = finishController.getTerminationTester();
// }
FinishController fc = new FinishController(finishController.getTerminationTester(), finishController.getValidityTester());//10/31/07 gmagoon: changed to create new finishController instance in each case (apparently, the finish controller becomes associated with reactionSystem in setFinishController within ReactionSystem); alteratively, could use clone, but might need to change FinishController to be "cloneable"
// FinishController fc = new FinishController(termTestCopy, finishController.getValidityTester());
i++;//10/30/07 gmagoon: added
Logger.info("Creating reaction system "+i);
reactionSystemList.add(new ReactionSystem(tm, pm, reactionModelEnlarger, fc, ds, getPrimaryKineticLibrary(), getReactionGenerator(), getSpeciesSeed(), is, getReactionModel(),lrg, i, equationOfState));
Logger.info((initialStatusList.get(i-1)).toString() + "\n");
}
}
}
// PDepNetwork.setTemperatureArray(temperatureArray);//10/30/07 gmagoon: passing temperatureArray to PDepNetwork; 11/6/07 gmagoon: moved before initialization of lrg;
// PDepNetwork.setPressureArray(pressureArray);//10/30/07 gmagoon: same for pressure;//UPDATE: commenting out: not needed if updateKLeak is done for one temperature/pressure at a time; 11/1-2/07 restored; 11/6/07 gmagoon: moved before initialization of lrg;
}
catch (IOException e) {
Logger.error("Error reading reaction system initialization file.");
throw new IOException("Input file error: " + e.getMessage());
}
Logger.info("");
}
public void setReactionModel(ReactionModel p_ReactionModel) {
reactionModel = p_ReactionModel;
}
public void modelGeneration() {
//long begin_t = System.currentTimeMillis();
try{
ChemGraph.readForbiddenStructure();
setSpeciesSeed(new LinkedHashSet());//10/4/07 gmagoon moved from initializeCoreEdgeReactionModel
// setReactionGenerator(new TemplateReactionGenerator());//10/4/07 gmagoon: moved inside initializeReactionSystem; 11/3-4/07 gmagoon: probably reverted on or before 10/10/07 (although I have not investigated this change in detail); //11/4/07 gmagoon: moved inside initializeReactionSystems
// setLibraryReactionGenerator(new LibraryReactionGenerator());//10/10/07 gmagoon: moved after initializeReactionSystem
// initializeCoreEdgeReactionModel();//10/4/07 gmagoon moved from below to run initializeCoreEdgeReactionModel before initializeReactionSystem; 11/3-4/07 gmagoon: probably reverted on or before 10/10/07
initializeReactionSystems();
}
catch (IOException e) {
Logger.logStackTrace(e);
Logger.critical(e.getMessage());
System.exit(0);
}
catch (InvalidSymbolException e) {
Logger.logStackTrace(e);
Logger.critical(e.getMessage());
System.exit(0);
}
//10/31/07 gmagoon: initialize validList (to false) before initializeCoreEdgeReactionModel is called
validList = new LinkedList();
for (Integer i = 0; i<reactionSystemList.size();i++) {
validList.add(false);
}
initializeCoreEdgeReactionModel();//10/4/07 gmagoon: moved before initializeReactionSystem; 11/3-4/07 gmagoon: probably reverted on or before 10/10/07
//10/24/07 gmagoon: changed to use reactionSystemList
// LinkedList initList = new LinkedList();//10/25/07 gmagoon: moved these variables to apply to entire class
// LinkedList beginList = new LinkedList();
// LinkedList endList = new LinkedList();
// LinkedList lastTList = new LinkedList();
// LinkedList currentTList = new LinkedList();
// LinkedList lastPList = new LinkedList();
// LinkedList currentPList = new LinkedList();
// LinkedList conditionChangedList = new LinkedList();
// LinkedList reactionChangedList = new LinkedList();
//5/6/08 gmagoon: determine whether there are intermediate time/conversion steps, type of termination tester is based on characteristics of 1st reaction system (it is assumed that they are all identical in terms of type of termination tester)
boolean intermediateSteps = true;
ReactionSystem rs0 = (ReactionSystem)reactionSystemList.get(0);
if (rs0.finishController.terminationTester instanceof ReactionTimeTT){
if (timeStep == null){
intermediateSteps = false;
}
}
else if (numConversions==1){ //if we get to this block, we presumably have a conversion terminationTester; this required moving numConversions to be attribute...alternative to using numConversions is to access one of the DynamicSimulators and determine conversion length
intermediateSteps=false;
}
//10/24/07 gmagoon: note: each element of for loop could be done in parallel if desired; some modifications would be needed
for (Iterator iter = reactionSystemList.iterator(); iter.hasNext(); ) {
ReactionSystem rs = (ReactionSystem)iter.next();
if ((reactionModelEnlarger instanceof RateBasedPDepRME)) {//1/2/09 gmagoon and rwest: only call initializePDepNetwork for P-dep cases
if (!readrestart) rs.initializePDepNetwork();
}
ReactionTime init = rs.getInitialReactionTime();
initList.add(init);
ReactionTime begin = init;
beginList.add(begin);
ReactionTime end;
if (rs.finishController.terminationTester instanceof ReactionTimeTT){
//5/5/08 gmagoon: added below if statement to avoid null pointer exception in cases where there are no intermediate time steps specified
if (!(timeStep==null)){
end = (ReactionTime)timeStep.get(0);
}
else{
end= ((ReactionTimeTT)rs.finishController.terminationTester).finalTime;
}
//end = (ReactionTime)timeStep.get(0);
endList.add(end);
}
else{
end = new ReactionTime(1e6,"sec");
endList.add(end);
}
// int iterationNumber = 1;
lastTList.add(rs.getTemperature(init));
currentTList.add(rs.getTemperature(init));
lastPList.add(rs.getPressure(init));
currentPList.add(rs.getPressure(init));
conditionChangedList.add(false);
reactionChangedList.add(false);//10/31/07 gmagoon: added
//Chemkin.writeChemkinInputFile(reactionSystem.getReactionModel(),reactionSystem.getPresentStatus());
}
int iterationNumber = 1;
LinkedList terminatedList = new LinkedList();//10/24/07 gmagoon: this may not be necessary, as if one reactionSystem is terminated, I think all should be terminated
//validList = new LinkedList();//10/31/07 gmagoon: moved before initializeCoreEdgeReactionModel
//10/24/07 gmagoon: initialize allTerminated and allValid to true; these variables keep track of whether all the reactionSystem variables satisfy termination and validity, respectively
boolean allTerminated = true;
boolean allValid = true;
// IF RESTART IS TURNED ON
// Update the systemSnapshot for each ReactionSystem in the reactionSystemList
if (readrestart) {
for (Integer i=0; i<reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
InitialStatus is = rs.getInitialStatus();
putRestartSpeciesInInitialStatus(is,i);
rs.appendUnreactedSpeciesStatus((InitialStatus)initialStatusList.get(i), rs.getPresentTemperature());
}
}
printModelSize();
// Write Chemkin input file only for the LAST reaction system (preserving old behaviour from when it used to be overwritten N times).
Chemkin.writeChemkinInputFile((ReactionSystem)reactionSystemList.getLast());
Logger.info(String.format("Running time: %.3f min", + (System.currentTimeMillis()-Global.tAtInitialization)/1000./60.));
printMemoryUsed();
Logger.flush();
//10/24/07 gmagoon: note: each element of for loop could be done in parallel if desired; some modifications would be needed
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
ReactionTime begin = (ReactionTime)beginList.get(i);
ReactionTime end = (ReactionTime)endList.get(i);
endList.set(i,rs.solveReactionSystem(begin, end, true, true, true, iterationNumber-1));
boolean terminated = rs.isReactionTerminated();
terminatedList.add(terminated);
if(!terminated)
allTerminated = false;
boolean valid = rs.isModelValid();
//validList.add(valid);
validList.set(i, valid);//10/31/07 gmagoon: validList initialization moved before initializeCoreEdgeReactionModel
if(!valid)
allValid = false;
reactionChangedList.set(i,false);
}
//9/1/09 gmagoon: if we are using QM, output a file with the CHEMKIN name, the RMG name, the (modified) InChI, and the (modified) InChIKey
if (ChemGraph.useQM){
writeInChIs(getReactionModel());
}
writeDictionary(getReactionModel());
//System.exit(0);
StringBuilder print_info = Global.diagnosticInfo;
print_info.append("\nMolecule \t Flux\t\tTime\t \t\t \t Core \t \t Edge \t \t memory\n");
print_info.append(" \t moleular \t characteristic \t findspecies \t moveUnreactedToReacted \t enlarger \t restart1 \t totalEnlarger \t resetSystem \t readSolverFile\t writeSolverFile \t justSolver \t SolverIterations \t solverSpeciesStatus \t Totalsolver \t gc \t restart+diagnosis \t chemkin thermo \t chemkin reactions \t validitytester \t Species \t Reactions\t Species\t Reactions \t memory used \t allSpecies \t TotalTime \t findRateConstant\t identifyReactedSites \t reactChemGraph \t makespecies\t CheckReverseReaction \t makeTemplateReaction \t getReactionfromStruc \t genReverseFromReac");
print_info.append("\t\t\t\t\t\t\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size()+ "\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedReactionSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSetIncludingReverseSize() + "\t"+Global.makeSpecies+"\n");
double solverMin = 0;
double vTester = 0;
/*if (!restart){
writeRestartFile();
writeCoreReactions();
writeAllReactions();
}*/
//System.exit(0);
SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
Logger.debug("Species dictionary size: "+dictionary.size());
//boolean reactionChanged = false;//10/24/07 gmagoon: I don't know if this is even required, but I will change to use reactionChangedList (I put analogous line of code for list in above for loop); update: yes, it is required; I had been thinking of conditionChangedList
//10/24/07: changed to use allTerminated and allValid
// step 2: iteratively grow reaction system
while (!allTerminated || !allValid) {
while (!allValid) {
//writeCoreSpecies();
double pt = System.currentTimeMillis();
// Grab all species from primary kinetics / reaction libraries
// WE CANNOT PRUNE THESE SPECIES
HashMap unprunableSpecies = new HashMap();
if (getPrimaryKineticLibrary() != null) {
unprunableSpecies.putAll(getPrimaryKineticLibrary().speciesSet);
}
if (getReactionLibrary() != null) {
unprunableSpecies.putAll(getReactionLibrary().getDictionary());
}
//prune the reaction model (this will only do something in the AUTO case)
pruneReactionModel(unprunableSpecies);
garbageCollect();
//System.out.println("After pruning:");
//printModelSize();
// ENLARGE THE MODEL!!! (this is where the good stuff happens)
enlargeReactionModel();
double totalEnlarger = (System.currentTimeMillis() - pt)/1000/60;
//PDepNetwork.completeNetwork(reactionSystem.reactionModel.getSpeciesSet());
//10/24/07 gmagoon: changed to use reactionSystemList
if ((reactionModelEnlarger instanceof RateBasedPDepRME)) {//1/2/09 gmagoon and rwest: only call initializePDepNetwork for P-dep cases
for (Iterator iter = reactionSystemList.iterator(); iter.hasNext(); ) {
ReactionSystem rs = (ReactionSystem)iter.next();
rs.initializePDepNetwork();
}
//reactionSystem.initializePDepNetwork();
}
printModelSize();
// Write Chemkin input file only for the LAST reaction system (preserving old behaviour from when it used to be overwritten N times).
Chemkin.writeChemkinInputFile((ReactionSystem)reactionSystemList.getLast());
Logger.info(String.format("Running time: %.3f min", + (System.currentTimeMillis()-Global.tAtInitialization)/1000./60.));
printMemoryUsed();
Logger.flush();
pt = System.currentTimeMillis();
//10/24/07 gmagoon: changed to use reactionSystemList
for (Iterator iter = reactionSystemList.iterator(); iter.hasNext(); ) {
ReactionSystem rs = (ReactionSystem)iter.next();
rs.resetSystemSnapshot();
}
//reactionSystem.resetSystemSnapshot();
double resetSystem = (System.currentTimeMillis() - pt)/1000/60;
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
//reactionChanged = true;
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
reactionChangedList.set(i,true);
// begin = init;
beginList.set(i, (ReactionTime)initList.get(i));
if (rs.finishController.terminationTester instanceof ReactionTimeTT){
//5/5/08 gmagoon: added below if statement to avoid null pointer exception in cases where there are no intermediate time steps specified
if (!(timeStep==null)){
endList.set(i,(ReactionTime)timeStep.get(0));
}
else{
endList.set(i, ((ReactionTimeTT)rs.finishController.terminationTester).finalTime);
}
// endList.set(i, (ReactionTime)timeStep.get(0));
//end = (ReactionTime)timeStep.get(0);
}
else
endList.set(i, new ReactionTime(1e6,"sec"));
//end = new ReactionTime(1e6,"sec");
// iterationNumber = 1;//10/24/07 gmagoon: moved outside of loop
currentTList.set(i,rs.getTemperature((ReactionTime)beginList.get(i)));
currentPList.set(i,rs.getPressure((ReactionTime)beginList.get(i)));
conditionChangedList.set(i,!(((Temperature)currentTList.get(i)).equals((Temperature)lastTList.get(i))) || !(((Pressure)currentPList.get(i)).equals((Pressure)lastPList.get(i))));
//currentT = reactionSystem.getTemperature(begin);
//currentP = reactionSystem.getPressure(begin);
//conditionChanged = (!currentT.equals(lastT) || !currentP.equals(lastP));
}
iterationNumber = 1;
double startTime = System.currentTimeMillis();
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean reactionChanged = (Boolean)reactionChangedList.get(i);
boolean conditionChanged = (Boolean)conditionChangedList.get(i);
ReactionTime begin = (ReactionTime)beginList.get(i);
ReactionTime end = (ReactionTime)endList.get(i);
endList.set(i,rs.solveReactionSystem(begin, end, false, reactionChanged, conditionChanged, iterationNumber-1));
//end = reactionSystem.solveReactionSystem(begin, end, false, reactionChanged, conditionChanged, iterationNumber-1);
}
solverMin = solverMin + (System.currentTimeMillis()-startTime)/1000/60;
startTime = System.currentTimeMillis();
//9/1/09 gmagoon: if we are using QM, output a file with the CHEMKIN name, the RMG name, the (modified) InChI, and the (modified) InChIKey
if (ChemGraph.useQM){
writeInChIs(getReactionModel());
}
writeDictionary(getReactionModel());
double chemkint = (System.currentTimeMillis()-startTime)/1000/60;
if (writerestart) {
/*
* Rename current restart files:
* In the event RMG fails while writing the restart files,
* user won't lose any information
*/
String[] restartFiles = {"Restart/coreReactions.txt", "Restart/coreSpecies.txt",
"Restart/edgeReactions.txt", "Restart/edgeSpecies.txt",
"Restart/pdepnetworks.txt", "Restart/pdepreactions.txt"};
writeBackupRestartFiles(restartFiles);
writeCoreSpecies();
writeCoreReactions();
writeEdgeSpecies();
writeEdgeReactions();
if (PDepNetwork.generateNetworks == true) writePDepNetworks();
/*
* Remove backup restart files from Restart folder
*/
removeBackupRestartFiles(restartFiles);
}
//10/24/07 gmagoon: changed to use reactionSystemList
Logger.info("");
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
Logger.info(String.format("For reaction system: %d out of %d", i+1, reactionSystemList.size()));
Logger.info(String.format("At this time: %10.4e s", ((ReactionTime)endList.get(i)).getTime()));
Species spe = SpeciesDictionary.getSpeciesFromID(getLimitingReactantID());
double conv = rs.getPresentConversion(spe);
Logger.info(String.format("Conversion of %s is: %-10.4g", spe.getFullName(), conv));
}
Logger.info("");
startTime = System.currentTimeMillis();
double mU = Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory();
Logger.info("");
double gc = (System.currentTimeMillis()-startTime)/1000./60.;
startTime = System.currentTimeMillis();
//10/24/07 gmagoon: updating to use reactionSystemList
allValid = true;
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean valid = rs.isModelValid();
if(!valid)
allValid = false;
validList.set(i,valid);
//valid = reactionSystem.isModelValid();
}
vTester = vTester + (System.currentTimeMillis()-startTime)/1000/60;
startTime = System.currentTimeMillis();
writeDiagnosticInfo();
writeEnlargerInfo();
double restart2 = (System.currentTimeMillis()-startTime)/1000/60;
int allSpecies, allReactions;
allSpecies = SpeciesDictionary.getInstance().size();
print_info.append(totalEnlarger + "\t" + resetSystem + "\t" + Global.readSolverFile + "\t" + Global.writeSolverFile + "\t" + Global.solvertime + "\t" + Global.solverIterations + "\t" + Global.speciesStatusGenerator + "\t" + solverMin + "\t" + gc + "\t" + restart2 + "\t" + Global.chemkinThermo + '\t' + Global.chemkinReaction + "\t" + vTester + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedSpeciesSet().size()+ "\t" + ((CoreEdgeReactionModel)getReactionModel()).getReactedReactionSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().size() + "\t" + ((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSetIncludingReverseSize() + "\t" + mU + "\t" + allSpecies + "\t" + (System.currentTimeMillis()-Global.tAtInitialization)/1000/60 + "\t"+ String.valueOf(Global.RT_findRateConstant)+"\t"+Global.RT_identifyReactedSites+"\t"+Global.RT_reactChemGraph+"\t"+Global.makeSpecies+"\t"+Global.checkReactionReverse+"\t"+Global.makeTR+ "\t" + Global.getReacFromStruc + "\t" + Global.generateReverse+"\n");
}
//5/6/08 gmagoon: in order to handle cases where no intermediate time/conversion steps are used, only evaluate the next block of code when there are intermediate time/conversion steps
double startTime = System.currentTimeMillis();
if(intermediateSteps){
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
reactionChangedList.set(i, false);
//reactionChanged = false;
Temperature currentT = (Temperature)currentTList.get(i);
Pressure currentP = (Pressure)currentPList.get(i);
lastTList.set(i,(Temperature)currentT.clone()) ;
lastPList.set(i,(Pressure)currentP.clone());
//lastT = (Temperature)currentT.clone();
//lastP = (Pressure)currentP.clone();
currentTList.set(i,rs.getTemperature((ReactionTime)beginList.get(i)));//10/24/07 gmagoon: ****I think this should actually be at end? (it shouldn't matter for isothermal/isobaric case)
currentPList.set(i,rs.getPressure((ReactionTime)beginList.get(i)));
conditionChangedList.set(i,!(((Temperature)currentTList.get(i)).equals((Temperature)lastTList.get(i))) || !(((Pressure)currentPList.get(i)).equals((Pressure)lastPList.get(i))));
//currentT = reactionSystem.getTemperature(begin);//10/24/07 gmagoon: ****I think this should actually be at end? (it shouldn't matter for isothermal/isobaric case)
//currentP = reactionSystem.getPressure(begin);
//conditionChanged = (!currentT.equals(lastT) || !currentP.equals(lastP));
beginList.set(i,((SystemSnapshot)(rs.getSystemSnapshotEnd().next())).time);
// begin=((SystemSnapshot)(reactionSystem.getSystemSnapshotEnd().next())).time;
if (rs.finishController.terminationTester instanceof ReactionTimeTT){
if (iterationNumber < timeStep.size()){
endList.set(i,(ReactionTime)timeStep.get(iterationNumber));
//end = (ReactionTime)timeStep.get(iterationNumber);
}
else
endList.set(i, ((ReactionTimeTT)rs.finishController.terminationTester).finalTime);
//end = ((ReactionTimeTT)reactionSystem.finishController.terminationTester).finalTime;
}
else
endList.set(i,new ReactionTime(1e6,"sec"));
//end = new ReactionTime(1e6,"sec");
}
iterationNumber++;
startTime = System.currentTimeMillis();//5/6/08 gmagoon: moved declaration outside of if statement so it can be accessed in subsequent vTester line; previous steps are probably so fast that I could eliminate this line without much effect on normal operation with intermediate steps
//double startTime = System.currentTimeMillis();
//10/24/07 gmagoon: changed to use reactionSystemList
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean reactionChanged = (Boolean)reactionChangedList.get(i);
boolean conditionChanged = (Boolean)conditionChangedList.get(i);
ReactionTime begin = (ReactionTime)beginList.get(i);
ReactionTime end = (ReactionTime)endList.get(i);
endList.set(i,rs.solveReactionSystem(begin, end, false, reactionChanged, false, iterationNumber-1));
// end = reactionSystem.solveReactionSystem(begin, end, false, reactionChanged, false, iterationNumber-1);
}
solverMin = solverMin + (System.currentTimeMillis()-startTime)/1000/60;
startTime = System.currentTimeMillis();
//5/6/08 gmagoon: changed to separate validity and termination testing, and termination testing is done last...termination testing should be done even if there are no intermediate conversions; however, validity is guaranteed if there are no intermediate conversions based on previous conditional if statement
allValid = true;
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean valid = rs.isModelValid();
validList.set(i,valid);
if(!valid)
allValid = false;
}
}//5/6/08 gmagoon: end of block for intermediateSteps
allTerminated = true;
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
boolean terminated = rs.isReactionTerminated();
terminatedList.set(i,terminated);
if(!terminated){
allTerminated = false;
Logger.error("Reaction System "+(i+1)+" has not reached its termination criterion");
if (rs.isModelValid()&& runKillableToPreventInfiniteLoop(intermediateSteps, iterationNumber)) {
Logger.info("although it seems to be valid (complete), so it was not interrupted for being invalid.");
Logger.info("This probably means there was an error with the ODE solver, and we risk entering an endless loop.");
Logger.info("Stopping.");
throw new Error();
}
}
}
//10/24/07 gmagoon: changed to use reactionSystemList, allValid
if (allValid) {
Logger.info("Model generation completed!");
printModelSize();
}
vTester = vTester + (System.currentTimeMillis()-startTime)/1000/60;//5/6/08 gmagoon: for case where intermediateSteps = false, this will use startTime declared just before intermediateSteps loop, and will only include termination testing, but no validity testing
}
//System.out.println("Performing model reduction");
if (paraInfor != 0){
Logger.info("Model Generation performed. Now generating sensitivity data.");
//10/24/07 gmagoon: updated to use reactionSystemList
LinkedList dynamicSimulator2List = new LinkedList();
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
//6/25/08 gmagoon: updated to pass index i
//6/25/08 gmagoon: updated to pass (dummy) finishController and autoflag (set to false here);
dynamicSimulator2List.add(new JDASPK(rtol, atol, paraInfor, (InitialStatus)initialStatusList.get(i),i));
//DynamicSimulator dynamicSimulator2 = new JDASPK(rtol, atol, paraInfor, initialStatus);
((DynamicSimulator)dynamicSimulator2List.get(i)).addConversion(((JDASPK)rs.dynamicSimulator).conversionSet, ((JDASPK)rs.dynamicSimulator).conversionSet.length);
//dynamicSimulator2.addConversion(((JDASPK)reactionSystem.dynamicSimulator).conversionSet, ((JDASPK)reactionSystem.dynamicSimulator).conversionSet.length);
rs.setDynamicSimulator((DynamicSimulator)dynamicSimulator2List.get(i));
//reactionSystem.setDynamicSimulator(dynamicSimulator2);
int numSteps = rs.systemSnapshot.size() -1;
rs.resetSystemSnapshot();
beginList.set(i, (ReactionTime)initList.get(i));
//begin = init;
if (rs.finishController.terminationTester instanceof ReactionTimeTT){
endList.set(i,((ReactionTimeTT)rs.finishController.terminationTester).finalTime);
//end = ((ReactionTimeTT)reactionSystem.finishController.terminationTester).finalTime;
}
else{
ReactionTime end = (ReactionTime)endList.get(i);
endList.set(i, end.add(end));
//end = end.add(end);
}
terminatedList.set(i, false);
//terminated = false;
ReactionTime begin = (ReactionTime)beginList.get(i);
ReactionTime end = (ReactionTime)endList.get(i);
rs.solveReactionSystemwithSEN(begin, end, true, false, false);
//reactionSystem.solveReactionSystemwithSEN(begin, end, true, false, false);
}
}
// All of the reaction systems are the same, so just write the chemkin
// file for the first reaction system
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(0);
Chemkin.writeChemkinInputFile(getReactionModel(),rs.getPresentStatus());
//9/1/09 gmagoon: if we are using QM, output a file with the CHEMKIN name, the RMG name, the (modified) InChI, and the (modified) InChIKey
if (ChemGraph.useQM){
writeInChIs(getReactionModel());
}
writeDictionary(getReactionModel());
}
//9/1/09 gmagoon: this function writes a "dictionary" with Chemkin name, RMG name, (modified) InChI, and InChIKey
//this is based off of writeChemkinFile in ChemkinInputFile.java
private void writeInChIs(ReactionModel p_reactionModel) {
StringBuilder result=new StringBuilder();
for (Iterator iter = ((CoreEdgeReactionModel)p_reactionModel).core.getSpecies(); iter.hasNext(); ) {
Species species = (Species) iter.next();
result.append(species.getChemkinName() + "\t"+species.getName() + "\t" + species.getChemGraph().getModifiedInChIAnew() + "\t" + species.getChemGraph().getModifiedInChIKeyAnew()+ "\n");
}
String file = "inchiDictionary.txt";
try {
FileWriter fw = new FileWriter(file);
fw.write(result.toString());
fw.close();
}
catch (Exception e) {
Logger.logStackTrace(e);
Logger.critical("Error in writing InChI file inchiDictionary.txt!");
Logger.critical(e.getMessage());
System.exit(0);
}
}
//9/14/09 gmagoon: function to write dictionary, based on code copied from RMG.java
private void writeDictionary(ReactionModel rm){
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)rm;
//Write core species to RMG_Dictionary.txt
String coreSpecies ="";
Iterator iter = cerm.getSpecies();
if (Species.useInChI) {
while (iter.hasNext()){
int i=1;
Species spe = (Species) iter.next();
coreSpecies = coreSpecies + spe.getChemkinName() + " " + spe.getInChI() + "\n"+spe.getChemGraph().toString(i)+"\n\n";
}
} else {
while (iter.hasNext()){
int i=1;
Species spe = (Species) iter.next();
coreSpecies = coreSpecies + spe.getChemkinName() + "\n"+spe.getChemGraph().toString(i)+"\n\n";
}
}
try{
File rmgDictionary = new File("RMG_Dictionary.txt");
FileWriter fw = new FileWriter(rmgDictionary);
fw.write(coreSpecies);
fw.close();
}
catch (IOException e) {
Logger.critical("Could not write RMG_Dictionary.txt");
System.exit(0);
}
// If we have solvation on, then every time we write the dictionary, also write the solvation properties
if (Species.useSolvation) {
writeSolvationProperties(rm);
}
}
private void writeSolvationProperties(ReactionModel rm){
//Write core species to RMG_Solvation_Properties.txt
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)rm;
StringBuilder result = new StringBuilder();
result.append("ChemkinName\tChemicalFormula\tMolecularWeight\tRadius\tDiffusivity\tAbrahamS\tAbrahamB\tAbrahamE\tAbrahamL\tAbrahamA\tAbrahamV\tChemkinName\n\n");
Iterator iter = cerm.getSpecies();
while (iter.hasNext()){
Species spe = (Species)iter.next();
result.append(spe.getChemkinName() + "\t");
result.append(spe.getChemGraph().getChemicalFormula()+ "\t");
result.append(spe.getMolecularWeight() + "\t");
result.append(spe.getChemGraph().getRadius()+ "\t");
result.append(spe.getChemGraph().getDiffusivity()+ "\t");
result.append(spe.getChemGraph().getAbramData().toString()+ "\t");
result.append(spe.getChemkinName() + "\n");
}
try{
File rmgSolvationProperties = new File("RMG_Solvation_Properties.txt");
FileWriter fw = new FileWriter(rmgSolvationProperties);
fw.write(result.toString() );
fw.close();
}
catch (IOException e) {
Logger.critical("Could not write RMG_Solvation_Properties.txt");
System.exit(0);
}
}
/*
* MRH 23MAR2010:
* Commenting out deprecated parseRestartFiles method
*/
// private void parseRestartFiles() {
// parseAllSpecies();
// parseCoreSpecies();
// parseEdgeSpecies();
// parseAllReactions();
// parseCoreReactions();
//
// }
/*
* MRH 23MAR2010:
* Commenting out deprecated parseEdgeReactions method
*/
// private void parseEdgeReactions() {
// SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
// //HasMap speciesMap = dictionary.dictionary;
// try{
// File coreReactions = new File("Restart/edgeReactions.txt");
// FileReader fr = new FileReader(coreReactions);
// BufferedReader reader = new BufferedReader(fr);
// String line = ChemParser.readMeaningfulLine(reader);
// boolean found = false;
// LinkedHashSet reactionSet = new LinkedHashSet();
// while (line != null){
// Reaction reaction = ChemParser.parseEdgeArrheniusReaction(dictionary,line,1,1);
// boolean added = reactionSet.add(reaction);
// if (!added){
// if (reaction.hasResonanceIsomerAsReactant()){
// //Structure reactionStructure = reaction.getStructure();
// found = getResonanceStructure(reaction,"reactants", reactionSet);
// }
// if (reaction.hasResonanceIsomerAsProduct() && !found){
// //Structure reactionStructure = reaction.getStructure();
// found = getResonanceStructure(reaction,"products", reactionSet);
// }
//
// if (!found){
// System.out.println("Cannot add reaction "+line+" to the Reaction Edge. All resonance isomers have already been added");
// System.exit(0);
// }
// else found = false;
// }
// //Reaction reverse = reaction.getReverseReaction();
// //if (reverse != null) reactionSet.add(reverse);
// line = ChemParser.readMeaningfulLine(reader);
// }
// ((CoreEdgeReactionModel)getReactionModel()).addReactionSet(reactionSet);
// }
// catch (IOException e){
// System.out.println("Could not read the corespecies restart file");
// System.exit(0);
// }
//
// }
/*
* MRH 23MAR2010:
* Commenting out deprecated parseAllSpecies method
*/
// public void parseCoreReactions() {
// SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
// int i=1;
// //HasMap speciesMap = dictionary.dictionary;
// try{
// File coreReactions = new File("Restart/coreReactions.txt");
// FileReader fr = new FileReader(coreReactions);
// BufferedReader reader = new BufferedReader(fr);
// String line = ChemParser.readMeaningfulLine(reader);
// boolean found = false;
// LinkedHashSet reactionSet = new LinkedHashSet();
// while (line != null){
// Reaction reaction = ChemParser.parseCoreArrheniusReaction(dictionary,line,1,1);//,((CoreEdgeReactionModel)reactionSystem.reactionModel));
// boolean added = reactionSet.add(reaction);
// if (!added){
// if (reaction.hasResonanceIsomerAsReactant()){
// //Structure reactionStructure = reaction.getStructure();
// found = getResonanceStructure(reaction,"reactants", reactionSet);
// }
// if (reaction.hasResonanceIsomerAsProduct() && !found){
// //Structure reactionStructure = reaction.getStructure();
// found = getResonanceStructure(reaction,"products", reactionSet);
// }
//
// if (!found){
// System.out.println("Cannot add reaction "+line+" to the Reaction Core. All resonance isomers have already been added");
// //System.exit(0);
// }
// else found = false;
// }
//
// Reaction reverse = reaction.getReverseReaction();
// if (reverse != null) {
// reactionSet.add(reverse);
// //System.out.println(2 + "\t " + line);
// }
//
// //else System.out.println(1 + "\t" + line);
// line = ChemParser.readMeaningfulLine(reader);
// i=i+1;
// }
// ((CoreEdgeReactionModel)getReactionModel()).addReactedReactionSet(reactionSet);
// }
// catch (IOException e){
// System.out.println("Could not read the coreReactions restart file");
// System.exit(0);
// }
//
// }
/*
* MRH 23MAR2010:
* Commenting out deprecated parseAllSpecies method
*/
// private void parseAllReactions() {
// SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
// int i=1;
// //HasMap speciesMap = dictionary.dictionary;
// try{
// File allReactions = new File("Restart/allReactions.txt");
// FileReader fr = new FileReader(allReactions);
// BufferedReader reader = new BufferedReader(fr);
// String line = ChemParser.readMeaningfulLine(reader);
// boolean found = false;
// LinkedHashSet reactionSet = new LinkedHashSet();
// OuterLoop:
// while (line != null){
// Reaction reaction = ChemParser.parseArrheniusReaction(dictionary,line,1,1,((CoreEdgeReactionModel)getReactionModel()));
//
// if (((CoreEdgeReactionModel)getReactionModel()).categorizeReaction(reaction)==-1){
// boolean added = reactionSet.add(reaction);
// if (!added){
// found = false;
// if (reaction.hasResonanceIsomerAsReactant()){
// //Structure reactionStructure = reaction.getStructure();
// found = getResonanceStructure(reaction,"reactants", reactionSet);
// }
// if (reaction.hasResonanceIsomerAsProduct() && !found){
// //Structure reactionStructure = reaction.getStructure();
// found = getResonanceStructure(reaction,"products", reactionSet);
// }
//
// if (!found){
// Iterator iter = reactionSet.iterator();
// while (iter.hasNext()){
// Reaction reacTemp = (Reaction)iter.next();
// if (reacTemp.equals(reaction)){
// reactionSet.remove(reacTemp);
// reactionSet.add(reaction);
// break;
// }
// }
//
// //System.out.println("Cannot add reaction "+line+" to the Reaction Core. All resonance isomers have already been added");
// //System.exit(0);
// }
//
// //else found = false;
// }
// }
//
//
// /*Reaction reverse = reaction.getReverseReaction();
// if (reverse != null && ((CoreEdgeReactionModel)reactionSystem.reactionModel).isReactedReaction(reaction)) {
// reactionSet.add(reverse);
// //System.out.println(2 + "\t " + line);
// }*/
// //else System.out.println(1 + "\t" + line);
//
// i=i+1;
//
// line = ChemParser.readMeaningfulLine(reader);
// }
// ((CoreEdgeReactionModel)getReactionModel()).addReactionSet(reactionSet);
// }
// catch (IOException e){
// System.out.println("Could not read the corespecies restart file");
// System.exit(0);
// }
//
// }
private boolean getResonanceStructure(Reaction p_Reaction, String rOrP, LinkedHashSet reactionSet) {
Structure reactionStructure = p_Reaction.getStructure();
//Structure tempreactionStructure = new Structure(reactionStructure.getReactantList(),reactionStructure.getProductList());
boolean found = false;
if (rOrP.equals("reactants")){
Iterator originalreactants = reactionStructure.getReactants();
HashSet tempHashSet = new HashSet();
while(originalreactants.hasNext()){
tempHashSet.add(originalreactants.next());
}
Iterator reactants = tempHashSet.iterator();
while(reactants.hasNext() && !found){
ChemGraph reactant = (ChemGraph)reactants.next();
if (reactant.getSpecies().hasResonanceIsomers()){
Iterator chemGraphIterator = reactant.getSpecies().getResonanceIsomers();
ChemGraph newChemGraph ;//= (ChemGraph)chemGraphIterator.next();
while(chemGraphIterator.hasNext() && !found){
newChemGraph = (ChemGraph)chemGraphIterator.next();
reactionStructure.removeReactants(reactant);
reactionStructure.addReactants(newChemGraph);
reactant = newChemGraph;
if (reactionSet.add(p_Reaction)){
found = true;
}
}
}
}
}
else{
Iterator originalproducts = reactionStructure.getProducts();
HashSet tempHashSet = new HashSet();
while(originalproducts.hasNext()){
tempHashSet.add(originalproducts.next());
}
Iterator products = tempHashSet.iterator();
while(products.hasNext() && !found){
ChemGraph product = (ChemGraph)products.next();
if (product.getSpecies().hasResonanceIsomers()){
Iterator chemGraphIterator = product.getSpecies().getResonanceIsomers();
ChemGraph newChemGraph ;//= (ChemGraph)chemGraphIterator.next();
while(chemGraphIterator.hasNext() && !found){
newChemGraph = (ChemGraph)chemGraphIterator.next();
reactionStructure.removeProducts(product);
reactionStructure.addProducts(newChemGraph);
product = newChemGraph;
if (reactionSet.add(p_Reaction)){
found = true;
}
}
}
}
}
return found;
}
public void parseCoreSpecies() {
// String restartFileContent ="";
//int speciesCount = 0;
//boolean added;
SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
try{
File coreSpecies = new File ("Restart/coreSpecies.txt");
FileReader fr = new FileReader(coreSpecies);
BufferedReader reader = new BufferedReader(fr);
String line = ChemParser.readMeaningfulLine(reader, true);
//HashSet speciesSet = new HashSet();
// if (reactionSystem == null){//10/24/07 gmagoon: commenting out since contents of if was already commented out anyway
// //ReactionSystem reactionSystem = new ReactionSystem();
// }
setReactionModel(new CoreEdgeReactionModel());//10/4/07 gmagoon:changed to setReactionModel
while (line!=null) {
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
int ID = Integer.parseInt(index);
Species spe = dictionary.getSpeciesFromID(ID);
if (spe == null)
Logger.warning("There was no species with ID "+ID +" in the species dictionary");
((CoreEdgeReactionModel)getReactionModel()).addReactedSpecies(spe);
line = ChemParser.readMeaningfulLine(reader, true);
}
}
catch (IOException e){
Logger.critical("Could not read the corespecies restart file");
System.exit(0);
}
}
public static void garbageCollect(){
System.gc();
}
public static void printMemoryUsed(){
garbageCollect();
Runtime rT = Runtime.getRuntime();
double uM, tM, fM;
tM = rT.totalMemory() / 1.0e6;
fM = rT.freeMemory() / 1.0e6;
uM = tM - fM;
Logger.debug("After garbage collection:");
Logger.info(String.format("Memory used: %.2f MB / %.2f MB (%.2f%%)", uM, tM, uM / tM * 100.));
}
/*
* MRH 23MAR2010:
* Commenting out deprecated parseAllSpecies method
*/
// public LinkedHashSet parseAllSpecies() {
// // String restartFileContent ="";
// int speciesCount = 0;
// LinkedHashSet speciesSet = new LinkedHashSet();
//
// boolean added;
// try{
// long initialTime = System.currentTimeMillis();
//
// File coreSpecies = new File ("allSpecies.txt");
// BufferedReader reader = new BufferedReader(new FileReader(coreSpecies));
// String line = ChemParser.readMeaningfulLine(reader);
// int i=0;
// while (line!=null) {
// i++;
// StringTokenizer st = new StringTokenizer(line);
// String index = st.nextToken();
// String name = null;
// if (!index.startsWith("(")) name = index;
// else name = st.nextToken().trim();
// int ID = getID(name);
//
// name = getName(name);
// Graph g = ChemParser.readChemGraph(reader);
// ChemGraph cg = null;
// try {
// cg = ChemGraph.make(g);
// }
// catch (ForbiddenStructureException e) {
// System.out.println("Forbidden Structure:\n" + e.getMessage());
// System.exit(0);
// }
// Species species;
// if (ID == 0)
// species = Species.make(name,cg);
// else
// species = Species.make(name,cg,ID);
// speciesSet.add(species);
// double flux = 0;
// int species_type = 1;
// line = ChemParser.readMeaningfulLine(reader);
// System.out.println(line);
// }
// }
// catch (IOException e){
// System.out.println("Could not read the allSpecies restart file");
// System.exit(0);
// }
// return speciesSet;
// }
private String getName(String name) {
//int id;
String number = "";
int index=0;
if (!name.endsWith(")")) return name;
else {
char [] nameChars = name.toCharArray();
String temp = String.copyValueOf(nameChars);
int i=name.length()-2;
//char test = "(";
while (i>0){
if (name.charAt(i)== '(') {
index=i;
i=0;
}
else i = i-1;
}
}
number = name.substring(0,index);
return number;
}
private int getID(String name) {
int id;
String number = "";
if (!name.endsWith(")")) return 0;
else {
char [] nameChars = name.toCharArray();
int i=name.length()-2;
//char test = "(";
while (i>0){
if (name.charAt(i)== '(') i=0;
else{
number = name.charAt(i)+number;
i = i-1;
}
}
}
id = Integer.parseInt(number);
return id;
}
/*
* MRH 23MAR2010:
* Commenting out deprecated parseAllSpecies method
*/
// private void parseEdgeSpecies() {
// // String restartFileContent ="";
// SpeciesDictionary dictionary = SpeciesDictionary.getInstance();
// try{
// File edgeSpecies = new File ("Restart/edgeSpecies.txt");
// FileReader fr = new FileReader(edgeSpecies);
// BufferedReader reader = new BufferedReader(fr);
// String line = ChemParser.readMeaningfulLine(reader);
// //HashSet speciesSet = new HashSet();
//
// while (line!=null) {
//
// StringTokenizer st = new StringTokenizer(line);
// String index = st.nextToken();
// int ID = Integer.parseInt(index);
// Species spe = dictionary.getSpeciesFromID(ID);
// if (spe == null)
// System.out.println("There was no species with ID "+ID +" in the species dictionary");
// //reactionSystem.reactionModel = new CoreEdgeReactionModel();
// ((CoreEdgeReactionModel)getReactionModel()).addUnreactedSpecies(spe);
// line = ChemParser.readMeaningfulLine(reader);
// }
//
// }
// catch (IOException e){
// System.out.println("Could not read the edgepecies restart file");
// System.exit(0);
// }
//
// }
/*private int calculateAllReactionsinReactionTemplate() {
int totalnum = 0;
TemplateReactionGenerator trg = (TemplateReactionGenerator)reactionSystem.reactionGenerator;
Iterator iter = trg.getReactionTemplateLibrary().getReactionTemplate();
while (iter.hasNext()){
ReactionTemplate rt = (ReactionTemplate)iter.next();
totalnum += rt.getNumberOfReactions();
}
return totalnum;
}*/
private void writeEnlargerInfo() {
try {
File diagnosis = new File("enlarger.xls");
FileWriter fw = new FileWriter(diagnosis);
fw.write(Global.enlargerInfo.toString());
fw.close();
}
catch (IOException e) {
Logger.critical("Cannot write enlarger file");
System.exit(0);
}
}
private void writeDiagnosticInfo() {
try {
File diagnosis = new File("diagnosis.xls");
FileWriter fw = new FileWriter(diagnosis);
fw.write(Global.diagnosticInfo.toString());
fw.close();
}
catch (IOException e) {
Logger.critical("Cannot write diagnosis file");
System.exit(0);
}
}
//10/25/07 gmagoon: I don't think this is used, but I will update to use reactionSystem and reactionTime as parameter to access temperature; commented-out usage of writeRestartFile will need to be modified
//Is still incomplete.
public void writeRestartFile(ReactionSystem p_rs, ReactionTime p_time ) {
//writeCoreSpecies(p_rs);
//writeCoreReactions(p_rs, p_time);
//writeEdgeSpecies();
//writeAllReactions(p_rs, p_time);
//writeEdgeReactions(p_rs, p_time);
//String restartFileName;
//String restartFileContent="";
/*File restartFile;
try {
restartFileName="Restart.txt";
restartFile = new File(restartFileName);
FileWriter fw = new FileWriter(restartFile);
restartFileContent = restartFileContent+ "TemperatureModel: Constant " + reactionSystem.temperatureModel.getTemperature(reactionSystem.getInitialReactionTime()).getStandard()+ " (K)\n";
restartFileContent = restartFileContent+ "PressureModel: Constant " + reactionSystem.pressureModel.getPressure(reactionSystem.getInitialReactionTime()).getAtm() + " (atm)\n\n";
restartFileContent = restartFileContent+ "InitialStatus: \n";
int speciesCount = 1;
for(Iterator iter=reactionSystem.reactionModel.getSpecies();iter.hasNext();){
Species species = (Species) iter.next();
restartFileContent = restartFileContent + "("+ speciesCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n";
restartFileContent = restartFileContent + species.toStringWithoutH(1) + "\n";
speciesCount = speciesCount + 1;
}
restartFileContent = restartFileContent + "\n\n END \n\nInertGas:\n";
for (Iterator iter=reactionSystem.getPresentStatus().getInertGas(); iter.hasNext();){
String inertName= (String) iter.next();
restartFileContent = restartFileContent + inertName + " " + reactionSystem.getPresentStatus().getInertGas(inertName) + " mol/cm3 \n";
}
restartFileContent = restartFileContent + "END\n";
double tolerance;
if (reactionSystem.reactionModelEnlarger instanceof RateBasedPDepRME){
restartFileContent = restartFileContent + "ReactionModelEnlarger: RateBasedPDepModelEnlarger\n";
restartFileContent = restartFileContent + "FinishController: RateBasedPDepFinishController\n";
}
else {
restartFileContent = restartFileContent + "ReactionModelEnlarger: RateBasedModelEnlarger\n";
restartFileContent = restartFileContent + "FinishController: RateBasedFinishController\n";
}
if (reactionSystem.finishController.terminationTester instanceof ConversionTT){
restartFileContent = restartFileContent + "(1) Goal Conversion: ";
for (Iterator iter = ((ConversionTT)reactionSystem.finishController.terminationTester).getSpeciesGoalConversionSet();iter.hasNext();){
SpeciesConversion sc = (SpeciesConversion) iter.next();
restartFileContent = restartFileContent + sc.getSpecies().getName()+" "+sc.conversion + "\n";
}
}
else {
restartFileContent = restartFileContent + "(1) Goal ReactionTime: "+((ReactionTimeTT)reactionSystem.finishController.terminationTester).finalTime.toString();
}
restartFileContent = restartFileContent + "Error Tolerance: " +((RateBasedVT) reactionSystem.finishController.validityTester).tolerance + "\n";
fw.write(restartFileContent);
fw.close();
}
catch (IOException e) {
System.out.println("Could not write the restart file");
System.exit(0);
}*/
}
/*
* MRH 25MAR2010
* This method is no longer used
*/
/*Only write the forward reactions in the model core.
The reverse reactions are generated from the forward reactions.*/
//10/25/07 gmagoon: added reaction system and reaction time as parameters and eliminated use of Global.temperature
// private void writeEdgeReactions(ReactionSystem p_rs, ReactionTime p_time) {
// StringBuilder restartFileContent =new StringBuilder();
// int reactionCount = 1;
// try{
// File coreSpecies = new File ("Restart/edgeReactions.txt");
// FileWriter fw = new FileWriter(coreSpecies);
// for(Iterator iter=((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSet().iterator();iter.hasNext();){
//
// Reaction reaction = (Reaction) iter.next();
// //if (reaction.getDirection()==1){
// //restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n";
// restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n");
// reactionCount = reactionCount + 1;
// //}
// }
// //restartFileContent += "\nEND";
// fw.write(restartFileContent.toString());
// fw.close();
// }
// catch (IOException e){
// System.out.println("Could not write the restart edgereactions file");
// System.exit(0);
// }
//
// }
/*
* MRH 25MAR2010:
* This method is no longer used
*/
//10/25/07 gmagoon: added reaction system and reaction time as parameters and eliminated use of Global.temperature
// private void writeAllReactions(ReactionSystem p_rs, ReactionTime p_time) {
// StringBuilder restartFileContent = new StringBuilder();
// int reactionCount = 1;
// try{
// File allReactions = new File ("Restart/allReactions.txt");
// FileWriter fw = new FileWriter(allReactions);
// for(Iterator iter=getReactionModel().getReaction();iter.hasNext();){
//
// Reaction reaction = (Reaction) iter.next();
//
// //restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n";
// restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n");
//
// }
//
// for(Iterator iter=((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSet().iterator();iter.hasNext();){
//
// Reaction reaction = (Reaction) iter.next();
// //if (reaction.getDirection()==1){
// //restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n";
// restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n");
//
// }
// //restartFileContent += "\nEND";
// fw.write(restartFileContent.toString());
// fw.close();
// }
// catch (IOException e){
// System.out.println("Could not write the restart edgereactions file");
// System.exit(0);
// }
//
// }
private void writeEdgeSpecies() {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Restart/edgeSpecies.txt"));
for(Iterator iter=((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().iterator();iter.hasNext();){
Species species = (Species) iter.next();
bw.write(species.getFullName());
bw.newLine();
int dummyInt = 0;
bw.write(species.getChemGraph().toString(dummyInt));
bw.newLine();
}
} catch (FileNotFoundException ex) {
Logger.logStackTrace(ex);
} catch (IOException ex) {
Logger.logStackTrace(ex);
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
Logger.logStackTrace(ex);
}
}
}
private void writePrunedEdgeSpecies(Species species) {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Pruning/edgeSpecies.txt", true));
bw.write(species.getChemkinName());
bw.newLine();
int dummyInt = 0;
bw.write(species.getChemGraph().toString(dummyInt));
bw.newLine();
} catch (FileNotFoundException ex) {
Logger.logStackTrace(ex);
} catch (IOException ex) {
Logger.logStackTrace(ex);
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
Logger.logStackTrace(ex);
}
}
}
/*
* MRH 25MAR2010:
* This method is no longer used
*/
//10/25/07 gmagoon: added reaction system and reaction time as parameters and eliminated use of Global.temperature
// private void writeCoreReactions(ReactionSystem p_rs, ReactionTime p_time) {
// StringBuilder restartFileContent = new StringBuilder();
// int reactionCount = 0;
// try{
// File coreSpecies = new File ("Restart/coreReactions.txt");
// FileWriter fw = new FileWriter(coreSpecies);
// for(Iterator iter=getReactionModel().getReaction();iter.hasNext();){
//
// Reaction reaction = (Reaction) iter.next();
// if (reaction.getDirection()==1){
// //restartFileContent = restartFileContent + "("+ reactionCount + ") "+species.getChemkinName() + " " + reactionSystem.getPresentConcentration(species) + " (mol/cm3) \n";
// restartFileContent = restartFileContent.append(reaction.toRestartString(p_rs.getTemperature(p_time)) + "\n");
// reactionCount = reactionCount + 1;
// }
// }
// //restartFileContent += "\nEND";
// fw.write(restartFileContent.toString());
// fw.close();
// }
// catch (IOException e){
// System.out.println("Could not write the restart corereactions file");
// System.exit(0);
// }
// }
private void writeCoreSpecies() {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Restart/coreSpecies.txt"));
for(Iterator iter=getReactionModel().getSpecies();iter.hasNext();){
Species species = (Species) iter.next();
bw.write(species.getFullName());
bw.newLine();
int dummyInt = 0;
bw.write(species.getChemGraph().toString(dummyInt));
bw.newLine();
}
} catch (FileNotFoundException ex) {
Logger.logStackTrace(ex);
} catch (IOException ex) {
Logger.logStackTrace(ex);
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
Logger.logStackTrace(ex);
}
}
}
private void writeCoreReactions() {
BufferedWriter bw_rxns = null;
BufferedWriter bw_pdeprxns = null;
try {
bw_rxns = new BufferedWriter(new FileWriter("Restart/coreReactions.txt"));
bw_pdeprxns = new BufferedWriter(new FileWriter("Restart/pdepreactions.txt"));
String EaUnits = ArrheniusKinetics.getEaUnits();
String AUnits = ArrheniusKinetics.getAUnits();
bw_rxns.write("UnitsOfEa: " + EaUnits);
bw_rxns.newLine();
bw_pdeprxns.write("Unit:\nA: mol/cm3/s\nE: " + EaUnits + "\n\nReactions:");
bw_pdeprxns.newLine();
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)getReactionModel();
LinkedHashSet allcoreRxns = cerm.core.reaction;
for(Iterator iter=allcoreRxns.iterator(); iter.hasNext();){
Reaction reaction = (Reaction) iter.next();
if (reaction.isForward()) {
if (reaction instanceof TROEReaction) {
TROEReaction troeRxn = (TROEReaction) reaction;
bw_pdeprxns.write(troeRxn.toRestartString(new Temperature(298,"K")));
bw_pdeprxns.newLine();
}
else if (reaction instanceof LindemannReaction) {
LindemannReaction lindeRxn = (LindemannReaction) reaction;
bw_pdeprxns.write(lindeRxn.toRestartString(new Temperature(298,"K")));
bw_pdeprxns.newLine();
}
else if (reaction instanceof ThirdBodyReaction) {
ThirdBodyReaction tbRxn = (ThirdBodyReaction) reaction;
bw_pdeprxns.write(tbRxn.toRestartString(new Temperature(298,"K")));
bw_pdeprxns.newLine();
}
else {
//bw.write(reaction.toChemkinString(new Temperature(298,"K")));
bw_rxns.write(reaction.toRestartString(new Temperature(298,"K"),false));
bw_rxns.newLine();
}
}
}
} catch (FileNotFoundException ex) {
Logger.logStackTrace(ex);
} catch (IOException ex) {
Logger.logStackTrace(ex);
} finally {
try {
if (bw_rxns != null) {
bw_rxns.flush();
bw_rxns.close();
}
if (bw_pdeprxns != null) {
bw_pdeprxns.flush();
bw_pdeprxns.close();
}
} catch (IOException ex) {
Logger.logStackTrace(ex);
}
}
}
private void writeEdgeReactions() {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Restart/edgeReactions.txt"));
String EaUnits = ArrheniusKinetics.getEaUnits();
bw.write("UnitsOfEa: " + EaUnits);
bw.newLine();
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)getReactionModel();
LinkedHashSet alledgeRxns = cerm.edge.reaction;
for(Iterator iter=alledgeRxns.iterator(); iter.hasNext();){
Reaction reaction = (Reaction) iter.next();
if (reaction.isForward()) {
//bw.write(reaction.toChemkinString(new Temperature(298,"K")));
bw.write(reaction.toRestartString(new Temperature(298,"K"),false));
bw.newLine();
} else if (reaction.getReverseReaction().isForward()) {
//bw.write(reaction.getReverseReaction().toChemkinString(new Temperature(298,"K")));
bw.write(reaction.getReverseReaction().toRestartString(new Temperature(298,"K"),false));
bw.newLine();
} else
Logger.warning("Could not determine forward direction for following rxn: " + reaction.toString());
}
} catch (FileNotFoundException ex) {
Logger.logStackTrace(ex);
} catch (IOException ex) {
Logger.logStackTrace(ex);
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
Logger.logStackTrace(ex);
}
}
}
//gmagoon 4/5/10: based on Mike's writeEdgeReactions
private void writePrunedEdgeReaction(Reaction reaction) {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Pruning/edgeReactions.txt", true));
if (reaction.isForward()) {
bw.write(reaction.toChemkinString(new Temperature(298,"K")));
// bw.write(reaction.toRestartString(new Temperature(298,"K")));
bw.newLine();
} else if (reaction.getReverseReaction().isForward()) {
bw.write(reaction.getReverseReaction().toChemkinString(new Temperature(298,"K")));
//bw.write(reaction.getReverseReaction().toRestartString(new Temperature(298,"K")));
bw.newLine();
} else
Logger.warning("Could not determine forward direction for following rxn: " + reaction.toString());
} catch (FileNotFoundException ex) {
Logger.logStackTrace(ex);
} catch (IOException ex) {
Logger.logStackTrace(ex);
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
Logger.logStackTrace(ex);
}
}
}
private void writePDepNetworks() {
BufferedWriter bw = null;
try {
bw = new BufferedWriter(new FileWriter("Restart/pdepnetworks.txt"));
int numFameTemps = PDepRateConstant.getTemperatures().length;
int numFamePress = PDepRateConstant.getPressures().length;
int numChebyTemps = ChebyshevPolynomials.getNT();
int numChebyPress = ChebyshevPolynomials.getNP();
//int numPlog = PDepArrheniusKinetics.getNumPressures();
int numPlog = numFamePress; // probably often the case for FAME-generated PLOG rates (but not for seed or library reactions)
String EaUnits = ArrheniusKinetics.getEaUnits();
bw.write("UnitsOfEa: " + EaUnits);
bw.newLine();
bw.write("NumberOfFameTemps: " + numFameTemps);
bw.newLine();
bw.write("NumberOfFamePress: " + numFamePress);
bw.newLine();
bw.write("NumberOfChebyTemps: " + numChebyTemps);
bw.newLine();
bw.write("NumberOfChebyPress: " + numChebyPress);
bw.newLine();
bw.write("NumberOfPLogs: Could be different for seed and library reactions, but default for FAME-generated rates is probably "+ numPlog);
bw.newLine();
bw.newLine();
LinkedList allNets = PDepNetwork.getNetworks();
for(Iterator iter=allNets.iterator(); iter.hasNext();){
PDepNetwork pdepnet = (PDepNetwork) iter.next();
bw.write("PDepNetwork #" + pdepnet.getID());
bw.newLine();
// Write netReactionList
LinkedList netRxns = pdepnet.getNetReactions();
bw.write("netReactionList:");
bw.newLine();
for (Iterator iter2=netRxns.iterator(); iter2.hasNext();) {
PDepReaction currentPDepRxn = (PDepReaction)iter2.next();
bw.write(currentPDepRxn.toString());
bw.newLine();
bw.write(writeRatesAndParameters(currentPDepRxn,numFameTemps,
numFamePress,numChebyTemps,numChebyPress,numPlog));
}
// Write nonincludedReactionList
LinkedList nonIncludeRxns = pdepnet.getNonincludedReactions();
bw.write("nonIncludedReactionList:");
bw.newLine();
for (Iterator iter2=nonIncludeRxns.iterator(); iter2.hasNext();) {
PDepReaction currentPDepRxn = (PDepReaction)iter2.next();
bw.write(currentPDepRxn.toString());
bw.newLine();
bw.write(writeRatesAndParameters(currentPDepRxn,numFameTemps,
numFamePress,numChebyTemps,numChebyPress,numPlog));
PDepReaction currentPDepReverseRxn = currentPDepRxn.getReverseReaction();
// Not all nonIncludedReactions are reversible
// (MRH FEB-16-2011) ... and not all reverse reactions
// have pressure-dependent rate coefficients (apparently)
if (currentPDepReverseRxn != null && currentPDepReverseRxn.getPDepRate() != null) {
bw.write(currentPDepReverseRxn.toString());
bw.newLine();
bw.write(writeRatesAndParameters(currentPDepReverseRxn,numFameTemps,
numFamePress,numChebyTemps,numChebyPress,numPlog));
}
}
// Write pathReactionList
LinkedList pathRxns = pdepnet.getPathReactions();
bw.write("pathReactionList:");
bw.newLine();
for (Iterator iter2=pathRxns.iterator(); iter2.hasNext();) {
PDepReaction currentPDepRxn = (PDepReaction)iter2.next();
bw.write(currentPDepRxn.getDirection() + "\t" + currentPDepRxn.toRestartString(new Temperature(298,"K")));
bw.newLine();
}
bw.newLine();
bw.newLine();
}
} catch (FileNotFoundException ex) {
Logger.logStackTrace(ex);
} catch (IOException ex) {
Logger.logStackTrace(ex);
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
Logger.logStackTrace(ex);
}
}
}
public String writeRatesAndParameters(PDepReaction pdeprxn, int numFameTemps,
int numFamePress, int numChebyTemps, int numChebyPress, int numPlog) {
StringBuilder sb = new StringBuilder();
// Write the rate coefficients
double[][] rateConstants = pdeprxn.getPDepRate().getRateConstants();
for (int i=0; i<numFameTemps; i++) {
for (int j=0; j<numFamePress; j++) {
sb.append(rateConstants[i][j] + "\t");
}
sb.append("\n");
}
sb.append("\n");
// If chebyshev polynomials are present, write them
if (numChebyTemps != 0) {
ChebyshevPolynomials chebyPolys = pdeprxn.getPDepRate().getChebyshev();
for (int i=0; i<numChebyTemps; i++) {
for (int j=0; j<numChebyPress; j++) {
sb.append(chebyPolys.getAlpha(i,j) + "\t");
}
sb.append("\n");
}
sb.append("\n");
}
// If plog parameters are present, write them
PDepArrheniusKinetics[] kinetics = pdeprxn.getPDepRate().getPDepArrheniusKinetics();
if (kinetics != null) {
for (int i=0; i<kinetics.length; i++) {
sb.append(kinetics[i].toChemkinString());
sb.append("\n");
}
}
/*
else if (numPlog != 0) {
PDepArrheniusKinetics kinetics = pdeprxn.getPDepRate().getPDepArrheniusKinetics();
for (int i=0; i<numPlog; i++) {
double Hrxn = pdeprxn.calculateHrxn(new Temperature(298,"K"));
sb.append(kinetics.pressures[i].getPa() + "\t" + kinetics.getKinetics(i).toChemkinString(Hrxn,new Temperature(298,"K"),false) + "\n");
}
sb.append("\n");
}
*/
return sb.toString();
}
public LinkedList getTimeStep() {
return timeStep;
}
public static boolean getUseDiffusion() {
return useDiffusion;
}
public static boolean getUseSolvation() {
return useSolvation;
}
public void setUseDiffusion(Boolean p_boolean) {
useDiffusion = p_boolean;
}
public void setUseSolvation(Boolean p_boolean) {
useSolvation = p_boolean;
}
public void setTimeStep(ReactionTime p_timeStep) {
if (timeStep == null)
timeStep = new LinkedList();
timeStep.add(p_timeStep);
}
public String getWorkingDirectory() {
return workingDirectory;
}
public void setWorkingDirectory(String p_workingDirectory) {
workingDirectory = p_workingDirectory;
}
//svp
public boolean getError(){
return error;
}
//svp
public boolean getSensitivity(){
return sensitivity;
}
public LinkedList getSpeciesList() {
return species;
}
//gmagoon 10/24/07: commented out getReactionSystem and setReactionSystem
// public ReactionSystem getReactionSystem() {
// return reactionSystem;
// }
//11/2/07 gmagoon: adding accessor method for reactionSystemList
public LinkedList getReactionSystemList(){
return reactionSystemList;
}
//added by gmagoon 9/24/07
// public void setReactionSystem(ReactionSystem p_ReactionSystem) {
// reactionSystem = p_ReactionSystem;
// }
//copied from ReactionSystem.java by gmagoon 9/24/07
public ReactionModel getReactionModel() {
return reactionModel;
}
public void readRestartSpecies() {
Logger.info("Reading in species from Restart folder");
// Read in core species -- NOTE code is almost duplicated in Read in edge species (second part of procedure)
try {
FileReader in = new FileReader("Restart/coreSpecies.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader, true);
while (line != null) {
// The first line of a new species is the user-defined name
String totalSpeciesName = line;
String[] splitString1 = totalSpeciesName.split("[(]");
String[] splitString2 = splitString1[splitString1.length-1].split("[)]");
// The remaining lines are the graph
Graph g = ChemParser.readChemGraph(reader);
// Make the ChemGraph, assuming it does not contain a forbidden structure
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
} catch (ForbiddenStructureException e) {
Logger.critical("Error reading graph: Graph contains a forbidden structure.\n" + g.toString());
System.exit(0);
}
// Make the species
int intLocation = totalSpeciesName.indexOf("(" + splitString2[0] + ")");
Species species = Species.make(totalSpeciesName.substring(0,intLocation),cg,Integer.parseInt(splitString2[0]));
// Add the new species to the set of species
restartCoreSpcs.add(species);
/*int species_type = 1; // reacted species
for (int i=0; i<numRxnSystems; i++) {
SpeciesStatus ss = new SpeciesStatus(species,species_type,y[i],yprime[i]);
speciesStatus[i].put(species, ss);
}*/
line = ChemParser.readMeaningfulLine(reader, true);
}
} catch (FileNotFoundException e) {
Logger.logStackTrace(e);
} catch (IOException e) {
Logger.logStackTrace(e);
}
// Read in edge species
try {
FileReader in = new FileReader("Restart/edgeSpecies.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader, true);
while (line != null) {
// The first line of a new species is the user-defined name
String totalSpeciesName = line;
String[] splitString1 = totalSpeciesName.split("[(]");
String[] splitString2 = splitString1[splitString1.length-1].split("[)]"); // Change JDM to reflect MRH 2-11-2010
// The remaining lines are the graph
Graph g = ChemParser.readChemGraph(reader);
// Make the ChemGraph, assuming it does not contain a forbidden structure
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
} catch (ForbiddenStructureException e) {
Logger.critical("Error reading graph: Graph contains a forbidden structure.\n" + g.toString());
System.exit(0);
}
// Rewrite the species name ... with the exception of the (#)
String speciesName = splitString1[0];
for (int numTokens=1; numTokens<splitString1.length-1; ++numTokens) {
speciesName += "(" + splitString1[numTokens];
}
// Make the species
Species species = Species.make(speciesName,cg,Integer.parseInt(splitString2[0]));
// Add the new species to the set of species
restartEdgeSpcs.add(species);
line = ChemParser.readMeaningfulLine(reader, true);
}
} catch (FileNotFoundException e) {
Logger.logStackTrace(e);
} catch (IOException e) {
Logger.logStackTrace(e);
}
}
public void readRestartReactions() {
// Grab the IDs from the core species
int[] coreSpcsIds = new int[restartCoreSpcs.size()];
int i = 0;
for (Iterator iter = restartCoreSpcs.iterator(); iter.hasNext();) {
Species spcs = (Species)iter.next();
coreSpcsIds[i] = spcs.getID();
++i;
}
Logger.info("Reading reactions from Restart folder");
// Read in core reactions
try {
FileReader in = new FileReader("Restart/coreReactions.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader, true);
// Determine units of Ea
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken();
String EaUnits = st.nextToken();
line = ChemParser.readMeaningfulLine(reader, true);
while (line != null) {
if (!line.trim().equals("DUP")) {
Reaction r = ChemParser.parseRestartReaction(line,coreSpcsIds,"core",EaUnits);
Iterator rxnIter = restartCoreRxns.iterator();
boolean foundRxn = false;
while (rxnIter.hasNext()) {
Reaction old = (Reaction)rxnIter.next();
if (old.equals(r)) {
old.addAdditionalKinetics(r.getKinetics()[0],1,true);
foundRxn = true;
break;
}
}
if (!foundRxn) {
if (r.hasReverseReaction()) r.generateReverseReaction();
restartCoreRxns.add(r);
}
}
line = ChemParser.readMeaningfulLine(reader, true);
}
} catch (FileNotFoundException e) {
Logger.logStackTrace(e);
} catch (IOException e) {
Logger.logStackTrace(e);
}
/*
* Read in the pdepreactions.txt file:
* This file contains third-body, lindemann, and troe reactions
* A RMG mechanism would only have these reactions if a user specified
* them in a Seed Mechanism, meaning they are core species &
* reactions.
* Place these reactions in a new Seed Mechanism, using the
* coreSpecies.txt file as the species.txt file.
*/
SeedMechanism restart_seed_mechanism = null;
try {
String path = System.getProperty("user.dir") + "/Restart";
restart_seed_mechanism = new SeedMechanism("Restart", path, false, true);
} catch (IOException e1) {
Logger.logStackTrace(e1);
}
restartCoreRxns.addAll(restart_seed_mechanism.getReactionSet());
// Read in edge reactions
try {
FileReader in = new FileReader("Restart/edgeReactions.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader, true);
// Determine units of Ea
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken();
String EaUnits = st.nextToken();
line = ChemParser.readMeaningfulLine(reader, true);
while (line != null) {
if (!line.trim().equals("DUP")) {
Reaction r = ChemParser.parseRestartReaction(line,coreSpcsIds,"edge",EaUnits);
Iterator rxnIter = restartEdgeRxns.iterator();
boolean foundRxn = false;
while (rxnIter.hasNext()) {
Reaction old = (Reaction)rxnIter.next();
if (old.equals(r)) {
old.addAdditionalKinetics(r.getKinetics()[0],1,true);
foundRxn = true;
break;
}
}
if (!foundRxn) {
r.generateReverseReaction();
restartEdgeRxns.add(r);
}
}
line = ChemParser.readMeaningfulLine(reader, true);
}
} catch (FileNotFoundException e) {
Logger.logStackTrace(e);
} catch (IOException e) {
Logger.logStackTrace(e);
}
}
public LinkedHashMap getRestartSpeciesStatus(int i) {
LinkedHashMap speciesStatus = new LinkedHashMap();
try {
FileReader in = new FileReader("Restart/coreSpecies.txt");
BufferedReader reader = new BufferedReader(in);
Integer numRxnSystems = Integer.parseInt(ChemParser.readMeaningfulLine(reader, true));
String line = ChemParser.readMeaningfulLine(reader, true);
while (line != null) {
// The first line of a new species is the user-defined name
String totalSpeciesName = line;
String[] splitString1 = totalSpeciesName.split("[(]");
String[] splitString2 = splitString1[1].split("[)]");
double y = 0.0;
double yprime = 0.0;
for (int j=0; j<numRxnSystems; j++) {
StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
if (j == i) {
y = Double.parseDouble(st.nextToken());
yprime = Double.parseDouble(st.nextToken());
}
}
// The remaining lines are the graph
Graph g = ChemParser.readChemGraph(reader);
// Make the ChemGraph, assuming it does not contain a forbidden structure
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
} catch (ForbiddenStructureException e) {
Logger.critical("Error reading graph: Graph contains a forbidden structure.\n" + g.toString());
System.exit(0);
}
// Make the species
Species species = Species.make(splitString1[0],cg);
// Add the new species to the set of species
//restartCoreSpcs.add(species);
int species_type = 1; // reacted species
SpeciesStatus ss = new SpeciesStatus(species,species_type,y,yprime);
speciesStatus.put(species, ss);
line = ChemParser.readMeaningfulLine(reader, true);
}
} catch (FileNotFoundException e) {
Logger.logStackTrace(e);
} catch (IOException e) {
Logger.logStackTrace(e);
}
return speciesStatus;
}
public void putRestartSpeciesInInitialStatus(InitialStatus is, int i) {
try {
FileReader in = new FileReader("Restart/coreSpecies.txt");
BufferedReader reader = new BufferedReader(in);
String line = ChemParser.readMeaningfulLine(reader, true);
while (line != null) {
// The first line of a new species is the user-defined name
String totalSpeciesName = line;
String[] splitString1 = totalSpeciesName.split("[(]");
String[] splitString2 = splitString1[1].split("[)]");
// The remaining lines are the graph
Graph g = ChemParser.readChemGraph(reader);
// Make the ChemGraph, assuming it does not contain a forbidden structure
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
} catch (ForbiddenStructureException e) {
Logger.critical("Error reading graph: Graph contains a forbidden structure.\n" + g.toString());
System.exit(0);
}
// Make the species
Species species = Species.make(splitString1[0],cg);
// Add the new species to the set of species
//restartCoreSpcs.add(species);
if (is.getSpeciesStatus(species) == null) {
SpeciesStatus ss = new SpeciesStatus(species,1,0.0,0.0);
is.putSpeciesStatus(ss);
}
line = ChemParser.readMeaningfulLine(reader, true);
}
} catch (FileNotFoundException e) {
Logger.logStackTrace(e);
} catch (IOException e) {
Logger.logStackTrace(e);
}
}
public void readPDepNetworks() {
LinkedList allNetworks = PDepNetwork.getNetworks();
try {
FileReader in = new FileReader("Restart/pdepnetworks.txt");
BufferedReader reader = new BufferedReader(in);
StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
String tempString = st.nextToken();
String EaUnits = st.nextToken();
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
tempString = st.nextToken();
int numFameTs = Integer.parseInt(st.nextToken());
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
tempString = st.nextToken();
int numFamePs = Integer.parseInt(st.nextToken());
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
tempString = st.nextToken();
int numChebyTs = Integer.parseInt(st.nextToken());
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
tempString = st.nextToken();
int numChebyPs = Integer.parseInt(st.nextToken());
st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
tempString = st.nextToken();
int numPlogs = Integer.parseInt(st.nextToken());
double[][] rateCoefficients = new double[numFameTs][numFamePs];
double[][] chebyPolys = new double[numChebyTs][numChebyPs];
Kinetics[] plogKinetics = new Kinetics[numPlogs];
String line = ChemParser.readMeaningfulLine(reader, true); // line should be "PDepNetwork #"
while (line != null) {
line = ChemParser.readMeaningfulLine(reader, true); // line should now be "netReactionList:"
PDepNetwork newNetwork = new PDepNetwork();
LinkedList netRxns = newNetwork.getNetReactions();
LinkedList nonincludeRxns = newNetwork.getNonincludedReactions();
line = ChemParser.readMeaningfulLine(reader, true); // line is either data or "nonIncludedReactionList"
// If line is "nonincludedreactionlist", we need to skip over this while loop
if (!line.toLowerCase().startsWith("nonincludedreactionlist")) {
while (!line.toLowerCase().startsWith("nonincludedreactionlist")) {
// Read in the forward rxn
String[] reactsANDprods = line.split("\\-->");
/*
* Determine if netReaction is reversible or irreversible
*/
boolean reactionIsReversible = true;
if (reactsANDprods.length == 2)
reactionIsReversible = false;
else
reactsANDprods = line.split("\\<=>");
PDepIsomer Reactants = parseIsomerFromRestartFile(reactsANDprods[0].trim());
PDepIsomer Products = parseIsomerFromRestartFile(reactsANDprods[1].trim());
newNetwork.addIsomer(Reactants);
newNetwork.addIsomer(Products);
rateCoefficients = parseRateCoeffsFromRestartFile(numFameTs,numFamePs,reader);
PDepRateConstant pdepk = parsePDepRateConstantFromRestartFile(reader,numChebyTs,numChebyPs,rateCoefficients,numPlogs,EaUnits);
PDepReaction forward = new PDepReaction(Reactants, Products, pdepk);
// Read in the reverse reaction
if (reactionIsReversible) {
PDepReaction reverse = new PDepReaction(Products, Reactants, new PDepRateConstant());
reverse.setPDepRateConstant(null);
reverse.setReverseReaction(forward);
forward.setReverseReaction(reverse);
}
else {
PDepReaction reverse = null;
forward.setReverseReaction(reverse);
}
netRxns.add(forward);
line = ChemParser.readMeaningfulLine(reader, true);
}
}
// This loop ends once line == "nonIncludedReactionList"
line = ChemParser.readMeaningfulLine(reader, true); // line is either data or "pathReactionList"
if (!line.toLowerCase().startsWith("pathreactionList")) {
while (!line.toLowerCase().startsWith("pathreactionlist")) {
// Read in the forward rxn
String[] reactsANDprods = line.split("\\-->");
/*
* Determine if nonIncludedReaction is reversible or irreversible
*/
boolean reactionIsReversible = true;
if (reactsANDprods.length == 2)
reactionIsReversible = false;
else
reactsANDprods = line.split("\\<=>");
PDepIsomer Reactants = parseIsomerFromRestartFile(reactsANDprods[0].trim());
PDepIsomer Products = parseIsomerFromRestartFile(reactsANDprods[1].trim());
newNetwork.addIsomer(Reactants);
newNetwork.addIsomer(Products);
rateCoefficients = parseRateCoeffsFromRestartFile(numFameTs,numFamePs,reader);
PDepRateConstant pdepk = parsePDepRateConstantFromRestartFile(reader,numChebyTs,numChebyPs,rateCoefficients,numPlogs,EaUnits);
PDepReaction forward = new PDepReaction(Reactants, Products, pdepk);
// Read in the reverse reaction
if (reactionIsReversible) {
PDepReaction reverse = new PDepReaction(Products, Reactants, new PDepRateConstant());
reverse.setPDepRateConstant(null);
reverse.setReverseReaction(forward);
forward.setReverseReaction(reverse);
}
else {
PDepReaction reverse = null;
forward.setReverseReaction(reverse);
}
nonincludeRxns.add(forward);
line = ChemParser.readMeaningfulLine(reader, true);
}
}
// This loop ends once line == "pathReactionList"
line = ChemParser.readMeaningfulLine(reader, true); // line is either data or "PDepNetwork #_" or null (end of file)
while (line != null && !line.toLowerCase().startsWith("pdepnetwork")) {
st = new StringTokenizer(line);
int direction = Integer.parseInt(st.nextToken());
// First token is the rxn structure: A+B=C+D
// Note: Up to 3 reactants/products allowed
// : Either "=" or "=>" will separate reactants and products
String structure = st.nextToken();
// Separate the reactants from the products
boolean generateReverse = false;
String[] reactsANDprods = structure.split("\\=>");
if (reactsANDprods.length == 1) {
reactsANDprods = structure.split("[=]");
generateReverse = true;
}
SpeciesDictionary sd = SpeciesDictionary.getInstance();
LinkedList r = ChemParser.parseReactionSpecies(sd, reactsANDprods[0]);
LinkedList p = ChemParser.parseReactionSpecies(sd, reactsANDprods[1]);
Structure s = new Structure(r,p);
s.setDirection(direction);
// Next three tokens are the modified Arrhenius parameters
double rxn_A = Double.parseDouble(st.nextToken());
double rxn_n = Double.parseDouble(st.nextToken());
double rxn_E = Double.parseDouble(st.nextToken());
if (EaUnits.equals("cal/mol"))
rxn_E = rxn_E / 1000;
else if (EaUnits.equals("J/mol"))
rxn_E = rxn_E / 4.184 / 1000;
else if (EaUnits.equals("kJ/mol"))
rxn_E = rxn_E / 4.184;
else if (EaUnits.equals("Kelvins"))
rxn_E = rxn_E * 1.987;
UncertainDouble uA = new UncertainDouble(rxn_A,0.0,"A");
UncertainDouble un = new UncertainDouble(rxn_n,0.0,"A");
UncertainDouble uE = new UncertainDouble(rxn_E,0.0,"A");
// The remaining tokens are comments
String comments = "";
if (st.hasMoreTokens()) {
String beginningOfComments = st.nextToken();
int startIndex = line.indexOf(beginningOfComments);
comments = line.substring(startIndex);
}
if (comments.startsWith("!")) comments = comments.substring(1);
// while (st.hasMoreTokens()) {
// comments += st.nextToken();
// }
ArrheniusKinetics[] k = new ArrheniusKinetics[1];
k[0] = new ArrheniusKinetics(uA,un,uE,"",1,"",comments);
Reaction pathRxn = new Reaction();
// if (direction == 1)
// pathRxn = Reaction.makeReaction(s,k,generateReverse);
// else
// pathRxn = Reaction.makeReaction(s.generateReverseStructure(),k,generateReverse);
pathRxn = Reaction.makeReaction(s,k,generateReverse);
PDepIsomer Reactants = new PDepIsomer(r);
PDepIsomer Products = new PDepIsomer(p);
PDepReaction pdeppathrxn = new PDepReaction(Reactants,Products,pathRxn);
newNetwork.addReaction(pdeppathrxn,true);
newNetwork.addIsomer(Reactants);
newNetwork.addIsomer(Products);
line = ChemParser.readMeaningfulLine(reader, true);
}
newNetwork.setAltered(false);
PDepNetwork.getNetworks().add(newNetwork);
}
} catch (FileNotFoundException e) {
Logger.logStackTrace(e);
} catch (IOException e) {
Logger.logStackTrace(e);
}
}
public PDepIsomer parseIsomerFromRestartFile(String p_string) {
SpeciesDictionary sd = SpeciesDictionary.getInstance();
PDepIsomer isomer = null;
if (p_string.contains("+")) {
String[] indivReacts = p_string.split("[+]");
String name = indivReacts[0].trim();
Species spc1 = sd.getSpeciesFromNameID(name);
if (spc1 == null) {
spc1 = getSpeciesBySPCName(name,sd);
}
name = indivReacts[1].trim();
String[] nameANDincluded = name.split("\\(included =");
Species spc2 = sd.getSpeciesFromNameID(nameANDincluded[0].trim());
if (spc2 == null) {
spc2 = getSpeciesBySPCName(name,sd);
}
boolean isIncluded = Boolean.parseBoolean(nameANDincluded[1].substring(0,nameANDincluded[1].length()-1));
isomer = new PDepIsomer(spc1,spc2,isIncluded);
} else {
String name = p_string.trim();
/*
* Separate the (included =boolean) portion of the string
* from the name of the Isomer
*/
String[] nameANDincluded = name.split("\\(included =");
Species spc = sd.getSpeciesFromNameID(nameANDincluded[0].trim());
if (spc == null) {
spc = getSpeciesBySPCName(name,sd);
}
boolean isIncluded = Boolean.parseBoolean(nameANDincluded[1].substring(0,nameANDincluded[1].length()-1));
isomer = new PDepIsomer(spc,isIncluded);
}
return isomer;
}
public double[][] parseRateCoeffsFromRestartFile(int numFameTs, int numFamePs, BufferedReader reader) {
double[][] rateCoefficients = new double[numFameTs][numFamePs];
for (int i=0; i<numFameTs; i++) {
StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
for (int j=0; j<numFamePs; j++) {
rateCoefficients[i][j] = Double.parseDouble(st.nextToken());
}
}
return rateCoefficients;
}
public PDepRateConstant parsePDepRateConstantFromRestartFile(BufferedReader reader,
int numChebyTs, int numChebyPs, double[][] rateCoefficients,
int numPlogs, String EaUnits) {
PDepRateConstant pdepk = null;
if (numChebyTs > 0) {
double chebyPolys[][] = new double[numChebyTs][numChebyPs];
for (int i=0; i<numChebyTs; i++) {
StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
for (int j=0; j<numChebyPs; j++) {
chebyPolys[i][j] = Double.parseDouble(st.nextToken());
}
}
ChebyshevPolynomials chebyshev = new ChebyshevPolynomials(numChebyTs,
ChebyshevPolynomials.getTlow(), ChebyshevPolynomials.getTup(),
numChebyPs, ChebyshevPolynomials.getPlow(), ChebyshevPolynomials.getPup(),
chebyPolys);
pdepk = new PDepRateConstant(rateCoefficients,chebyshev);
} else if (numPlogs > 0) {
PDepArrheniusKinetics pdepAK = new PDepArrheniusKinetics(numPlogs);
for (int i=0; i<numPlogs; i++) {
StringTokenizer st = new StringTokenizer(ChemParser.readMeaningfulLine(reader, true));
Pressure p = new Pressure(Double.parseDouble(st.nextToken()),"Pa");
UncertainDouble dA = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A");
UncertainDouble dn = new UncertainDouble(Double.parseDouble(st.nextToken()),0.0,"A");
double Ea = Double.parseDouble(st.nextToken());
if (EaUnits.equals("cal/mol"))
Ea = Ea / 1000;
else if (EaUnits.equals("J/mol"))
Ea = Ea / 4.184 / 1000;
else if (EaUnits.equals("kJ/mol"))
Ea = Ea / 4.184;
else if (EaUnits.equals("Kelvins"))
Ea = Ea * 1.987;
UncertainDouble dE = new UncertainDouble(Ea,0.0,"A");
ArrheniusKinetics k = new ArrheniusKinetics(dA, dn, dE, "", 1, "", "");
pdepAK.setKinetics(i, p, k);
pdepk = new PDepRateConstant(rateCoefficients,pdepAK);
}
}
return pdepk;
}
/**
* MRH 14Jan2010
*
* getSpeciesBySPCName
*
* Input: String name - Name of species, normally chemical formula followed
* by "J"s for radicals, and then (#)
* SpeciesDictionary sd
*
* This method was originally written as a complement to the method readPDepNetworks.
* jdmo found a bug with the readrestart option. The bug was that the method was
* attempting to add a null species to the Isomer list. The null species resulted
* from searching the SpeciesDictionary by chemkinName (e.g. C4H8OJJ(48)), when the
* chemkinName present in the dictionary was SPC(48).
*
*/
public Species getSpeciesBySPCName(String name, SpeciesDictionary sd) {
String[] nameFromNumber = name.split("\\(");
String newName = "SPC(" + nameFromNumber[1];
return sd.getSpeciesFromChemkinName(newName);
}
/**
* MRH 12-Jun-2009
*
* Function initializes the model's core and edge.
* The initial core species always consists of the species contained
* in the condition.txt file. If seed mechanisms exist, those species
* (and the reactions given in the seed mechanism) are also added to
* the core.
* The initial edge species/reactions are determined by reacting the core
* species by one full iteration.
*/
public void initializeCoreEdgeModel() {
LinkedHashSet allInitialCoreSpecies = new LinkedHashSet();
LinkedHashSet allInitialCoreRxns = new LinkedHashSet();
if (readrestart) {
allInitialCoreSpecies.addAll(restartCoreSpcs);
allInitialCoreRxns.addAll(restartCoreRxns);
}
// Add the species from the condition.txt (input) file
allInitialCoreSpecies.addAll(getSpeciesSeed());
// Add the species from the seed mechanisms, if they exist
if (hasSeedMechanisms()) {
allInitialCoreSpecies.addAll(getSeedMechanism().getSpeciesSet());
allInitialCoreRxns.addAll(getSeedMechanism().getReactionSet());
}
CoreEdgeReactionModel cerm = new CoreEdgeReactionModel(allInitialCoreSpecies, allInitialCoreRxns);
// Store the seed mechanism in the CERM so that we can access it from there when writing chemkin files:
if (hasSeedMechanisms()) {
cerm.setSeedMechanism(getSeedMechanism());
}
if (readrestart) {
cerm.addUnreactedSpeciesSet(restartEdgeSpcs);
cerm.addUnreactedReactionSet(restartEdgeRxns);
}
setReactionModel(cerm);
PDepNetwork.reactionModel = getReactionModel();
PDepNetwork.reactionSystem = (ReactionSystem) getReactionSystemList().get(0);
// Determine initial set of reactions and edge species using only the
// species enumerated in the input file and the seed mechanisms as the core
if (!readrestart) {
LinkedHashSet reactionSet_withdup;
LinkedHashSet reactionSet;
// If Seed Mechanism is present and Generate Reaction is set on
if (hasSeedMechanisms() && getSeedMechanism().shouldGenerateReactions()) {
reactionSet_withdup = getLibraryReactionGenerator().react(allInitialCoreSpecies);
reactionSet_withdup.addAll(getReactionGenerator().react(allInitialCoreSpecies));
// Removing Duplicates instances of reaction if present
reactionSet = getLibraryReactionGenerator().RemoveDuplicateReac(reactionSet_withdup);
}
else {
reactionSet_withdup = new LinkedHashSet();
LinkedHashSet tempnewReactionSet = getLibraryReactionGenerator().react(allInitialCoreSpecies);
if(tempnewReactionSet.isEmpty()){
Logger.info("No reactions of initial core and seed species found in Reaction Library");
}
else {
Logger.info("Reactions of initial core and seed species found in Reaction Library:");
Logger.info(tempnewReactionSet.toString());
}
// Adds Reactions Found in Library Reaction Generator to Reaction Set
reactionSet_withdup.addAll(tempnewReactionSet);
// Generates Reaction from the Reaction Generator and adds them to Reaction Set
Logger.info("Generating reactions of initial core species using reaction families.");
Logger.info("(Condition file species will react with seed species, but seed species will not \n" +
"react with each other because GenerateReactions is off)");
// nb. speciesSeed contains the condition file species (not the seed mechanism species)
for (Iterator iter = speciesSeed.iterator(); iter.hasNext(); ) {
Species spec = (Species) iter.next();
reactionSet_withdup.addAll(getReactionGenerator().react(allInitialCoreSpecies, spec,"All"));
}
reactionSet = getLibraryReactionGenerator().RemoveDuplicateReac(reactionSet_withdup);
}
// Set initial core-edge reaction model based on above results
if (reactionModelEnlarger instanceof RateBasedRME) {
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
cerm.addReaction(r);
}
}
else {
// Only keep the reactions involving bimolecular reactants and bimolecular products
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
if (r.getReactantNumber() > 1 && r.getProductNumber() > 1){
cerm.addReaction(r);
}
else {
cerm.categorizeReaction(r.getStructure());
PDepNetwork.addReactionToNetworks(r);
}
}
}
}
/*
* 22-SEPT-2010
* ELSE:
* If reading in restart files, at the very least, we should react
* all species present in the input file (speciesSeed) with all of
* the coreSpecies. Before, when the following else statement was
* not present, we would completely skip this step. Thus, RMG would
* come to the first ODE solve, integrate to a very large time, and
* conclude that the model was both valid and terminated, thereby
* not adding any new reactions to the core regardless of the
* conditions stated in the input file.
* EXAMPLE:
* A user runs RMG for iso-octane with Restart turned on. The
* simulation converges and now the user would like to add a small
* amount of 1-butanol to the input file, while reading in from the
* Restart files. What should happen, at the very least, is 1-butanol
* reacts with the other species present in the input file and with
* the already-known coreSpecies. This will, at a minimum, add these
* reactions to the core. Whether the model remains validated and
* terminated depends on the conditions stated in the input file.
* MRH ([email protected])
*/
else {
LinkedHashSet reactionSet_withdup;
LinkedHashSet reactionSet;
/*
* If the user has specified a Seed Mechanism, and that the cross reactions
* should be generated, generate those here
* NOTE: Since the coreSpecies from the Restart files are treated as a Seed
* Mechanism, MRH is inclined to comment out the following lines. Depending
* on how large the Seed Mechanism and/or Restart files are, RMG could get
* "stuck" cross-reacting hundreds of species against each other.
*/
// if (hasSeedMechanisms() && getSeedMechanism().shouldGenerateReactions()) {
// reactionSet_withdup = getLibraryReactionGenerator().react(getSeedMechanism().getSpeciesSet());
// reactionSet_withdup.addAll(getReactionGenerator().react(getSeedMechanism().getSpeciesSet()));
// reactionSet = getLibraryReactionGenerator().RemoveDuplicateReac(reactionSet_withdup);
// }
/*
* If not, react the species present in the input file against any
* reaction libraries, and then against all RMG-defined reaction
* families
*/
// else {
reactionSet_withdup = new LinkedHashSet();
LinkedHashSet tempnewReactionSet = getLibraryReactionGenerator().react(speciesSeed);
if (!tempnewReactionSet.isEmpty()) {
Logger.info("Reaction Set Found from Reaction Library "+tempnewReactionSet);
}
// Adds Reactions Found in Library Reaction Generator to Reaction Set
reactionSet_withdup.addAll(tempnewReactionSet);
// Generates Reaction from the Reaction Generator and adds them to Reaction Set
for (Iterator iter = speciesSeed.iterator(); iter.hasNext(); ) {
Species spec = (Species) iter.next();
reactionSet_withdup.addAll(getReactionGenerator().react(allInitialCoreSpecies,spec,"All"));
}
reactionSet = getLibraryReactionGenerator().RemoveDuplicateReac(reactionSet_withdup);
// }
// Set initial core-edge reaction model based on above results
if (reactionModelEnlarger instanceof RateBasedRME) {
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
cerm.addReaction(r);
}
}
else {
// Only keep the reactions involving bimolecular reactants and bimolecular products
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
if (r.getReactantNumber() > 1 && r.getProductNumber() > 1){
cerm.addReaction(r);
}
else {
cerm.categorizeReaction(r.getStructure());
PDepNetwork.addReactionToNetworks(r);
}
}
}
}
for (Integer i = 0; i < reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i);
rs.setReactionModel(getReactionModel());
}
// We cannot return a system with no core reactions, so if this is a case we must add to the core
while (getReactionModel().isEmpty() && !PDepNetwork.hasCoreReactions((CoreEdgeReactionModel) getReactionModel())) {
for (Integer i = 0; i < reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i);
if (reactionModelEnlarger instanceof RateBasedPDepRME)
rs.initializePDepNetwork();
rs.appendUnreactedSpeciesStatus((InitialStatus)initialStatusList.get(i), rs.getPresentTemperature());
}
enlargeReactionModel();
}
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
rs.setReactionModel(getReactionModel());
}
return;
}
//9/24/07 gmagoon: moved from ReactionSystem.java
public void initializeCoreEdgeModelWithPKL() {
initializeCoreEdgeModelWithoutPKL();
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel)getReactionModel();
LinkedHashSet primarySpeciesSet = getPrimaryKineticLibrary().getSpeciesSet(); //10/14/07 gmagoon: changed to use getPrimaryReactionLibrary
LinkedHashSet primaryKineticSet = getPrimaryKineticLibrary().getReactionSet();
cerm.addReactedSpeciesSet(primarySpeciesSet);
cerm.addPrimaryKineticSet(primaryKineticSet);
LinkedHashSet newReactions = getReactionGenerator().react(cerm.getReactedSpeciesSet());
if (reactionModelEnlarger instanceof RateBasedRME)
cerm.addReactionSet(newReactions);
else {
Iterator iter = newReactions.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
if (r.getReactantNumber() == 2 && r.getProductNumber() == 2){
cerm.addReaction(r);
}
}
}
return;
//#]
}
//9/24/07 gmagoon: moved from ReactionSystem.java
protected void initializeCoreEdgeModelWithoutPKL() {
CoreEdgeReactionModel cerm = new CoreEdgeReactionModel(new LinkedHashSet(getSpeciesSeed()));
setReactionModel(cerm);
PDepNetwork.reactionModel = getReactionModel();
PDepNetwork.reactionSystem = (ReactionSystem) getReactionSystemList().get(0);
// Determine initial set of reactions and edge species using only the
// species enumerated in the input file as the core
LinkedHashSet reactionSet = getReactionGenerator().react(getSpeciesSeed());
reactionSet.addAll(getLibraryReactionGenerator().react(getSpeciesSeed()));
// Set initial core-edge reaction model based on above results
if (reactionModelEnlarger instanceof RateBasedRME) {
// Only keep the reactions involving bimolecular reactants and bimolecular products
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
cerm.addReaction(r);
}
}
else {
// Only keep the reactions involving bimolecular reactants and bimolecular products
Iterator iter = reactionSet.iterator();
while (iter.hasNext()){
Reaction r = (Reaction)iter.next();
if (r.getReactantNumber() > 1 && r.getProductNumber() > 1){
cerm.addReaction(r);
}
else {
cerm.categorizeReaction(r.getStructure());
PDepNetwork.addReactionToNetworks(r);
}
}
}
//10/9/07 gmagoon: copy reactionModel to reactionSystem; there may still be scope problems, particularly in above elseif statement
//10/24/07 gmagoon: want to copy same reaction model to all reactionSystem variables; should probably also make similar modifications elsewhere; may or may not need to copy in ...WithPRL function
for (Integer i = 0; i < reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i);
rs.setReactionModel(getReactionModel());
}
//reactionSystem.setReactionModel(getReactionModel());
// We cannot return a system with no core reactions, so if this is a case we must add to the core
while (getReactionModel().isEmpty()&&!PDepNetwork.hasCoreReactions((CoreEdgeReactionModel) getReactionModel())) {
for (Integer i = 0; i < reactionSystemList.size(); i++) {
ReactionSystem rs = (ReactionSystem) reactionSystemList.get(i);
if (reactionModelEnlarger instanceof RateBasedPDepRME)
rs.initializePDepNetwork();
rs.appendUnreactedSpeciesStatus((InitialStatus)initialStatusList.get(i), rs.getPresentTemperature());
}
enlargeReactionModel();
}
for (Integer i = 0; i<reactionSystemList.size();i++) {
ReactionSystem rs = (ReactionSystem)reactionSystemList.get(i);
rs.setReactionModel(getReactionModel());
}
return;
//#]
}
//## operation initializeCoreEdgeReactionModel()
//9/24/07 gmagoon: moved from ReactionSystem.java
public void initializeCoreEdgeReactionModel() {
Logger.info("Initializing core-edge reaction model");
initializeCoreEdgeModel();
}
//9/24/07 gmagoon: copied from ReactionSystem.java
public ReactionGenerator getReactionGenerator() {
return reactionGenerator;
}
//10/4/07 gmagoon: moved from ReactionSystem.java
public void setReactionGenerator(ReactionGenerator p_ReactionGenerator) {
reactionGenerator = p_ReactionGenerator;
}
//9/25/07 gmagoon: moved from ReactionSystem.java
//10/24/07 gmagoon: changed to use reactionSystemList
//## operation enlargeReactionModel()
public void enlargeReactionModel() {
//#[ operation enlargeReactionModel()
if (reactionModelEnlarger == null) throw new NullPointerException("ReactionModelEnlarger");
Logger.info("");
Logger.info("Enlarging reaction model");
reactionModelEnlarger.enlargeReactionModel(reactionSystemList, reactionModel, validList);
return;
//#]
}
public void pruneReactionModel(HashMap unprunableSpecies) {
Runtime runtime = Runtime.getRuntime();
HashMap prunableSpeciesMap = new HashMap();
//check whether all the reaction systems reached target conversion/time
boolean allReachedTarget = true;
for (Integer i = 0; i < reactionSystemList.size(); i++) {
JDAS ds = (JDAS)((ReactionSystem) reactionSystemList.get(i)).getDynamicSimulator();
if (!ds.targetReached) allReachedTarget = false;
}
JDAS ds0 = (JDAS)((ReactionSystem) reactionSystemList.get(0)).getDynamicSimulator(); //get the first reactionSystem dynamic simulator
//prune the reaction model if AUTO is being used, and all reaction systems have reached target time/conversion, and edgeTol is non-zero (and positive, obviously), and if there are a sufficient number of species in the reaction model (edge + core)
if ( JDAS.autoflag &&
allReachedTarget &&
edgeTol>0 &&
(((CoreEdgeReactionModel)reactionModel).getEdge().getSpeciesNumber()+reactionModel.getSpeciesNumber())>= minSpeciesForPruning){
int numberToBePruned = ((CoreEdgeReactionModel)reactionModel).getEdge().getSpeciesNumber() - maxEdgeSpeciesAfterPruning;
//System.out.println("PDep Pruning DEBUG:\nThe number of species in the model's edge, before pruning: " + ((CoreEdgeReactionModel)reactionModel).getEdge().getSpeciesNumber());
//System.out.println("PDep Pruning DEBUG:\nRMG thinks the following number of species" +
// " needs to be pruned: " + numberToBePruned);
Iterator iter = JDAS.edgeID.keySet().iterator();//determine the maximum edge flux ratio for each edge species
while(iter.hasNext()){
Species spe = (Species)iter.next();
Integer id = (Integer)JDAS.edgeID.get(spe);
double maxmaxRatio = ds0.maxEdgeFluxRatio[id-1];
boolean prunable = ds0.prunableSpecies[id-1];
//go through the rest of the reaction systems to see if there are higher max flux ratios
for (Integer i = 1; i < reactionSystemList.size(); i++) {
JDAS ds = (JDAS)((ReactionSystem) reactionSystemList.get(i)).getDynamicSimulator();
if(ds.maxEdgeFluxRatio[id-1] > maxmaxRatio) maxmaxRatio = ds.maxEdgeFluxRatio[id-1];
if(!ds.prunableSpecies[id-1]) prunable = false;// probably redundant: if the conc. is zero in one system, it should be zero in all systems, but it is included for completeness
}
//if the species is "prunable" (i.e. it doesn't have any reactions producing it with zero flux), add it to the prunableSpeciesMap
if( prunable){
prunableSpeciesMap.put(spe, maxmaxRatio);
}
}
//repeat with the edgeLeakID; if a species appears in both lists, it will be prunable only if it is prunable in both cases, and the sum of maximum edgeFlux + maximum edgeLeakFlux (for each reaction system) will be considered; this will be a conservative overestimate of maximum (edgeFlux+edgeLeakFlux)
iter = JDAS.edgeLeakID.keySet().iterator();
while(iter.hasNext()){
Species spe = (Species)iter.next();
Integer id = (Integer)JDAS.edgeLeakID.get(spe);
//check whether the same species is in edgeID
if(JDAS.edgeID.containsKey(spe)){//the species exists in edgeID
if(prunableSpeciesMap.containsKey(spe)){//the species was determined to be "prunable" based on edgeID
Integer idEdge=(Integer)JDAS.edgeID.get(spe);
double maxmaxRatio = ds0.maxEdgeFluxRatio[id-1]+ds0.maxEdgeFluxRatio[idEdge-1];
boolean prunable = ds0.prunableSpecies[id-1];
//go through the rest of the reaction systems to see if there are higher max flux ratios
for (Integer i = 1; i < reactionSystemList.size(); i++) {
JDAS ds = (JDAS)((ReactionSystem) reactionSystemList.get(i)).getDynamicSimulator();
if(ds.maxEdgeFluxRatio[id-1]+ds.maxEdgeFluxRatio[idEdge-1] > maxmaxRatio) maxmaxRatio = ds.maxEdgeFluxRatio[id-1]+ds.maxEdgeFluxRatio[idEdge-1];
if(!ds.prunableSpecies[id-1]) prunable = false;// probably redundant: if the conc. is zero in one system, it should be zero in all systems, but it is included for completeness
}
if( prunable){//if the species is "prunable" (i.e. it doesn't have any reactions producing it with zero flux), replace with the newly determined maxmaxRatio
prunableSpeciesMap.remove(spe);
prunableSpeciesMap.put(spe, maxmaxRatio);
}
else{//otherwise, the species is not prunable in both edgeID and edgeLeakID and should be removed from the prunable species map
prunableSpeciesMap.remove(spe);
}
}
}
else{//the species is new
double maxmaxRatio = ds0.maxEdgeFluxRatio[id-1];
boolean prunable = ds0.prunableSpecies[id-1];
//go through the rest of the reaction systems to see if there are higher max flux ratios
for (Integer i = 1; i < reactionSystemList.size(); i++) {
JDAS ds = (JDAS)((ReactionSystem) reactionSystemList.get(i)).getDynamicSimulator();
if(ds.maxEdgeFluxRatio[id-1] > maxmaxRatio) maxmaxRatio = ds.maxEdgeFluxRatio[id-1];
if(!ds.prunableSpecies[id-1]) prunable = false;// probably redundant: if the conc. is zero in one system, it should be zero in all systems, but it is included for completeness
}
//if the species is "prunable" (i.e. it doesn't have any reactions producing it with zero flux), add it to the prunableSpeciesMap
if( prunable){
prunableSpeciesMap.put(spe, maxmaxRatio);
}
}
}
// at this point prunableSpeciesMap includes ALL prunable species, no matter how large their flux
//System.out.println("PDep Pruning DEBUG:\nRMG has marked the following number of species" +
// " as prunable, before checking against explored (included) species: " + prunableSpeciesMap.size());
// Pressure dependence only: Species that are included in any
// PDepNetwork are not eligible for pruning, so they must be removed
// from the map of prunable species
if (reactionModelEnlarger instanceof RateBasedPDepRME) {
LinkedList speciesToRemove = new LinkedList();
for (iter = prunableSpeciesMap.keySet().iterator(); iter.hasNext(); ) {
Species spec = (Species) iter.next();
if (PDepNetwork.isSpeciesIncludedInAnyNetwork(spec))
speciesToRemove.add(spec);
}
for (iter = speciesToRemove.iterator(); iter.hasNext(); ) {
prunableSpeciesMap.remove(iter.next());
}
}
//System.out.println("PDep Pruning DEBUG:\nRMG now reduced the number of prunable species," +
// " after checking against explored (included) species, to: " + prunableSpeciesMap.size());
// sort the prunableSpecies by maxmaxRatio
// i.e. sort the map by values
List prunableSpeciesList = new LinkedList(prunableSpeciesMap.entrySet());
Collections.sort(prunableSpeciesList, new Comparator() {
public int compare(Object o1, Object o2) {
return ((Comparable) ((Map.Entry) (o1)).getValue())
.compareTo(((Map.Entry) (o2)).getValue());
}
});
List speciesToPrune = new LinkedList();
int belowThreshold = 0;
int lowMaxFlux = 0;
for (Iterator it = prunableSpeciesList.iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
Species spe = (Species)entry.getKey();
double maxmaxRatio = (Double)entry.getValue();
if (maxmaxRatio < edgeTol)
{
Logger.info(String.format("Edge species %s has a maximum flux ratio (%.2g) lower than edge inclusion threshhold (%.2g) and will be pruned.",spe.getChemkinName(),maxmaxRatio,edgeTol ));
speciesToPrune.add(spe);
++belowThreshold;
}
else if ( numberToBePruned - speciesToPrune.size() > 0 ) {
if (maxmaxRatio>tolerance){
Logger.warning(String.format("To reach the requested maximum edge size after pruning (%d) would require pruning species with a maximum flux ratio above the requested overall tolerance (%.2g) which is inconsistent.",maxEdgeSpeciesAfterPruning,tolerance));
Logger.warning(String.format("No more species will be pruned this iteration, leaving an edge size of %d. Please increase your overall Error Tolerance if you'd like more species to be pruned.",maxEdgeSpeciesAfterPruning + numberToBePruned - speciesToPrune.size() ));
break;
}
Logger.info(String.format("Edge species %s has a low maximum flux ratio (%.2g) and will be pruned to reduce the edge size to the maximum (%d).",spe.getChemkinName(),maxmaxRatio,maxEdgeSpeciesAfterPruning ));
speciesToPrune.add(spe);
++lowMaxFlux;
}
else break; // no more to be pruned
}
//System.out.println("PDep Pruning DEBUG:\nRMG has marked the following number of species" +
// " to be pruned due to max flux ratio lower than threshold: " + belowThreshold);
//System.out.println("PDep Pruning DEBUG:\nRMG has marked the following number of species" +
// " to be pruned due to low max flux ratio : " + lowMaxFlux);
runtime.gc();
double memoryUsedBeforePruning = (runtime.totalMemory() - runtime.freeMemory()) / 1.0e6;
//now, speciesToPrune has been filled with species that should be pruned from the edge
Logger.info("Pruning...");
//prune species from the edge
//remove species from the edge and from the species dictionary and from edgeID
iter = speciesToPrune.iterator();
while(iter.hasNext()){
Species spe = (Species)iter.next();
writePrunedEdgeSpecies(spe);
((CoreEdgeReactionModel)getReactionModel()).getUnreactedSpeciesSet().remove(spe);
//SpeciesDictionary.getInstance().getSpeciesSet().remove(spe);
if (!unprunableSpecies.containsValue(spe))
SpeciesDictionary.getInstance().remove(spe);
else Logger.info("Pruning Message: Not removing the following species " +
"from the SpeciesDictionary\nas it is present in a Primary Kinetic / Reaction" +
" Library\nThe species will still be removed from the Edge of the " +
"Reaction Mechanism\n" + spe.toString());
JDAS.edgeID.remove(spe);
JDAS.edgeLeakID.remove(spe); // this would get cleaned up in another iteration when edgeLeakID is rebuilt, but debugging memory leaks is simpler if we explicitly clear it here.
}
//remove reactions from the edge involving pruned species
ReactionTemplateLibrary rtl = ReactionTemplateLibrary.getINSTANCE();
iter = ((CoreEdgeReactionModel)getReactionModel()).getUnreactedReactionSet().iterator();
HashSet toRemove = new HashSet();
while(iter.hasNext()){
Reaction reaction = (Reaction)iter.next();
if (reactionPrunableQ(reaction, speciesToPrune)) toRemove.add(reaction);
}
iter = toRemove.iterator();
while(iter.hasNext()){
Reaction reaction = (Reaction)iter.next();
writePrunedEdgeReaction(reaction);
Reaction reverse = reaction.getReverseReaction();
((CoreEdgeReactionModel)reactionModel).removeFromUnreactedReactionSet(reaction);
((CoreEdgeReactionModel)reactionModel).removeFromUnreactedReactionSet(reverse);
int number_removed;
number_removed = rtl.removeFromAllReactionDictionariesByStructure(reaction.getStructure());
if (number_removed != 1)
Logger.info(String.format("Removed edge forward %s from %s dictionaries",reaction.getStructure(),number_removed));
if (reverse != null) {
number_removed = rtl.removeFromAllReactionDictionariesByStructure(reverse.getStructure());
if (number_removed != 1)
Logger.info(String.format("Removed edge reverse %s from %s dictionaries",reverse.getStructure(),number_removed));
}
reaction.prune();
if (reverse != null) reverse.prune();
}
//remove reactions from PDepNetworks in PDep cases
if (reactionModelEnlarger instanceof RateBasedPDepRME) {
iter = PDepNetwork.getNetworks().iterator();
HashSet pdnToRemove = new HashSet();
HashSet toRemovePath;
HashSet toRemoveNet;
HashSet toRemoveNonincluded;
HashSet toRemoveIsomer;
while (iter.hasNext()){
PDepNetwork pdn = (PDepNetwork)iter.next();
//identify path reactions to remove
Iterator rIter = pdn.getPathReactions().iterator();
toRemovePath = new HashSet();
while(rIter.hasNext()){
Reaction reaction = (Reaction)rIter.next();
if (reactionPrunableQ(reaction, speciesToPrune)) toRemovePath.add(reaction);
}
//identify net reactions to remove
rIter = pdn.getNetReactions().iterator();
toRemoveNet = new HashSet();
while(rIter.hasNext()){
Reaction reaction = (Reaction)rIter.next();
if (reactionPrunableQ(reaction, speciesToPrune)) toRemoveNet.add(reaction);
}
//identify nonincluded reactions to remove
rIter = pdn.getNonincludedReactions().iterator();
toRemoveNonincluded = new HashSet();
while(rIter.hasNext()){
Reaction reaction = (Reaction)rIter.next();
if (reactionPrunableQ(reaction, speciesToPrune)) toRemoveNonincluded.add(reaction);
}
//identify isomers to remove
Iterator iIter = pdn.getIsomers().iterator();
toRemoveIsomer = new HashSet();
while(iIter.hasNext()){
PDepIsomer pdi = (PDepIsomer)iIter.next();
Iterator isIter = pdi.getSpeciesListIterator();
while(isIter.hasNext()){
Species spe = (Species)isIter.next();
if (speciesToPrune.contains(spe)&&!toRemove.contains(pdi)) toRemoveIsomer.add(pdi);
}
if(pdi.getSpeciesList().size()==0 && !toRemove.contains(pdi)) toRemoveIsomer.add(pdi);//if the pdi doesn't contain any species, schedule it for removal
}
//remove path reactions
Iterator iterRem = toRemovePath.iterator();
while(iterRem.hasNext()){
Reaction reaction = (Reaction)iterRem.next();
Reaction reverse = reaction.getReverseReaction();
pdn.removeFromPathReactionList((PDepReaction)reaction);
pdn.removeFromPathReactionList((PDepReaction)reverse);
Structure fwd_structure = reaction.getStructure();
Structure rev_structure = null;
if (reverse != null) {
rev_structure = reverse.getStructure();
}
else {
rev_structure = fwd_structure.generateReverseStructure();
}
int number_removed;
number_removed = rtl.removeFromAllReactionDictionariesByStructure(fwd_structure);
if (number_removed != 1)
Logger.info(String.format("Removed path forward %s from %s dictionaries",fwd_structure,number_removed));
number_removed = rtl.removeFromAllReactionDictionariesByStructure(rev_structure);
if (number_removed != 1)
Logger.info(String.format("Removed path reverse %s from %s dictionaries",rev_structure,number_removed));
reaction.prune();
if (reverse != null) reverse.prune();
}
//remove net reactions
iterRem = toRemoveNet.iterator();
while(iterRem.hasNext()){
Reaction reaction = (Reaction)iterRem.next();
Reaction reverse = reaction.getReverseReaction();
pdn.removeFromNetReactionList((PDepReaction)reaction);
pdn.removeFromNetReactionList((PDepReaction)reverse);
reaction.prune();
if (reverse != null) reverse.prune();
}
//remove nonincluded reactions
iterRem = toRemoveNonincluded.iterator();
while(iterRem.hasNext()){
Reaction reaction = (Reaction)iterRem.next();
Reaction reverse = reaction.getReverseReaction();
pdn.removeFromNonincludedReactionList((PDepReaction)reaction);
pdn.removeFromNonincludedReactionList((PDepReaction)reverse);
reaction.prune();
if (reverse != null) reverse.prune();
}
//remove isomers
iterRem = toRemoveIsomer.iterator();
while(iterRem.hasNext()){
PDepIsomer pdi = (PDepIsomer)iterRem.next();
pdn.removeFromIsomerList(pdi);
}
//remove the entire network if the network has no path or net reactions
if(pdn.getPathReactions().size()==0&&pdn.getNetReactions().size()==0) pdnToRemove.add(pdn);
}
iter = pdnToRemove.iterator();
while (iter.hasNext()){
PDepNetwork pdn = (PDepNetwork)iter.next();
PDepNetwork.getNetworks().remove(pdn);
}
}
runtime.gc();
double memoryUsedAfterPruning = (runtime.totalMemory() - runtime.freeMemory()) / 1.0e6;
Logger.info(String.format("Number of species pruned: %d", speciesToPrune.size()));
Logger.info(String.format("Memory used before pruning: %10.2f MB", memoryUsedBeforePruning));
Logger.info(String.format("Memory used after pruning: %10.2f MB", memoryUsedAfterPruning));
if (memoryUsedAfterPruning < memoryUsedBeforePruning)
Logger.info(String.format("Memory recovered by pruning: %10.2f MB", memoryUsedBeforePruning - memoryUsedAfterPruning));
else if (speciesToPrune.size() > 100)
// There were a significant number of species pruned, but we didn't recover any memory
Logger.warning("No memory recovered due to pruning!");
}
//System.out.println("PDep Pruning DEBUG:\nThe number of species in the model's edge, after pruning: " + ((CoreEdgeReactionModel)reactionModel).getEdge().getSpeciesNumber());
return;
}
//determines whether a reaction can be removed; returns true ; cf. categorizeReaction() in CoreEdgeReactionModel
//returns true if the reaction involves reactants or products that are in p_prunableSpecies; otherwise returns false
public boolean reactionPrunableQ(Reaction p_reaction, Collection p_prunableSpecies){
Iterator iter = p_reaction.getReactants();
while (iter.hasNext()) {
Species spe = (Species)iter.next();
if (p_prunableSpecies.contains(spe))
return true;
}
iter = p_reaction.getProducts();
while (iter.hasNext()) {
Species spe = (Species)iter.next();
if (p_prunableSpecies.contains(spe))
return true;
}
return false;
}
public boolean hasPrimaryKineticLibrary() {
if (primaryKineticLibrary == null) return false;
return (primaryKineticLibrary.size() > 0);
}
public boolean hasSeedMechanisms() {
if (getSeedMechanism() == null) return false;
return (seedMechanism.size() > 0);
}
//9/25/07 gmagoon: moved from ReactionSystem.java
public PrimaryKineticLibrary getPrimaryKineticLibrary() {
return primaryKineticLibrary;
}
//9/25/07 gmagoon: moved from ReactionSystem.java
public void setPrimaryKineticLibrary(PrimaryKineticLibrary p_PrimaryKineticLibrary) {
primaryKineticLibrary = p_PrimaryKineticLibrary;
}
public ReactionLibrary getReactionLibrary() {
return ReactionLibrary;
}
public void setReactionLibrary(ReactionLibrary p_ReactionLibrary) {
ReactionLibrary = p_ReactionLibrary;
}
//10/4/07 gmagoon: added
public LinkedHashSet getSpeciesSeed() {
return speciesSeed;
}
//10/4/07 gmagoon: added
public void setSpeciesSeed(LinkedHashSet p_speciesSeed) {
speciesSeed = p_speciesSeed;
}
//10/4/07 gmagoon: added
public LibraryReactionGenerator getLibraryReactionGenerator() {
return lrg;
}
//10/4/07 gmagoon: added
public void setLibraryReactionGenerator(LibraryReactionGenerator p_lrg) {
lrg = p_lrg;
}
public static Temperature getTemp4BestKinetics() {
return temp4BestKinetics;
}
public static void setTemp4BestKinetics(Temperature firstSysTemp) {
temp4BestKinetics = firstSysTemp;
}
public SeedMechanism getSeedMechanism() {
return seedMechanism;
}
public void setSeedMechanism(SeedMechanism p_seedMechanism) {
seedMechanism = p_seedMechanism;
}
public PrimaryThermoLibrary getPrimaryThermoLibrary() {
return primaryThermoLibrary;
}
public void setPrimaryThermoLibrary(PrimaryThermoLibrary p_primaryThermoLibrary) {
primaryThermoLibrary = p_primaryThermoLibrary;
}
public static double getAtol(){
return atol;
}
public boolean runKillableToPreventInfiniteLoop(boolean intermediateSteps, int iterationNumber) {
ReactionSystem rs0 = (ReactionSystem)reactionSystemList.get(0);
if (!intermediateSteps)//if there are no intermediate steps (for example when using AUTO method), return true;
return true;
//if there are intermediate steps, the run is killable if the iteration number exceeds the number of time steps / conversions
else if (rs0.finishController.terminationTester instanceof ReactionTimeTT){
if (iterationNumber - 1 > timeStep.size()){ //-1 correction needed since when this is called, iteration number has been incremented
return true;
}
}
else //the case where intermediate conversions are specified
if (iterationNumber - 1 > numConversions){ //see above; it is possible there is an off-by-one error here, so further testing will be needed
return true;
}
return false; //return false if none of the above criteria are met
}
public void readAndMakePKL(BufferedReader reader) throws IOException {
int Ilib = 0;
String line = ChemParser.readMeaningfulLine(reader, true);
while (!line.equals("END")) {
String name = extractLibraryName(line);
line = ChemParser.readMeaningfulLine(reader, true);
String[] tempString = line.split("Location: ");
String location = tempString[tempString.length-1].trim();
String path = System.getProperty("jing.rxn.ReactionLibrary.pathName");
path += "/" + location;
if (Ilib==0) {
setPrimaryKineticLibrary(new PrimaryKineticLibrary(name, path));
Ilib++;
}
else {
getPrimaryKineticLibrary().appendPrimaryKineticLibrary(name, path);
Ilib++;
}
line = ChemParser.readMeaningfulLine(reader, true);
}
if (Ilib==0) {
setPrimaryKineticLibrary(null);
}
else Logger.info("Primary Kinetic Libraries in use: " + getPrimaryKineticLibrary().getName());
}
public void readAndMakeReactionLibrary(BufferedReader reader) throws IOException {
int Ilib = 0;
String line = ChemParser.readMeaningfulLine(reader, true);
while (!line.equals("END")) {
String name = extractLibraryName(line);
line = ChemParser.readMeaningfulLine(reader, true);
String[] tempString = line.split("Location: ");
String location = tempString[tempString.length-1].trim();
String path = System.getProperty("jing.rxn.ReactionLibrary.pathName");
path += "/" + location;
if (Ilib==0) {
setReactionLibrary(new ReactionLibrary(name, path));
Ilib++;
}
else {
getReactionLibrary().appendReactionLibrary(name, path);
Ilib++;
}
line = ChemParser.readMeaningfulLine(reader, true);
}
if (Ilib==0) {
setReactionLibrary(null);
}
else Logger.info("Reaction Libraries in use: " + getReactionLibrary().getName());
}
public void readAndMakePTL(BufferedReader reader) {
int numPTLs = 0;
String line = ChemParser.readMeaningfulLine(reader, true);
while (!line.equals("END")) {
String name = extractLibraryName(line);
line = ChemParser.readMeaningfulLine(reader, true);
String[] tempString = line.split("Location: ");
String path = tempString[tempString.length-1].trim();
if (numPTLs==0) {
setPrimaryThermoLibrary(new PrimaryThermoLibrary(name,path));
++numPTLs;
}
else {
getPrimaryThermoLibrary().appendPrimaryThermoLibrary(name,path);
++numPTLs;
}
line = ChemParser.readMeaningfulLine(reader, true);
}
if (numPTLs == 0) setPrimaryThermoLibrary(null);
}
public void readExtraForbiddenStructures(BufferedReader reader) throws IOException {
Logger.info("Reading extra forbidden structures from input file.");
String line = ChemParser.readMeaningfulLine(reader, true);
while (!line.equals("END")) {
StringTokenizer token = new StringTokenizer(line);
String fgname = token.nextToken();
Graph fgGraph = null;
try {
fgGraph = ChemParser.readFGGraph(reader);
}
catch (InvalidGraphFormatException e) {
Logger.error("Invalid functional group in "+fgname);
throw new InvalidFunctionalGroupException(fgname + ": " + e.getMessage());
}
if (fgGraph == null) throw new InvalidFunctionalGroupException(fgname);
FunctionalGroup fg = FunctionalGroup.makeForbiddenStructureFG(fgname, fgGraph);
ChemGraph.addForbiddenStructure(fg);
line = ChemParser.readMeaningfulLine(reader, true);
Logger.debug(" Forbidden structure: "+fgname);
}
}
public void setSpectroscopicDataMode(String line) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String sdeType = st.nextToken().toLowerCase();
if (sdeType.equals("frequencygroups") || sdeType.equals("default")) {
SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
}
else if (sdeType.equals("therfit") || sdeType.equals("threefrequencymodel")) {
SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY;
}
else if (sdeType.equals("off") || sdeType.equals("none")) {
SpectroscopicData.mode = SpectroscopicData.Mode.OFF;
}
else throw new InvalidSymbolException("condition.txt: Unknown SpectroscopicDataEstimator = " + sdeType);
}
/**
* Sets the pressure dependence options to on or off. If on, checks for
* more options and sets them as well.
* @param line The current line in the condition file; should start with "PressureDependence:"
* @param reader The reader currently being used to parse the condition file
*/
public String setPressureDependenceOptions(String line, BufferedReader reader) throws InvalidSymbolException {
// Determine pressure dependence mode
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken(); // Should be "PressureDependence:"
String pDepType = st.nextToken();
if (pDepType.toLowerCase().equals("off")) {
// No pressure dependence
reactionModelEnlarger = new RateBasedRME();
PDepNetwork.generateNetworks = false;
/*
* If the Spectroscopic Data Estimator field is set to "Frequency Groups,"
* terminate the RMG job and inform the user to either:
* a) Set the Spectroscopic Data Estimator field to "off," OR
* b) Select a pressure-dependent model
*
* Before, RMG would read in "Frequency Groups" with no pressure-dependence
* and carry on. However, the calculated frequencies would not be stored /
* reported (plus increase the runtime), so no point in calculating them.
*/
if (SpectroscopicData.mode != SpectroscopicData.mode.OFF) {
Logger.critical("Terminating RMG simulation: User requested frequency estimation, " +
"yet no pressure-dependence.\nSUGGESTION: Set the " +
"SpectroscopicDataEstimator field in the input file to 'off'.");
System.exit(0);
}
line = ChemParser.readMeaningfulLine(reader, true);
}
else if (pDepType.toLowerCase().equals("modifiedstrongcollision") ||
pDepType.toLowerCase().equals("reservoirstate") ||
pDepType.toLowerCase().equals("chemdis")) {
reactionModelEnlarger = new RateBasedPDepRME();
PDepNetwork.generateNetworks = true;
// Set pressure dependence method
if (pDepType.toLowerCase().equals("reservoirstate"))
((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new FastMasterEqn(FastMasterEqn.Mode.RESERVOIRSTATE));
else if (pDepType.toLowerCase().equals("modifiedstrongcollision"))
((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new FastMasterEqn(FastMasterEqn.Mode.STRONGCOLLISION));
//else if (pDepType.toLowerCase().equals("chemdis"))
// ((RateBasedPDepRME) reactionModelEnlarger).setPDepKineticsEstimator(new Chemdis());
else
throw new InvalidSymbolException("condition.txt: Unknown PressureDependence mode = " + pDepType);
RateBasedPDepRME pdepModelEnlarger = (RateBasedPDepRME) reactionModelEnlarger;
// Turn on spectroscopic data estimation if not already on
if (pdepModelEnlarger.getPDepKineticsEstimator() instanceof FastMasterEqn && SpectroscopicData.mode == SpectroscopicData.Mode.OFF) {
Logger.warning("Spectroscopic data needed for pressure dependence; switching SpectroscopicDataEstimator to FrequencyGroups.");
SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
}
else if (pdepModelEnlarger.getPDepKineticsEstimator() instanceof Chemdis && SpectroscopicData.mode != SpectroscopicData.Mode.THREEFREQUENCY) {
Logger.warning("Switching SpectroscopicDataEstimator to three-frequency model.");
SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY;
}
// Next line must be PDepKineticsModel
line = ChemParser.readMeaningfulLine(reader, true);
if (line.toLowerCase().startsWith("pdepkineticsmodel:")) {
st = new StringTokenizer(line);
name = st.nextToken();
String pDepKinType = st.nextToken();
if (pDepKinType.toLowerCase().equals("chebyshev")) {
PDepRateConstant.setDefaultMode(PDepRateConstant.Mode.CHEBYSHEV);
// Default is to cubic order for basis functions
FastMasterEqn.setNumTBasisFuncs(4);
FastMasterEqn.setNumPBasisFuncs(4);
}
else if (pDepKinType.toLowerCase().equals("pdeparrhenius"))
PDepRateConstant.setDefaultMode(PDepRateConstant.Mode.PDEPARRHENIUS);
else if (pDepKinType.toLowerCase().equals("rate"))
PDepRateConstant.setDefaultMode(PDepRateConstant.Mode.RATE);
else
throw new InvalidSymbolException("condition.txt: Unknown PDepKineticsModel = " + pDepKinType);
// For Chebyshev polynomials, optionally specify the number of
// temperature and pressure basis functions
// Such a line would read, e.g.: "PDepKineticsModel: Chebyshev 4 4"
if (st.hasMoreTokens() && PDepRateConstant.getDefaultMode() == PDepRateConstant.Mode.CHEBYSHEV) {
try {
int numTBasisFuncs = Integer.parseInt(st.nextToken());
int numPBasisFuncs = Integer.parseInt(st.nextToken());
FastMasterEqn.setNumTBasisFuncs(numTBasisFuncs);
FastMasterEqn.setNumPBasisFuncs(numPBasisFuncs);
}
catch (NoSuchElementException e) {
throw new InvalidSymbolException("condition.txt: Missing number of pressure basis functions for Chebyshev polynomials.");
}
}
}
else
throw new InvalidSymbolException("condition.txt: Missing PDepKineticsModel after PressureDependence line.");
// Determine temperatures and pressures to use
// These can be specified automatically using TRange and PRange or
// manually using Temperatures and Pressures
Temperature[] temperatures = null;
Pressure[] pressures = null;
String Tunits = "K";
Temperature Tmin = new Temperature(300.0, "K");
Temperature Tmax = new Temperature(2000.0, "K");
int Tnumber = 8;
String Punits = "bar";
Pressure Pmin = new Pressure(0.01, "bar");
Pressure Pmax = new Pressure(100.0, "bar");
int Pnumber = 5;
// Read next line of input
line = ChemParser.readMeaningfulLine(reader, true);
boolean done = !(line.toLowerCase().startsWith("trange:") ||
line.toLowerCase().startsWith("prange:") ||
line.toLowerCase().startsWith("temperatures:") ||
line.toLowerCase().startsWith("pressures:"));
// Parse lines containing pressure dependence options
// Possible options are "TRange:", "PRange:", "Temperatures:", and "Pressures:"
// You must specify either TRange or Temperatures and either PRange or Pressures
// The order does not matter
while (!done) {
st = new StringTokenizer(line);
name = st.nextToken();
if (line.toLowerCase().startsWith("trange:")) {
Tunits = ChemParser.removeBrace(st.nextToken());
Tmin = new Temperature(Double.parseDouble(st.nextToken()), Tunits);
Tmax = new Temperature(Double.parseDouble(st.nextToken()), Tunits);
Tnumber = Integer.parseInt(st.nextToken());
}
else if (line.toLowerCase().startsWith("prange:")) {
Punits = ChemParser.removeBrace(st.nextToken());
Pmin = new Pressure(Double.parseDouble(st.nextToken()), Punits);
Pmax = new Pressure(Double.parseDouble(st.nextToken()), Punits);
Pnumber = Integer.parseInt(st.nextToken());
}
else if (line.toLowerCase().startsWith("temperatures:")) {
Tnumber = Integer.parseInt(st.nextToken());
Tunits = ChemParser.removeBrace(st.nextToken());
temperatures = new Temperature[Tnumber];
for (int i = 0; i < Tnumber; i++) {
temperatures[i] = new Temperature(Double.parseDouble(st.nextToken()), Tunits);
}
Tmin = temperatures[0];
Tmax = temperatures[Tnumber-1];
}
else if (line.toLowerCase().startsWith("pressures:")) {
Pnumber = Integer.parseInt(st.nextToken());
Punits = ChemParser.removeBrace(st.nextToken());
pressures = new Pressure[Pnumber];
for (int i = 0; i < Pnumber; i++) {
pressures[i] = new Pressure(Double.parseDouble(st.nextToken()), Punits);
}
Pmin = pressures[0];
Pmax = pressures[Pnumber-1];
}
// Read next line of input
line = ChemParser.readMeaningfulLine(reader, true);
done = !(line.toLowerCase().startsWith("trange:") ||
line.toLowerCase().startsWith("prange:") ||
line.toLowerCase().startsWith("temperatures:") ||
line.toLowerCase().startsWith("pressures:"));
}
// Set temperatures and pressures (if not already set manually)
if (temperatures == null) {
temperatures = new Temperature[Tnumber];
if (PDepRateConstant.getDefaultMode() == PDepRateConstant.Mode.CHEBYSHEV) {
// Use the Gauss-Chebyshev points
// The formula for the Gauss-Chebyshev points was taken from
// the Chemkin theory manual
for (int i = 1; i <= Tnumber; i++) {
double T = -Math.cos((2 * i - 1) * Math.PI / (2 * Tnumber));
T = 2.0 / ((1.0/Tmax.getK() - 1.0/Tmin.getK()) * T + 1.0/Tmax.getK() + 1.0/Tmin.getK());
temperatures[i-1] = new Temperature(T, "K");
}
}
else {
// Distribute equally on a 1/T basis
double slope = (1.0/Tmax.getK() - 1.0/Tmin.getK()) / (Tnumber - 1);
for (int i = 0; i < Tnumber; i++) {
double T = 1.0/(slope * i + 1.0/Tmin.getK());
temperatures[i] = new Temperature(T, "K");
}
}
}
if (pressures == null) {
pressures = new Pressure[Pnumber];
if (PDepRateConstant.getDefaultMode() == PDepRateConstant.Mode.CHEBYSHEV) {
// Use the Gauss-Chebyshev points
// The formula for the Gauss-Chebyshev points was taken from
// the Chemkin theory manual
for (int i = 1; i <= Pnumber; i++) {
double P = -Math.cos((2 * i - 1) * Math.PI / (2 * Pnumber));
P = Math.pow(10, 0.5 * ((Math.log10(Pmax.getBar()) - Math.log10(Pmin.getBar())) * P + Math.log10(Pmax.getBar()) + Math.log10(Pmin.getBar())));
pressures[i-1] = new Pressure(P, "bar");
}
}
else {
// Distribute equally on a log P basis
double slope = (Math.log10(Pmax.getBar()) - Math.log10(Pmin.getBar())) / (Pnumber - 1);
for (int i = 0; i < Pnumber; i++) {
double P = Math.pow(10, slope * i + Math.log10(Pmin.getBar()));
pressures[i] = new Pressure(P, "bar");
}
}
}
FastMasterEqn.setTemperatures(temperatures);
PDepRateConstant.setTemperatures(temperatures);
PDepRateConstant.setTMin(Tmin);
PDepRateConstant.setTMax(Tmax);
ChebyshevPolynomials.setTlow(Tmin);
ChebyshevPolynomials.setTup(Tmax);
FastMasterEqn.setPressures(pressures);
PDepRateConstant.setPressures(pressures);
PDepRateConstant.setPMin(Pmin);
PDepRateConstant.setPMax(Pmax);
ChebyshevPolynomials.setPlow(Pmin);
ChebyshevPolynomials.setPup(Pmax);
/*
* New option for input file: DecreaseGrainSize
* User now has the option to re-run fame with additional grains
* (smaller grain size) when the p-dep rate exceeds the
* high-P-limit rate.
* Default value: off
*/
if (line.toLowerCase().startsWith("decreasegrainsize")) {
st = new StringTokenizer(line);
String tempString = st.nextToken(); // "DecreaseGrainSize:"
tempString = st.nextToken().trim().toLowerCase();
if (tempString.equals("on") || tempString.equals("yes") ||
tempString.equals("true")) {
rerunFame = true;
} else rerunFame = false;
line = ChemParser.readMeaningfulLine(reader, true);
}
}
else {
throw new InvalidSymbolException("condition.txt: Unknown PressureDependence = " + pDepType);
}
return line;
}
public void createTModel(String line) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String modelType = st.nextToken();
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (modelType.equals("Constant")) {
tempList = new LinkedList();
//read first temperature
double t = Double.parseDouble(st.nextToken());
tempList.add(new ConstantTM(t, unit));
Temperature temp = new Temperature(t, unit);//10/29/07 gmagoon: added this line and next two lines to set Global.lowTemperature and Global.highTemperature
Global.lowTemperature = (Temperature)temp.clone();
Global.highTemperature = (Temperature)temp.clone();
//read remaining temperatures
while (st.hasMoreTokens()) {
t = Double.parseDouble(st.nextToken());
tempList.add(new ConstantTM(t, unit));
temp = new Temperature(t,unit);//10/29/07 gmagoon: added this line and next two "if" statements to set Global.lowTemperature and Global.highTemperature
if(temp.getK() < Global.lowTemperature.getK())
Global.lowTemperature = (Temperature)temp.clone();
if(temp.getK() > Global.highTemperature.getK())
Global.highTemperature = (Temperature)temp.clone();
}
}
else {
throw new InvalidSymbolException("condition.txt: Unknown TemperatureModel = " + modelType);
}
}
public void createPModel(String line) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String modelType = st.nextToken();
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
if (modelType.equals("Constant")) {
presList = new LinkedList();
//read first pressure
double p = Double.parseDouble(st.nextToken());
Pressure pres = new Pressure(p, unit);
Global.lowPressure = (Pressure)pres.clone();
Global.highPressure = (Pressure)pres.clone();
presList.add(new ConstantPM(p, unit));
//read remaining temperatures
while (st.hasMoreTokens()) {
p = Double.parseDouble(st.nextToken());
presList.add(new ConstantPM(p, unit));
pres = new Pressure(p, unit);
if(pres.getBar() < Global.lowPressure.getBar())
Global.lowPressure = (Pressure)pres.clone();
if(pres.getBar() > Global.lowPressure.getBar())
Global.highPressure = (Pressure)pres.clone();
}
}
else {
throw new InvalidSymbolException("condition.txt: Unknown PressureModel = " + modelType);
}
}
public LinkedHashMap populateInitialStatusListWithReactiveSpecies(BufferedReader reader) throws IOException {
LinkedHashMap speciesSet = new LinkedHashMap();
LinkedHashMap speciesStatus = new LinkedHashMap();
LinkedHashMap speciesFromInputFileSet = new LinkedHashMap();
int numSpeciesStatus = 0;
String line = ChemParser.readMeaningfulLine(reader, true);
while (!line.equals("END")) {
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String name = null;
if (!index.startsWith("(")) name = index;
else name = st.nextToken();
//if (restart) name += "("+speciesnum+")";
// 24Jun2009: MRH
// Check if the species name begins with a number.
// If so, terminate the program and inform the user to choose
// a different name. This is implemented so that the chem.inp
// file generated will be valid when run in Chemkin
try {
int doesNameBeginWithNumber = Integer.parseInt(name.substring(0,1));
Logger.critical("\nA species name should not begin with a number." +
" Please rename species: " + name + "\n");
System.exit(0);
} catch (NumberFormatException e) {
// We're good
}
if (!(st.hasMoreTokens())) throw new InvalidSymbolException("Couldn't find concentration of species: "+name);
// The next token will be the concentration units
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
// Read in the graph (and make the species) before we parse all of the concentrations
// Will store each SpeciesStatus (NXM where N is the # of species and M is the # of
// concentrations) in a LinkedHashMap, with a (int) counter as the unique key
Graph g = ChemParser.readChemGraph(reader);
ChemGraph cg = null;
try {
cg = ChemGraph.make(g);
}
catch (ForbiddenStructureException e) {
Logger.error("Forbidden Structure:\n" + e.getMessage());
throw new InvalidSymbolException("A species in the input file has a forbidden structure.");
}
//System.out.println(name);
// Check to see if chemgraph already appears in the input file
addChemGraphToListIfNotPresent_ElseTerminate(speciesFromInputFileSet,cg,name);
Species species = Species.make(name,cg);
int numConcentrations = 0; // The number of concentrations read-in for each species
// The remaining tokens are either:
// The desired concentrations
// The flag "unreactive"
// The flag "constantconcentration"
//GJB to allow "unreactive" species that only follow user-defined library reactions.
// They will not react according to RMG reaction families
boolean IsReactive = true;
boolean IsConstantConcentration = false;
double concentration = 0.0;
while (st.hasMoreTokens()) {
String reactive = st.nextToken().trim();
if (reactive.equalsIgnoreCase("unreactive"))
IsReactive = false;
else if (reactive.equalsIgnoreCase("constantconcentration"))
IsConstantConcentration=true;
else {
try {
concentration = Double.parseDouble(reactive);
} catch (NumberFormatException e) {
Logger.error(String.format("Unable to read concentration value '%s'. Check syntax of input line '%s'.",reactive,line));
throw e;
}
if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
concentration /= 1000;
unit = "mol/cm3";
}
else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
concentration /= 1000000;
unit = "mol/cm3";
}
else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
concentration /= 6.022e23;
}
else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
Logger.error(String.format("Unable to read concentration units '%s'. Check syntax of input line '%s'.",unit,line));
throw new InvalidUnitException("Species Concentration in condition.txt!");
}
SpeciesStatus ss = new SpeciesStatus(species,1,concentration,0.0);
speciesStatus.put(numSpeciesStatus, ss);
++numSpeciesStatus;
++numConcentrations;
}
}
// Check if the number of concentrations read in is consistent with all previous
// concentration counts. The first time this function is called, the variable
// numberOfEquivalenceRatios will be initialized.
boolean goodToGo = areTheNumberOfConcentrationsConsistent(numConcentrations);
if (!goodToGo) {
Logger.critical("\n\nThe number of concentrations (" + numConcentrations + ") supplied for species " + species.getName() +
"\nis not consistent with the number of concentrations (" + numberOfEquivalenceRatios + ") " +
"supplied for all previously read-in species \n\n" +
"Terminating RMG simulation.");
System.exit(0);
}
// Make a SpeciesStatus and store it in the LinkedHashMap
// double flux = 0;
// int species_type = 1; // reacted species
species.setReactivity(IsReactive); // GJB
species.setConstantConcentration(IsConstantConcentration);
speciesSet.put(name, species);
getSpeciesSeed().add(species);
line = ChemParser.readMeaningfulLine(reader, true);
}
ReactionTime initial = new ReactionTime(0,"S");
//10/23/07 gmagoon: modified for handling multiple temperature, pressure conditions; note: concentration within speciesStatus (and list of conversion values) should not need to be modified for each T,P since this is done within isTPCconsistent in ReactionSystem
initialStatusList = new LinkedList();
for (Iterator iter = tempList.iterator(); iter.hasNext(); ) {
TemperatureModel tm = (TemperatureModel)iter.next();
for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){
PressureModel pm = (PressureModel)iter2.next();
// LinkedHashMap speStat = (LinkedHashMap)speciesStatus.clone();//10/31/07 gmagoon: trying creating multiple instances of speciesStatus to address issues with concentration normalization (last normalization seems to apply to all)
// Set ks = speciesStatus.keySet();
// for (Iterator iter3 = ks.iterator(); iter3.hasNext();){//11/1/07 gmagoon: perform deep copy; (is there an easier or more elegant way to do this?)
int reactionSystemCounter = 0;
for (int totalConcs=0; totalConcs<numSpeciesStatus/speciesSet.size(); ++totalConcs) {
LinkedHashMap speStat = new LinkedHashMap();
for (int totalSpecs=0; totalSpecs<speciesSet.size(); ++totalSpecs) {
SpeciesStatus ssCopy = (SpeciesStatus)speciesStatus.get(totalConcs+totalSpecs*numSpeciesStatus/speciesSet.size());
String blah = ssCopy.getSpecies().getName();
speStat.put(ssCopy.getSpecies(),new SpeciesStatus(ssCopy.getSpecies(),ssCopy.getSpeciesType(),ssCopy.getConcentration(),ssCopy.getFlux()));
}
initialStatusList.add(new InitialStatus(speStat,tm.getTemperature(initial),pm.getPressure(initial)));
}
}
}
return speciesSet;
}
public void populateInitialStatusListWithInertSpecies(BufferedReader reader) {
String line = ChemParser.readMeaningfulLine(reader, true);
while (!line.equals("END")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken().trim();
// The next token is the units of concentration
String unit = st.nextToken();
unit = ChemParser.removeBrace(unit);
// The remaining tokens are concentrations
double inertConc = 0.0;
int counter = 0;
int numberOfConcentrations = 0;
while (st.hasMoreTokens()) {
String conc = st.nextToken();
inertConc = Double.parseDouble(conc);
if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
inertConc /= 1000;
unit = "mol/cm3";
}
else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
inertConc /= 1000000;
unit = "mol/cm3";
}
else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
inertConc /= 6.022e23;
unit = "mol/cm3";
}
else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
throw new InvalidUnitException("Inert Gas Concentration not recognized: " + unit);
}
//SystemSnapshot.putInertGas(name,inertConc);
// for(Iterator iter=initialStatusList.iterator();iter.hasNext(); ){//6/23/09 gmagoon: needed to change this to accommodate non-static inertConc
// ((InitialStatus)iter.next()).putInertGas(name,inertConc);
// }
int numberOfDiffTP = tempList.size() * presList.size();
for (int isIndex=counter; isIndex<initialStatusList.size(); isIndex+=initialStatusList.size()/numberOfDiffTP) {
InitialStatus is = ((InitialStatus)initialStatusList.get(isIndex));
((InitialStatus)initialStatusList.get(isIndex)).putInertGas(name,inertConc);
}
++counter;
++numberOfConcentrations;
}
// Check if the number of concentrations read in is consistent with all previous
// concentration counts. The first time this function is called, the variable
// numberOfEquivalenceRatios will be initialized.
boolean goodToGo = areTheNumberOfConcentrationsConsistent(numberOfConcentrations);
if (!goodToGo) {
Logger.critical("\n\nThe number of concentrations (" + numberOfConcentrations + ") supplied for species " + name +
"\nis not consistent with the number of concentrations (" + numberOfEquivalenceRatios + ") " +
"supplied for all previously read-in species \n\n" +
"Terminating RMG simulation.");
System.exit(0);
}
line = ChemParser.readMeaningfulLine(reader, true);
}
}
public String readMaxAtomTypes(String line, BufferedReader reader) {
if (line.startsWith("MaxCarbonNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxCarbonNumberPerSpecies:"
int maxCNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxCarbonNumber(maxCNum);
Logger.info("Note: Overriding default MAX_CARBON_NUM with user-defined value: " + maxCNum);
line = ChemParser.readMeaningfulLine(reader, true);
}
if (line.startsWith("MaxOxygenNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxOxygenNumberPerSpecies:"
int maxONum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxOxygenNumber(maxONum);
Logger.info("Note: Overriding default MAX_OXYGEN_NUM with user-defined value: " + maxONum);
line = ChemParser.readMeaningfulLine(reader, true);
}
if (line.startsWith("MaxRadicalNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxRadicalNumberPerSpecies:"
int maxRadNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxRadicalNumber(maxRadNum);
Logger.info("Note: Overriding default MAX_RADICAL_NUM with user-defined value: " + maxRadNum);
line = ChemParser.readMeaningfulLine(reader, true);
}
if (line.startsWith("MaxSulfurNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxSulfurNumberPerSpecies:"
int maxSNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxSulfurNumber(maxSNum);
Logger.info("Note: Overriding default MAX_SULFUR_NUM with user-defined value: " + maxSNum);
line = ChemParser.readMeaningfulLine(reader, true);
}
if (line.startsWith("MaxSiliconNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxSiliconNumberPerSpecies:"
int maxSiNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxSiliconNumber(maxSiNum);
Logger.info("Note: Overriding default MAX_SILICON_NUM with user-defined value: " + maxSiNum);
line = ChemParser.readMeaningfulLine(reader, true);
}
if (line.startsWith("MaxHeavyAtom")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxHeavyAtomPerSpecies:"
int maxHANum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxHeavyAtomNumber(maxHANum);
Logger.info("Note: Overriding default MAX_HEAVYATOM_NUM with user-defined value: " + maxHANum);
line = ChemParser.readMeaningfulLine(reader, true);
}
if (line.startsWith("MaxCycleNumber")) {
StringTokenizer st = new StringTokenizer(line);
String dummyString = st.nextToken(); // This should hold "MaxCycleNumberPerSpecies:"
int maxCycleNum = Integer.parseInt(st.nextToken());
ChemGraph.setMaxCycleNumber(maxCycleNum);
Logger.info("Note: Overriding default MAX_CYCLE_NUM with user-defined value: " + maxCycleNum);
line = ChemParser.readMeaningfulLine(reader, true);
}
return line;
}
public ReactionModelEnlarger getReactionModelEnlarger() {
return reactionModelEnlarger;
}
public LinkedList getTempList() {
return tempList;
}
public LinkedList getPressList() {
return presList;
}
public LinkedList getInitialStatusList() {
return initialStatusList;
}
public void writeBackupRestartFiles(String[] listOfFiles) {
for (int i=0; i<listOfFiles.length; i++) {
File temporaryRestartFile = new File(listOfFiles[i]);
if (temporaryRestartFile.exists()) temporaryRestartFile.renameTo(new File(listOfFiles[i]+"~"));
}
}
public void removeBackupRestartFiles(String[] listOfFiles) {
for (int i=0; i<listOfFiles.length; i++) {
File temporaryRestartFile = new File(listOfFiles[i]+"~");
temporaryRestartFile.delete();
}
}
public static boolean rerunFameWithAdditionalGrains() {
return rerunFame;
}
public void setLimitingReactantID(int id) {
limitingReactantID = id;
}
public int getLimitingReactantID() {
return limitingReactantID;
}
public void readAndMakePTransL(BufferedReader reader) {
int numPTLs = 0;
String line = ChemParser.readMeaningfulLine(reader, true);
while (!line.equals("END")) {
String name = extractLibraryName(line);
line = ChemParser.readMeaningfulLine(reader, true);
String[] tempString = line.split("Location: ");
String path = tempString[tempString.length-1].trim();
if (numPTLs==0) {
setPrimaryTransportLibrary(new PrimaryTransportLibrary(name,path));
++numPTLs;
}
else {
getPrimaryTransportLibrary().appendPrimaryTransportLibrary(name,path);
++numPTLs;
}
line = ChemParser.readMeaningfulLine(reader, true);
}
if (numPTLs == 0) setPrimaryTransportLibrary(null);
}
//Added by Amrit Jalan on December 21, 2010
public void readAndMakePAL() {
String name = "primaryAbrahamLibrary";
String path = "primaryAbrahamLibrary";
setPrimaryAbrahamLibrary(new PrimaryAbrahamLibrary(name,path));
getPrimaryAbrahamLibrary().appendPrimaryAbrahamLibrary(name,path);
}
public void readAndMakeSL(String solventname) {
String name = "SolventLibrary";
String path = "SolventLibrary";
setSolventLibrary(new SolventLibrary(name,path)); // the constructor with (name,path) reads in the library at construction time.
SolventData solvent = getSolventLibrary().getSolventData(solventname);
setSolvent(solvent);
}
public PrimaryTransportLibrary getPrimaryTransportLibrary() {
return primaryTransportLibrary;
}
public void setPrimaryTransportLibrary(PrimaryTransportLibrary p_primaryTransportLibrary) {
primaryTransportLibrary = p_primaryTransportLibrary;
}
public PrimaryAbrahamLibrary getPrimaryAbrahamLibrary() {
return primaryAbrahamLibrary;
}
public static SolventData getSolvent() {
return solvent;
}
public static double getViscosity() {
return viscosity;
}
public SolventLibrary getSolventLibrary() {
return solventLibrary;
}
public void setPrimaryAbrahamLibrary(PrimaryAbrahamLibrary p_primaryAbrahamLibrary) {
primaryAbrahamLibrary = p_primaryAbrahamLibrary;
}
public void setSolventLibrary(SolventLibrary p_solventLibrary) {
solventLibrary = p_solventLibrary;
}
public void setSolvent(SolventData p_solvent) {
solvent = p_solvent;
}
/**
* Print the current numbers of core and edge species and reactions to the
* console.
*/
public void printModelSize() {
CoreEdgeReactionModel cerm = (CoreEdgeReactionModel) getReactionModel();
int numberOfCoreSpecies = cerm.getReactedSpeciesSet().size();
int numberOfEdgeSpecies = cerm.getUnreactedSpeciesSet().size();
int numberOfCoreReactions = 0;
int numberOfEdgeReactions = 0;
double count = 0.0;
for (Iterator iter = cerm.getReactedReactionSet().iterator(); iter.hasNext(); ) {
Reaction rxn = (Reaction) iter.next();
// The model core stores reactions in both directions
// To avoid double-counting we must count each of these as 1/2
if (rxn.hasReverseReaction()) count += 0.5;
else count += 1;
}
numberOfCoreReactions = (int) Math.round(count);
count = 0.0;
for (Iterator iter = cerm.getUnreactedReactionSet().iterator(); iter.hasNext(); ) {
Reaction rxn = (Reaction) iter.next();
// The model edge stores reactions in only one direction, so each
// edge reaction counts as 1
count += 1;
}
numberOfEdgeReactions = (int) Math.round(count);
if (reactionModelEnlarger instanceof RateBasedPDepRME) {
numberOfCoreReactions += PDepNetwork.getNumCoreReactions(cerm);
numberOfEdgeReactions += PDepNetwork.getNumEdgeReactions(cerm);
}
Logger.info("");
Logger.info("The model core has " + Integer.toString(numberOfCoreReactions) + " reactions and "+ Integer.toString(numberOfCoreSpecies) + " species.");
Logger.info("The model edge has " + Integer.toString(numberOfEdgeReactions) + " reactions and "+ Integer.toString(numberOfEdgeSpecies) + " species.");
// If pressure dependence is on, print some information about the networks
if (reactionModelEnlarger instanceof RateBasedPDepRME) {
int numberOfNetworks = PDepNetwork.getNetworks().size();
int numberOfPathReactions = PDepNetwork.getNumPathReactions(cerm);
int numberOfNetReactions = PDepNetwork.getNumNetReactions(cerm);
Logger.info("There are " + Integer.toString(numberOfNetworks) + " partial pressure-dependent networks containing " + Integer.toString(numberOfPathReactions) + " path and " + Integer.toString(numberOfNetReactions) + " net reactions.");
}
}
public boolean areTheNumberOfConcentrationsConsistent(int number) {
if (numberOfEquivalenceRatios == 0) numberOfEquivalenceRatios = number;
else {
if (number == numberOfEquivalenceRatios) return true;
else return false;
}
return true;
}
public static void addChemGraphToListIfNotPresent_ElseTerminate(LinkedHashMap speciesMap, ChemGraph cg, String name) {
if (speciesMap.containsKey(cg)) {
Logger.error("The same ChemGraph appears multiple times in the user-specified input file\n" +
"Species " + name + " has the same ChemGraph as " +
(speciesMap.get(cg)));
System.exit(0);
} else
speciesMap.put(cg, name);
}
public String extractLibraryName(String line) {
String[] tempString = line.split("Name: ");
String name = tempString[tempString.length-1].trim();
if (name.contains("//")) {
tempString = line.split("//");
name = tempString[0].trim();
}
return name;
}
}
/*********************************************************************
File Path : RMG\RMG\jing\rxnSys\ReactionModelGenerator.java
*********************************************************************/
| false | true | public void initializeReactionSystems() throws InvalidSymbolException, IOException {
//#[ operation initializeReactionSystem()
try {
String initialConditionFile = System.getProperty("jing.rxnSys.ReactionModelGenerator.conditionFile");
if (initialConditionFile == null) {
Logger.critical("undefined system property: jing.rxnSys.ReactionModelGenerator.conditionFile");
System.exit(0);
}
//double sandeep = getCpuTime();
//System.out.println(getCpuTime()/1e9/60);
FileReader in = new FileReader(initialConditionFile);
BufferedReader reader = new BufferedReader(in);
//TemperatureModel temperatureModel = null;//10/27/07 gmagoon: commented out
//PressureModel pressureModel = null;//10/27/07 gmagoon: commented out
// ReactionModelEnlarger reactionModelEnlarger = null;//10/9/07 gmagoon: commented out: unneeded now and causes scope problems
FinishController finishController = null;
//DynamicSimulator dynamicSimulator = null;//10/27/07 gmagoon: commented out and replaced with following line
LinkedList dynamicSimulatorList = new LinkedList();
setPrimaryKineticLibrary(null);//10/14/07 gmagoon: changed to use setPrimaryReactionLibrary
double [] conversionSet = new double[50];
String line = ChemParser.readMeaningfulLine(reader, true);
/*if (line.startsWith("Restart")){
StringTokenizer st = new StringTokenizer(line);
String token = st.nextToken();
token = st.nextToken();
if (token.equalsIgnoreCase("true")) {
//Runtime.getRuntime().exec("cp Restart/allSpecies.txt Restart/allSpecies1.txt");
//Runtime.getRuntime().exec("echo >> allSpecies.txt");
restart = true;
}
else if (token.equalsIgnoreCase("false")) {
Runtime.getRuntime().exec("rm Restart/allSpecies.txt");
restart = false;
}
else throw new InvalidSymbolException("UnIdentified Symbol "+token+" after Restart:");
}
else throw new InvalidSymbolException("Can't find Restart!");*/
//line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Database")){//svp
line = ChemParser.readMeaningfulLine(reader, true);
}
else throw new InvalidSymbolException("Can't find database!");
// if (line.startsWith("PrimaryThermoLibrary")){//svp
// line = ChemParser.readMeaningfulLine(reader);
// }
// else throw new InvalidSymbolException("Can't find primary thermo library!");
/*
* Added by MRH on 15-Jun-2009
* Give user the option to change the maximum carbon, oxygen,
* and/or radical number for all species. These lines will be
* optional in the condition.txt file. Values are hard-
* coded into RMG (in ChemGraph.java), but any user-
* defined input will override these values.
*/
/*
* Moved from before InitialStatus to before PrimaryThermoLibary
* by MRH on 27-Oct-2009
* Overriding default values of maximum number of "X" per
* chemgraph should come before RMG attempts to make any
* chemgraph. The first instance RMG will attempt to make a
* chemgraph is in reading the primary thermo library.
*/
line = readMaxAtomTypes(line,reader);
// if (line.startsWith("MaxCarbonNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxCarbonNumberPerSpecies:"
// int maxCNum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxCarbonNumber(maxCNum);
// System.out.println("Note: Overriding RMG-defined MAX_CARBON_NUM with user-defined value: " + maxCNum);
// line = ChemParser.readMeaningfulLine(reader);
// }
// if (line.startsWith("MaxOxygenNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxOxygenNumberPerSpecies:"
// int maxONum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxOxygenNumber(maxONum);
// System.out.println("Note: Overriding RMG-defined MAX_OXYGEN_NUM with user-defined value: " + maxONum);
// line = ChemParser.readMeaningfulLine(reader);
// }
// if (line.startsWith("MaxRadicalNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxRadicalNumberPerSpecies:"
// int maxRadNum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxRadicalNumber(maxRadNum);
// System.out.println("Note: Overriding RMG-defined MAX_RADICAL_NUM with user-defined value: " + maxRadNum);
// line = ChemParser.readMeaningfulLine(reader);
// }
// if (line.startsWith("MaxSulfurNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxSulfurNumberPerSpecies:"
// int maxSNum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxSulfurNumber(maxSNum);
// System.out.println("Note: Overriding RMG-defined MAX_SULFUR_NUM with user-defined value: " + maxSNum);
// line = ChemParser.readMeaningfulLine(reader);
// }
// if (line.startsWith("MaxSiliconNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxSiliconNumberPerSpecies:"
// int maxSiNum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxSiliconNumber(maxSiNum);
// System.out.println("Note: Overriding RMG-defined MAX_SILICON_NUM with user-defined value: " + maxSiNum);
// line = ChemParser.readMeaningfulLine(reader);
// }
// if (line.startsWith("MaxHeavyAtom")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxHeavyAtomPerSpecies:"
// int maxHANum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxHeavyAtomNumber(maxHANum);
// System.out.println("Note: Overriding RMG-defined MAX_HEAVYATOM_NUM with user-defined value: " + maxHANum);
// line = ChemParser.readMeaningfulLine(reader);
// }
/*
* Read in the Primary Thermo Library
* MRH 7-Jul-2009
*/
if (line.startsWith("PrimaryThermoLibrary:")) {
/*
* MRH 27Feb2010:
* Changing the "read in Primary Thermo Library information" code
* into it's own method.
*
* Other modules (e.g. PopulateReactions) will be utilizing the exact code.
* Rather than copying and pasting code into other modules, just have
* everything call this new method: readAndMakePTL
*/
readAndMakePTL(reader);
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate PrimaryThermoLibrary field");
line = ChemParser.readMeaningfulLine(reader, true);
/*
* MRH 17-May-2010:
* Added primary transport library field
*/
if (line.toLowerCase().startsWith("primarytransportlibrary")) {
readAndMakePTransL(reader);
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate PrimaryTransportLibrary field.");
line = ChemParser.readMeaningfulLine(reader, true);
// Extra forbidden structures may be specified after the Primary Thermo Library
if (line.startsWith("ForbiddenStructures:")) {
readExtraForbiddenStructures(reader);
line = ChemParser.readMeaningfulLine(reader, true);
}
if (line.toLowerCase().startsWith("readrestart")) {
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken(); // "ReadRestart:"
tempString = st.nextToken();
if (tempString.toLowerCase().equals("yes")) {
readrestart = true;
readRestartSpecies();
readRestartReactions();
} else readrestart = false;
line = ChemParser.readMeaningfulLine(reader, true);
} else throw new InvalidSymbolException("Cannot locate ReadRestart field");
if (line.toLowerCase().startsWith("writerestart")) {
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken(); // "WriteRestart:"
tempString = st.nextToken();
if (tempString.toLowerCase().equals("yes"))
writerestart = true;
else writerestart = false;
line = ChemParser.readMeaningfulLine(reader, true);
} else throw new InvalidSymbolException("Cannot locate WriteRestart field");
// read temperature model
//gmagoon 10/23/07: modified to handle multiple temperatures; note that this requires different formatting of units in condition.txt
if (line.startsWith("TemperatureModel:")) {
createTModel(line);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String modelType = st.nextToken();
// //String t = st.nextToken();
// String unit = st.nextToken();
// unit = ChemParser.removeBrace(unit);
// if (modelType.equals("Constant")) {
// tempList = new LinkedList();
// //read first temperature
// double t = Double.parseDouble(st.nextToken());
// tempList.add(new ConstantTM(t, unit));
// Temperature temp = new Temperature(t, unit);//10/29/07 gmagoon: added this line and next two lines to set Global.lowTemperature and Global.highTemperature
// Global.lowTemperature = (Temperature)temp.clone();
// Global.highTemperature = (Temperature)temp.clone();
// //read remaining temperatures
// while (st.hasMoreTokens()) {
// t = Double.parseDouble(st.nextToken());
// tempList.add(new ConstantTM(t, unit));
// temp = new Temperature(t,unit);//10/29/07 gmagoon: added this line and next two "if" statements to set Global.lowTemperature and Global.highTemperature
// if(temp.getK() < Global.lowTemperature.getK())
// Global.lowTemperature = (Temperature)temp.clone();
// if(temp.getK() > Global.highTemperature.getK())
// Global.highTemperature = (Temperature)temp.clone();
// }
// // Global.temperature = new Temperature(t,unit);
// }
//10/23/07 gmagoon: commenting out; further updates needed to get this to work
//else if (modelType.equals("Curved")) {
// String t = st.nextToken();
// // add reading curved temperature function here
// temperatureModel = new CurvedTM(new LinkedList());
//}
// else {
// throw new InvalidSymbolException("condition.txt: Unknown TemperatureModel = " + modelType);
// }
}
else throw new InvalidSymbolException("condition.txt: can't find TemperatureModel!");
// read in pressure model
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("PressureModel:")) {
createPModel(line);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String modelType = st.nextToken();
// //String p = st.nextToken();
// String unit = st.nextToken();
// unit = ChemParser.removeBrace(unit);
// if (modelType.equals("Constant")) {
// presList = new LinkedList();
// //read first pressure
// double p = Double.parseDouble(st.nextToken());
// Pressure pres = new Pressure(p, unit);
// Global.lowPressure = (Pressure)pres.clone();
// Global.highPressure = (Pressure)pres.clone();
// presList.add(new ConstantPM(p, unit));
// //read remaining temperatures
// while (st.hasMoreTokens()) {
// p = Double.parseDouble(st.nextToken());
// presList.add(new ConstantPM(p, unit));
// pres = new Pressure(p, unit);
// if(pres.getBar() < Global.lowPressure.getBar())
// Global.lowPressure = (Pressure)pres.clone();
// if(pres.getBar() > Global.lowPressure.getBar())
// Global.highPressure = (Pressure)pres.clone();
// }
// //Global.pressure = new Pressure(p, unit);
// }
// //10/23/07 gmagoon: commenting out; further updates needed to get this to work
// //else if (modelType.equals("Curved")) {
// // // add reading curved pressure function here
// // pressureModel = new CurvedPM(new LinkedList());
// //}
// else {
// throw new InvalidSymbolException("condition.txt: Unknown PressureModel = " + modelType);
// }
}
else throw new InvalidSymbolException("condition.txt: can't find PressureModel!");
// after PressureModel comes an optional line EquationOfState
// if "EquationOfState: Liquid" is found then initial concentrations are assumed to be correct
// if it is ommited, then initial concentrations are normalised to ensure PV=NRT (ideal gas law)
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("EquationOfState")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String eosType = st.nextToken().toLowerCase();
if (eosType.equals("liquid")) {
equationOfState="Liquid";
Logger.info("Equation of state: Liquid. Relying on concentrations in input file to get density correct; not checking PV=NRT");
}
line = ChemParser.readMeaningfulLine(reader, true);
}
// Read in InChI generation
if (line.startsWith("InChIGeneration:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String inchiOnOff = st.nextToken().toLowerCase();
if (inchiOnOff.equals("on")) {
Species.useInChI = true;
} else if (inchiOnOff.equals("off")) {
Species.useInChI = false;
}
else throw new InvalidSymbolException("condition.txt: Unknown InChIGeneration flag: " + inchiOnOff);
line = ChemParser.readMeaningfulLine(reader, true);
}
// Read in Solvation effects
if (line.startsWith("Solvation:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String solvationOnOff = st.nextToken().toLowerCase();
if (solvationOnOff.equals("on")) {
setUseSolvation(true);
Species.useSolvation = true;
readAndMakePAL();
String solventname = st.nextToken().toLowerCase();
readAndMakeSL(solventname);
Logger.info(String.format(
"Using solvation corrections to thermochemsitry with solvent properties of %s",solventname));
} else if (solvationOnOff.startsWith("off")) {
setUseSolvation(false);
Species.useSolvation = false;
}
else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff);
line = ChemParser.readMeaningfulLine(reader, true);
}
// Read in Diffusion effects
// If 'Diffusion' is 'on' then override the settings made by the solvation flag and sets solvation 'on'
if (line.startsWith("Diffusion:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String diffusionOnOff = st.nextToken().toLowerCase();
if (diffusionOnOff.equals("on")) {
String viscosity_str = st.nextToken();
viscosity = Double.parseDouble(viscosity_str);
setUseDiffusion(true);
Logger.info(String.format(
"Using diffusion corrections to kinetics with solvent viscosity of %.3g Pa.s.",viscosity));
} else if (diffusionOnOff.equals("off")) {
setUseDiffusion(false);
}
else throw new InvalidSymbolException("condition.txt: Unknown diffusion flag: " + diffusionOnOff);
line = ChemParser.readMeaningfulLine(reader,true);//read in reactants or thermo line
}
/* AJ 12JULY2010:
* Right now we do not want RMG to throw an exception if it cannot find a diffusion flag
*/
//else throw new InvalidSymbolException("condition.txt: Cannot find diffusion flag.");
// Should have already read in reactants or thermo line into variable 'line'
// Read in optional QM thermo generation
if (line.startsWith("ThermoMethod:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String thermoMethod = st.nextToken().toLowerCase();
if (thermoMethod.equals("qm")) {
ChemGraph.useQM = true;
if(st.hasMoreTokens()){//override the default qmprogram ("both") if there are more; current options: "gaussian03" and "mopac" and of course, "both"
QMTP.qmprogram = st.nextToken().toLowerCase();
}
line=ChemParser.readMeaningfulLine(reader, true);
if(line.startsWith("QMForCyclicsOnly:")){
StringTokenizer st2 = new StringTokenizer(line);
String nameCyc = st2.nextToken();
String option = st2.nextToken().toLowerCase();
if (option.equals("on")) {
ChemGraph.useQMonCyclicsOnly = true;
}
}
else{
Logger.critical("condition.txt: Can't find 'QMForCyclicsOnly:' field");
System.exit(0);
}
line=ChemParser.readMeaningfulLine(reader, true);
if(line.startsWith("MaxRadNumForQM:")){
StringTokenizer st3 = new StringTokenizer(line);
String nameRadNum = st3.nextToken();
Global.maxRadNumForQM = Integer.parseInt(st3.nextToken());
}
else{
Logger.critical("condition.txt: Can't find 'MaxRadNumForQM:' field");
System.exit(0);
}
}//otherwise, the flag useQM will remain false by default and the traditional group additivity approach will be used
line = ChemParser.readMeaningfulLine(reader, true);//read in reactants
}
// // Read in Solvation effects
// if (line.startsWith("Solvation:")) {
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String solvationOnOff = st.nextToken().toLowerCase();
// if (solvationOnOff.equals("on")) {
// Species.useSolvation = true;
// } else if (solvationOnOff.equals("off")) {
// Species.useSolvation = false;
// }
// else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff);
// }
// else throw new InvalidSymbolException("condition.txt: Cannot find solvation flag.");
// read in reactants
//
//10/4/07 gmagoon: moved to initializeCoreEdgeReactionModel
//LinkedHashSet p_speciesSeed = new LinkedHashSet();//gmagoon 10/4/07: changed to p_speciesSeed
//setSpeciesSeed(p_speciesSeed);//gmagoon 10/4/07: added
LinkedHashMap speciesSet = new LinkedHashMap();
/*
* 7/Apr/2010: MRH
* Neither of these variables are utilized
*/
// LinkedHashMap speciesStatus = new LinkedHashMap();
// int speciesnum = 1;
//System.out.println(line);
if (line.startsWith("InitialStatus")) {
speciesSet = populateInitialStatusListWithReactiveSpecies(reader);
// line = ChemParser.readMeaningfulLine(reader);
// while (!line.equals("END")) {
// StringTokenizer st = new StringTokenizer(line);
// String index = st.nextToken();
// String name = null;
// if (!index.startsWith("(")) name = index;
// else name = st.nextToken();
// //if (restart) name += "("+speciesnum+")";
// // 24Jun2009: MRH
// // Check if the species name begins with a number.
// // If so, terminate the program and inform the user to choose
// // a different name. This is implemented so that the chem.inp
// // file generated will be valid when run in Chemkin
// try {
// int doesNameBeginWithNumber = Integer.parseInt(name.substring(0,1));
// System.out.println("\nA species name should not begin with a number." +
// " Please rename species: " + name + "\n");
// System.exit(0);
// } catch (NumberFormatException e) {
// // We're good
// }
// speciesnum ++;
// if (!(st.hasMoreTokens())) throw new InvalidSymbolException("Couldn't find concentration of species: "+name);
// String conc = st.nextToken();
// double concentration = Double.parseDouble(conc);
// String unit = st.nextToken();
// unit = ChemParser.removeBrace(unit);
// if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
// concentration /= 1000;
// unit = "mol/cm3";
// }
// else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
// concentration /= 1000000;
// unit = "mol/cm3";
// }
// else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
// concentration /= 6.022e23;
// }
// else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
// throw new InvalidUnitException("Species Concentration in condition.txt!");
// }
//
// //GJB to allow "unreactive" species that only follow user-defined library reactions.
// // They will not react according to RMG reaction families
// boolean IsReactive = true;
// boolean IsConstantConcentration = false;
// while (st.hasMoreTokens()) {
// String reactive = st.nextToken().trim();
// if (reactive.equalsIgnoreCase("unreactive"))
// IsReactive = false;
// if (reactive.equalsIgnoreCase("constantconcentration"))
// IsConstantConcentration=true;
// }
//
// Graph g = ChemParser.readChemGraph(reader);
// ChemGraph cg = null;
// try {
// cg = ChemGraph.make(g);
// }
// catch (ForbiddenStructureException e) {
// System.out.println("Forbidden Structure:\n" + e.getMessage());
// throw new InvalidSymbolException("A species in the input file has a forbidden structure.");
// }
// //System.out.println(name);
// Species species = Species.make(name,cg);
// species.setReactivity(IsReactive); // GJB
// species.setConstantConcentration(IsConstantConcentration);
// speciesSet.put(name, species);
// getSpeciesSeed().add(species);
// double flux = 0;
// int species_type = 1; // reacted species
// SpeciesStatus ss = new SpeciesStatus(species,species_type,concentration,flux);
// speciesStatus.put(species, ss);
// line = ChemParser.readMeaningfulLine(reader);
// }
// ReactionTime initial = new ReactionTime(0,"S");
// //10/23/07 gmagoon: modified for handling multiple temperature, pressure conditions; note: concentration within speciesStatus (and list of conversion values) should not need to be modified for each T,P since this is done within isTPCconsistent in ReactionSystem
// initialStatusList = new LinkedList();
// for (Iterator iter = tempList.iterator(); iter.hasNext(); ) {
// TemperatureModel tm = (TemperatureModel)iter.next();
// for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){
// PressureModel pm = (PressureModel)iter2.next();
// // LinkedHashMap speStat = (LinkedHashMap)speciesStatus.clone();//10/31/07 gmagoon: trying creating multiple instances of speciesStatus to address issues with concentration normalization (last normalization seems to apply to all)
// Set ks = speciesStatus.keySet();
// LinkedHashMap speStat = new LinkedHashMap();
// for (Iterator iter3 = ks.iterator(); iter3.hasNext();){//11/1/07 gmagoon: perform deep copy; (is there an easier or more elegant way to do this?)
// SpeciesStatus ssCopy = (SpeciesStatus)speciesStatus.get(iter3.next());
// speStat.put(ssCopy.getSpecies(),new SpeciesStatus(ssCopy.getSpecies(),ssCopy.getSpeciesType(),ssCopy.getConcentration(),ssCopy.getFlux()));
// }
// initialStatusList.add(new InitialStatus(speStat,tm.getTemperature(initial),pm.getPressure(initial)));
// }
// }
}
else throw new InvalidSymbolException("condition.txt: can't find InitialStatus!");
// read in inert gas concentration
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("InertGas:")) {
populateInitialStatusListWithInertSpecies(reader);
// line = ChemParser.readMeaningfulLine(reader);
// while (!line.equals("END")) {
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken().trim();
// String conc = st.nextToken();
// double inertConc = Double.parseDouble(conc);
// String unit = st.nextToken();
// unit = ChemParser.removeBrace(unit);
// if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
// inertConc /= 1000;
// unit = "mol/cm3";
// }
// else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
// inertConc /= 1000000;
// unit = "mol/cm3";
// }
// else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
// inertConc /= 6.022e23;
// unit = "mol/cm3";
// }
// else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
// throw new InvalidUnitException("Inert Gas Concentration not recognized: " + unit);
// }
//
// //SystemSnapshot.putInertGas(name,inertConc);
// for(Iterator iter=initialStatusList.iterator();iter.hasNext(); ){//6/23/09 gmagoon: needed to change this to accommodate non-static inertConc
// ((InitialStatus)iter.next()).putInertGas(name,inertConc);
// }
// line = ChemParser.readMeaningfulLine(reader);
// }
}
else throw new InvalidSymbolException("condition.txt: can't find Inert gas concentration!");
// read in spectroscopic data estimator
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("SpectroscopicDataEstimator:")) {
setSpectroscopicDataMode(line);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String sdeType = st.nextToken().toLowerCase();
// if (sdeType.equals("frequencygroups") || sdeType.equals("default")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
// }
// else if (sdeType.equals("therfit") || sdeType.equals("threefrequencymodel")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY;
// }
// else if (sdeType.equals("off") || sdeType.equals("none")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.OFF;
// }
// else throw new InvalidSymbolException("condition.txt: Unknown SpectroscopicDataEstimator = " + sdeType);
}
else throw new InvalidSymbolException("condition.txt: can't find SpectroscopicDataEstimator!");
// pressure dependence and related flags
line = ChemParser.readMeaningfulLine(reader, true);
if (line.toLowerCase().startsWith("pressuredependence:"))
line = setPressureDependenceOptions(line,reader);
else
throw new InvalidSymbolException("condition.txt: can't find PressureDependence flag!");
if (readrestart) if (PDepNetwork.generateNetworks) readPDepNetworks();
// include species (optional)
/*
*
* MRH 3-APR-2010:
* This if statement is no longer necessary and was causing an error
* when the PressureDependence field was set to "off"
*/
// if (!PDepRateConstant.getMode().name().equals("CHEBYSHEV") &&
// !PDepRateConstant.getMode().name().equals("PDEPARRHENIUS"))
// line = ChemParser.readMeaningfulLine(reader);
// read in finish controller
if (line.startsWith("FinishController")) {
line = ChemParser.readMeaningfulLine(reader, true);
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String goal = st.nextToken();
String type = st.nextToken();
TerminationTester tt;
if (type.startsWith("Conversion")) {
LinkedList spc = new LinkedList();
while (st.hasMoreTokens()) {
String name = st.nextToken();
Species spe = (Species)speciesSet.get(name);
if (spe == null) throw new InvalidConversionException("Unknown reactant in 'Goal Conversion' field of input file : " + name);
setLimitingReactantID(spe.getID());
String conv = st.nextToken();
double conversion;
try {
if (conv.endsWith("%")) {
conversion = Double.parseDouble(conv.substring(0,conv.length()-1))/100;
}
else {
conversion = Double.parseDouble(conv);
}
conversionSet[49] = conversion;
}
catch (NumberFormatException e) {
throw new NumberFormatException("wrong number format for conversion in initial condition file!");
}
SpeciesConversion sc = new SpeciesConversion(spe, conversion);
spc.add(sc);
}
tt = new ConversionTT(spc);
}
else if (type.startsWith("ReactionTime")) {
double time = Double.parseDouble(st.nextToken());
String unit = ChemParser.removeBrace(st.nextToken());
ReactionTime rt = new ReactionTime(time, unit);
tt = new ReactionTimeTT(rt);
}
else {
throw new InvalidSymbolException("condition.txt: Unknown FinishController = " + type);
}
line = ChemParser.readMeaningfulLine(reader, true);
st = new StringTokenizer(line, ":");
String temp = st.nextToken();
String tol = st.nextToken();
try {
if (tol.endsWith("%")) {
tolerance = Double.parseDouble(tol.substring(0,tol.length()-1))/100;
}
else {
tolerance = Double.parseDouble(tol);
}
}
catch (NumberFormatException e) {
throw new NumberFormatException("wrong number format for conversion in initial condition file!");
}
ValidityTester vt = null;
if (reactionModelEnlarger instanceof RateBasedRME) vt = new RateBasedVT(tolerance);
else if (reactionModelEnlarger instanceof RateBasedPDepRME) vt = new RateBasedPDepVT(tolerance);
else throw new InvalidReactionModelEnlargerException();
finishController = new FinishController(tt, vt);
}
else throw new InvalidSymbolException("condition.txt: can't find FinishController!");
// read in dynamic simulator
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("DynamicSimulator")) {
StringTokenizer st = new StringTokenizer(line,":");
String temp = st.nextToken();
String simulator = st.nextToken().trim();
//read in non-negative option if it exists: syntax would be something like this: "DynamicSimulator: DASSL: non-negative"
if (st.hasMoreTokens()){
if (st.nextToken().trim().toLowerCase().equals("non-negative")){
if(simulator.toLowerCase().equals("dassl")) JDAS.nonnegative = true;
else{
Logger.critical("Non-negative option is currently only supported for DASSL. Switch to DASSL solver or remove non-negative option.");
System.exit(0);
}
}
}
numConversions = 0;//5/6/08 gmagoon: moved declaration from initializeReactionSystem() to be an attribute so it can be accessed by modelGenerator()
//int numConversions = 0;
boolean autoflag = false;//5/2/08 gmagoon: updating the following if/else-if block to consider input where we want to check model validity within the ODE solver at each time step; this will be indicated by the use of a string beginning with "AUTO" after the "TimeStep" or "Conversions" line
// read in time step
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("TimeStep:") && finishController.terminationTester instanceof ReactionTimeTT) {
st = new StringTokenizer(line);
temp = st.nextToken();
while (st.hasMoreTokens()) {
temp = st.nextToken();
if (temp.startsWith("AUTO")){//note potential opportunity for making case insensitive by using: temp.toUpperCase().startsWith("AUTO")
autoflag=true;
}
else if (!autoflag){//use "else if" to make sure additional numbers are not read in case numbers are erroneously used following AUTO; note that there could still be a problem if numbers come before "AUTO"
double tStep = Double.parseDouble(temp);
String unit = "sec";
setTimeStep(new ReactionTime(tStep, unit));
}
}
((ReactionTimeTT)finishController.terminationTester).setTimeSteps(timeStep);
}
else if (line.startsWith("Conversions:") && finishController.terminationTester instanceof ConversionTT){
st = new StringTokenizer(line);
temp = st.nextToken();
int i=0;
SpeciesConversion sc = (SpeciesConversion)((ConversionTT)finishController.terminationTester).speciesGoalConversionSet.get(0);
Species convSpecies = sc.species;
Iterator iter = ((InitialStatus)(initialStatusList.get(0))).getSpeciesStatus();//10/23/07 gmagoon: changed to use first element of initialStatusList, as subsequent operations should not be affected by which one is chosen
double initialConc = 0;
while (iter.hasNext()){
SpeciesStatus sps = (SpeciesStatus)iter.next();
if (sps.species.equals(convSpecies)) initialConc = sps.concentration;
}
while (st.hasMoreTokens()){
temp=st.nextToken();
if (temp.startsWith("AUTO")){
autoflag=true;
}
else if (!autoflag){
double conv = Double.parseDouble(temp);
conversionSet[i] = (1-conv) * initialConc;
i++;
}
}
conversionSet[i] = (1 - conversionSet[49])* initialConc;
numConversions = i+1;
}
else throw new InvalidSymbolException("condition.txt: can't find time step for dynamic simulator!");
//
if (temp.startsWith("AUTOPRUNE")){//for the AUTOPRUNE case, read in additional lines for termTol and edgeTol
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("TerminationTolerance:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
termTol = Double.parseDouble(st.nextToken());
}
else {
Logger.critical("Cannot find TerminationTolerance in condition.txt");
System.exit(0);
}
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("PruningTolerance:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
edgeTol = Double.parseDouble(st.nextToken());
}
else {
Logger.critical("Cannot find PruningTolerance in condition.txt");
System.exit(0);
}
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("MinSpeciesForPruning:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
minSpeciesForPruning = Integer.parseInt(st.nextToken());
}
else {
Logger.critical("Cannot find MinSpeciesForPruning in condition.txt");
System.exit(0);
}
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("MaxEdgeSpeciesAfterPruning:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
maxEdgeSpeciesAfterPruning = Integer.parseInt(st.nextToken());
}
else {
Logger.critical("Cannot find MaxEdgeSpeciesAfterPruning in condition.txt");
System.exit(0);
}
//print header for pruning log (based on restart format)
BufferedWriter bw = null;
try {
File f = new File("Pruning/edgeReactions.txt");
bw = new BufferedWriter(new FileWriter("Pruning/edgeReactions.txt", true));
String EaUnits = ArrheniusKinetics.getEaUnits();
bw.write("UnitsOfEa: " + EaUnits);
bw.newLine();
} catch (FileNotFoundException ex) {
Logger.logStackTrace(ex);
} catch (IOException ex) {
Logger.logStackTrace(ex);
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
Logger.logStackTrace(ex);
}
}
}
else if (temp.startsWith("AUTO")){//in the non-autoprune case (i.e. original AUTO functionality), we set the new parameters to values that should reproduce original functionality
termTol = tolerance;
edgeTol = 0;
minSpeciesForPruning = 999999;//arbitrary high number (actually, the value here should not matter, since pruning should not be done)
maxEdgeSpeciesAfterPruning = 999999;
}
// read in atol
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Atol:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
atol = Double.parseDouble(st.nextToken());
}
else throw new InvalidSymbolException("condition.txt: can't find Atol for dynamic simulator!");
// read in rtol
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Rtol:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
String rel_tol = st.nextToken();
if (rel_tol.endsWith("%"))
rtol = Double.parseDouble(rel_tol.substring(0,rel_tol.length()-1));
else
rtol = Double.parseDouble(rel_tol);
}
else throw new InvalidSymbolException("condition.txt: can't find Rtol for dynamic simulator!");
if (simulator.equals("DASPK")) {
paraInfor = 0;//svp
// read in SA
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Error bars")) {//svp
st = new StringTokenizer(line,":");
temp = st.nextToken();
String sa = st.nextToken().trim();
if (sa.compareToIgnoreCase("on")==0) {
paraInfor = 1;
error = true;
}
else if (sa.compareToIgnoreCase("off")==0) {
paraInfor = 0;
error = false;
}
else throw new InvalidSymbolException("condition.txt: can't find error on/off information!");
}
else throw new InvalidSymbolException("condition.txt: can't find SA information!");
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Display sensitivity coefficients")){//svp
st = new StringTokenizer(line,":");
temp = st.nextToken();
String sa = st.nextToken().trim();
if (sa.compareToIgnoreCase("on")==0){
paraInfor = 1;
sensitivity = true;
}
else if (sa.compareToIgnoreCase("off")==0){
if (paraInfor != 1){
paraInfor = 0;
}
sensitivity = false;
}
else throw new InvalidSymbolException("condition.txt: can't find SA on/off information!");
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
//6/25/08 gmagoon: changed loop to use i index, and updated DASPK constructor to pass i (mirroring changes to DASSL
//6/25/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null?
for (int i = 0;i < initialStatusList.size();i++) {
dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i,finishController.getValidityTester(), autoflag, termTol, tolerance));
}
}
species = new LinkedList();
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Display sensitivity information") ){
line = ChemParser.readMeaningfulLine(reader, true);
Logger.info(line);
while (!line.equals("END")){
st = new StringTokenizer(line);
String name = st.nextToken();
if (name.toUpperCase().equals("ALL")) ReactionSystem.printAllSens = true; //gmagoon 12/22/09: if the line contains the word "all", turn on the flag to print out sensitivity information for everything
species.add(name);
line = ChemParser.readMeaningfulLine(reader, true);
}
}
}
else if (simulator.equals("DASSL")) {
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
// for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) {
// dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)iter.next()));
// }
//11/1/07 gmagoon: changed loop to use i index, and updated DASSL constructor to pass i
//5/5/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null?
for (int i = 0;i < initialStatusList.size();i++) {
dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i, finishController.getValidityTester(), autoflag, termTol, tolerance));
}
}
else if (simulator.equals("Chemkin")) {
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("ReactorType")) {
st = new StringTokenizer(line, ":");
temp = st.nextToken();
String reactorType = st.nextToken().trim();
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) {
//dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)iter.next()));
dynamicSimulatorList.add(new Chemkin(rtol, atol, reactorType));//11/4/07 gmagoon: fixing apparent cut/paste error
}
}
}
else throw new InvalidSymbolException("condition.txt: Unknown DynamicSimulator = " + simulator);
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList; note: although conversionSet should actually be different for each T,P condition, it will be modified in isTPCconsistent within ReactionSystem
for (Iterator iter = dynamicSimulatorList.iterator(); iter.hasNext(); ) {
double [] cs = conversionSet.clone();//11/1/07 gmagoon: trying to make sure multiple instances of conversionSet are used
((DynamicSimulator)(iter.next())).addConversion(cs, numConversions);
}
}
| public void initializeReactionSystems() throws InvalidSymbolException, IOException {
//#[ operation initializeReactionSystem()
try {
String initialConditionFile = System.getProperty("jing.rxnSys.ReactionModelGenerator.conditionFile");
if (initialConditionFile == null) {
Logger.critical("undefined system property: jing.rxnSys.ReactionModelGenerator.conditionFile");
System.exit(0);
}
//double sandeep = getCpuTime();
//System.out.println(getCpuTime()/1e9/60);
FileReader in = new FileReader(initialConditionFile);
BufferedReader reader = new BufferedReader(in);
//TemperatureModel temperatureModel = null;//10/27/07 gmagoon: commented out
//PressureModel pressureModel = null;//10/27/07 gmagoon: commented out
// ReactionModelEnlarger reactionModelEnlarger = null;//10/9/07 gmagoon: commented out: unneeded now and causes scope problems
FinishController finishController = null;
//DynamicSimulator dynamicSimulator = null;//10/27/07 gmagoon: commented out and replaced with following line
LinkedList dynamicSimulatorList = new LinkedList();
setPrimaryKineticLibrary(null);//10/14/07 gmagoon: changed to use setPrimaryReactionLibrary
double [] conversionSet = new double[50];
String line = ChemParser.readMeaningfulLine(reader, true);
/*if (line.startsWith("Restart")){
StringTokenizer st = new StringTokenizer(line);
String token = st.nextToken();
token = st.nextToken();
if (token.equalsIgnoreCase("true")) {
//Runtime.getRuntime().exec("cp Restart/allSpecies.txt Restart/allSpecies1.txt");
//Runtime.getRuntime().exec("echo >> allSpecies.txt");
restart = true;
}
else if (token.equalsIgnoreCase("false")) {
Runtime.getRuntime().exec("rm Restart/allSpecies.txt");
restart = false;
}
else throw new InvalidSymbolException("UnIdentified Symbol "+token+" after Restart:");
}
else throw new InvalidSymbolException("Can't find Restart!");*/
//line = ChemParser.readMeaningfulLine(reader);
if (line.startsWith("Database")){//svp
line = ChemParser.readMeaningfulLine(reader, true);
}
else throw new InvalidSymbolException("Can't find database!");
// if (line.startsWith("PrimaryThermoLibrary")){//svp
// line = ChemParser.readMeaningfulLine(reader);
// }
// else throw new InvalidSymbolException("Can't find primary thermo library!");
/*
* Added by MRH on 15-Jun-2009
* Give user the option to change the maximum carbon, oxygen,
* and/or radical number for all species. These lines will be
* optional in the condition.txt file. Values are hard-
* coded into RMG (in ChemGraph.java), but any user-
* defined input will override these values.
*/
/*
* Moved from before InitialStatus to before PrimaryThermoLibary
* by MRH on 27-Oct-2009
* Overriding default values of maximum number of "X" per
* chemgraph should come before RMG attempts to make any
* chemgraph. The first instance RMG will attempt to make a
* chemgraph is in reading the primary thermo library.
*/
line = readMaxAtomTypes(line,reader);
// if (line.startsWith("MaxCarbonNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxCarbonNumberPerSpecies:"
// int maxCNum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxCarbonNumber(maxCNum);
// System.out.println("Note: Overriding RMG-defined MAX_CARBON_NUM with user-defined value: " + maxCNum);
// line = ChemParser.readMeaningfulLine(reader);
// }
// if (line.startsWith("MaxOxygenNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxOxygenNumberPerSpecies:"
// int maxONum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxOxygenNumber(maxONum);
// System.out.println("Note: Overriding RMG-defined MAX_OXYGEN_NUM with user-defined value: " + maxONum);
// line = ChemParser.readMeaningfulLine(reader);
// }
// if (line.startsWith("MaxRadicalNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxRadicalNumberPerSpecies:"
// int maxRadNum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxRadicalNumber(maxRadNum);
// System.out.println("Note: Overriding RMG-defined MAX_RADICAL_NUM with user-defined value: " + maxRadNum);
// line = ChemParser.readMeaningfulLine(reader);
// }
// if (line.startsWith("MaxSulfurNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxSulfurNumberPerSpecies:"
// int maxSNum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxSulfurNumber(maxSNum);
// System.out.println("Note: Overriding RMG-defined MAX_SULFUR_NUM with user-defined value: " + maxSNum);
// line = ChemParser.readMeaningfulLine(reader);
// }
// if (line.startsWith("MaxSiliconNumber")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxSiliconNumberPerSpecies:"
// int maxSiNum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxSiliconNumber(maxSiNum);
// System.out.println("Note: Overriding RMG-defined MAX_SILICON_NUM with user-defined value: " + maxSiNum);
// line = ChemParser.readMeaningfulLine(reader);
// }
// if (line.startsWith("MaxHeavyAtom")) {
// StringTokenizer st = new StringTokenizer(line);
// String dummyString = st.nextToken(); // This should hold "MaxHeavyAtomPerSpecies:"
// int maxHANum = Integer.parseInt(st.nextToken());
// ChemGraph.setMaxHeavyAtomNumber(maxHANum);
// System.out.println("Note: Overriding RMG-defined MAX_HEAVYATOM_NUM with user-defined value: " + maxHANum);
// line = ChemParser.readMeaningfulLine(reader);
// }
/*
* Read in the Primary Thermo Library
* MRH 7-Jul-2009
*/
if (line.startsWith("PrimaryThermoLibrary:")) {
/*
* MRH 27Feb2010:
* Changing the "read in Primary Thermo Library information" code
* into it's own method.
*
* Other modules (e.g. PopulateReactions) will be utilizing the exact code.
* Rather than copying and pasting code into other modules, just have
* everything call this new method: readAndMakePTL
*/
readAndMakePTL(reader);
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate PrimaryThermoLibrary field");
line = ChemParser.readMeaningfulLine(reader, true);
/*
* MRH 17-May-2010:
* Added primary transport library field
*/
if (line.toLowerCase().startsWith("primarytransportlibrary")) {
readAndMakePTransL(reader);
} else throw new InvalidSymbolException("Error reading condition.txt file: "
+ "Could not locate PrimaryTransportLibrary field.");
line = ChemParser.readMeaningfulLine(reader, true);
// Extra forbidden structures may be specified after the Primary Thermo Library
if (line.startsWith("ForbiddenStructures:")) {
readExtraForbiddenStructures(reader);
line = ChemParser.readMeaningfulLine(reader, true);
}
if (line.toLowerCase().startsWith("readrestart")) {
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken(); // "ReadRestart:"
tempString = st.nextToken();
if (tempString.toLowerCase().equals("yes")) {
readrestart = true;
readRestartSpecies();
readRestartReactions();
} else readrestart = false;
line = ChemParser.readMeaningfulLine(reader, true);
} else throw new InvalidSymbolException("Cannot locate ReadRestart field");
if (line.toLowerCase().startsWith("writerestart")) {
StringTokenizer st = new StringTokenizer(line);
String tempString = st.nextToken(); // "WriteRestart:"
tempString = st.nextToken();
if (tempString.toLowerCase().equals("yes"))
writerestart = true;
else writerestart = false;
line = ChemParser.readMeaningfulLine(reader, true);
} else throw new InvalidSymbolException("Cannot locate WriteRestart field");
// read temperature model
//gmagoon 10/23/07: modified to handle multiple temperatures; note that this requires different formatting of units in condition.txt
if (line.startsWith("TemperatureModel:")) {
createTModel(line);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String modelType = st.nextToken();
// //String t = st.nextToken();
// String unit = st.nextToken();
// unit = ChemParser.removeBrace(unit);
// if (modelType.equals("Constant")) {
// tempList = new LinkedList();
// //read first temperature
// double t = Double.parseDouble(st.nextToken());
// tempList.add(new ConstantTM(t, unit));
// Temperature temp = new Temperature(t, unit);//10/29/07 gmagoon: added this line and next two lines to set Global.lowTemperature and Global.highTemperature
// Global.lowTemperature = (Temperature)temp.clone();
// Global.highTemperature = (Temperature)temp.clone();
// //read remaining temperatures
// while (st.hasMoreTokens()) {
// t = Double.parseDouble(st.nextToken());
// tempList.add(new ConstantTM(t, unit));
// temp = new Temperature(t,unit);//10/29/07 gmagoon: added this line and next two "if" statements to set Global.lowTemperature and Global.highTemperature
// if(temp.getK() < Global.lowTemperature.getK())
// Global.lowTemperature = (Temperature)temp.clone();
// if(temp.getK() > Global.highTemperature.getK())
// Global.highTemperature = (Temperature)temp.clone();
// }
// // Global.temperature = new Temperature(t,unit);
// }
//10/23/07 gmagoon: commenting out; further updates needed to get this to work
//else if (modelType.equals("Curved")) {
// String t = st.nextToken();
// // add reading curved temperature function here
// temperatureModel = new CurvedTM(new LinkedList());
//}
// else {
// throw new InvalidSymbolException("condition.txt: Unknown TemperatureModel = " + modelType);
// }
}
else throw new InvalidSymbolException("condition.txt: can't find TemperatureModel!");
// read in pressure model
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("PressureModel:")) {
createPModel(line);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String modelType = st.nextToken();
// //String p = st.nextToken();
// String unit = st.nextToken();
// unit = ChemParser.removeBrace(unit);
// if (modelType.equals("Constant")) {
// presList = new LinkedList();
// //read first pressure
// double p = Double.parseDouble(st.nextToken());
// Pressure pres = new Pressure(p, unit);
// Global.lowPressure = (Pressure)pres.clone();
// Global.highPressure = (Pressure)pres.clone();
// presList.add(new ConstantPM(p, unit));
// //read remaining temperatures
// while (st.hasMoreTokens()) {
// p = Double.parseDouble(st.nextToken());
// presList.add(new ConstantPM(p, unit));
// pres = new Pressure(p, unit);
// if(pres.getBar() < Global.lowPressure.getBar())
// Global.lowPressure = (Pressure)pres.clone();
// if(pres.getBar() > Global.lowPressure.getBar())
// Global.highPressure = (Pressure)pres.clone();
// }
// //Global.pressure = new Pressure(p, unit);
// }
// //10/23/07 gmagoon: commenting out; further updates needed to get this to work
// //else if (modelType.equals("Curved")) {
// // // add reading curved pressure function here
// // pressureModel = new CurvedPM(new LinkedList());
// //}
// else {
// throw new InvalidSymbolException("condition.txt: Unknown PressureModel = " + modelType);
// }
}
else throw new InvalidSymbolException("condition.txt: can't find PressureModel!");
// after PressureModel comes an optional line EquationOfState
// if "EquationOfState: Liquid" is found then initial concentrations are assumed to be correct
// if it is ommited, then initial concentrations are normalised to ensure PV=NRT (ideal gas law)
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("EquationOfState")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String eosType = st.nextToken().toLowerCase();
if (eosType.equals("liquid")) {
equationOfState="Liquid";
Logger.info("Equation of state: Liquid. Relying on concentrations in input file to get density correct; not checking PV=NRT");
}
line = ChemParser.readMeaningfulLine(reader, true);
}
// Read in InChI generation
if (line.startsWith("InChIGeneration:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String inchiOnOff = st.nextToken().toLowerCase();
if (inchiOnOff.equals("on")) {
Species.useInChI = true;
} else if (inchiOnOff.equals("off")) {
Species.useInChI = false;
}
else throw new InvalidSymbolException("condition.txt: Unknown InChIGeneration flag: " + inchiOnOff);
line = ChemParser.readMeaningfulLine(reader, true);
}
// Read in Solvation effects
if (line.startsWith("Solvation:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String solvationOnOff = st.nextToken().toLowerCase();
if (solvationOnOff.equals("on")) {
setUseSolvation(true);
Species.useSolvation = true;
readAndMakePAL();
String solventname = st.nextToken().toLowerCase();
readAndMakeSL(solventname);
Logger.info(String.format(
"Using solvation corrections to thermochemsitry with solvent properties of %s",solventname));
} else if (solvationOnOff.startsWith("off")) {
setUseSolvation(false);
Species.useSolvation = false;
}
else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff);
line = ChemParser.readMeaningfulLine(reader, true);
}
// Read in Diffusion effects
// If 'Diffusion' is 'on' then override the settings made by the solvation flag and sets solvation 'on'
if (line.startsWith("Diffusion:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String diffusionOnOff = st.nextToken().toLowerCase();
if (diffusionOnOff.equals("on")) {
String viscosity_str = st.nextToken();
viscosity = Double.parseDouble(viscosity_str);
setUseDiffusion(true);
Logger.info(String.format(
"Using diffusion corrections to kinetics with solvent viscosity of %.3g Pa.s.",viscosity));
} else if (diffusionOnOff.equals("off")) {
setUseDiffusion(false);
}
else throw new InvalidSymbolException("condition.txt: Unknown diffusion flag: " + diffusionOnOff);
line = ChemParser.readMeaningfulLine(reader,true);//read in reactants or thermo line
}
/* AJ 12JULY2010:
* Right now we do not want RMG to throw an exception if it cannot find a diffusion flag
*/
//else throw new InvalidSymbolException("condition.txt: Cannot find diffusion flag.");
// Should have already read in reactants or thermo line into variable 'line'
// Read in optional QM thermo generation
if (line.startsWith("ThermoMethod:")) {
StringTokenizer st = new StringTokenizer(line);
String name = st.nextToken();
String thermoMethod = st.nextToken().toLowerCase();
if (thermoMethod.equals("qm")) {
ChemGraph.useQM = true;
if(st.hasMoreTokens()){//override the default qmprogram ("both") if there are more; current options: "gaussian03" and "mopac" and of course, "both"
QMTP.qmprogram = st.nextToken().toLowerCase();
}
line=ChemParser.readMeaningfulLine(reader, true);
if(line.startsWith("QMForCyclicsOnly:")){
StringTokenizer st2 = new StringTokenizer(line);
String nameCyc = st2.nextToken();
String option = st2.nextToken().toLowerCase();
if (option.equals("on")) {
ChemGraph.useQMonCyclicsOnly = true;
}
}
else{
Logger.critical("condition.txt: Can't find 'QMForCyclicsOnly:' field");
System.exit(0);
}
line=ChemParser.readMeaningfulLine(reader, true);
if(line.startsWith("MaxRadNumForQM:")){
StringTokenizer st3 = new StringTokenizer(line);
String nameRadNum = st3.nextToken();
Global.maxRadNumForQM = Integer.parseInt(st3.nextToken());
}
else{
Logger.critical("condition.txt: Can't find 'MaxRadNumForQM:' field");
System.exit(0);
}
}//otherwise, the flag useQM will remain false by default and the traditional group additivity approach will be used
line = ChemParser.readMeaningfulLine(reader, true);//read in reactants
}
// // Read in Solvation effects
// if (line.startsWith("Solvation:")) {
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String solvationOnOff = st.nextToken().toLowerCase();
// if (solvationOnOff.equals("on")) {
// Species.useSolvation = true;
// } else if (solvationOnOff.equals("off")) {
// Species.useSolvation = false;
// }
// else throw new InvalidSymbolException("condition.txt: Unknown solvation flag: " + solvationOnOff);
// }
// else throw new InvalidSymbolException("condition.txt: Cannot find solvation flag.");
// read in reactants
//
//10/4/07 gmagoon: moved to initializeCoreEdgeReactionModel
//LinkedHashSet p_speciesSeed = new LinkedHashSet();//gmagoon 10/4/07: changed to p_speciesSeed
//setSpeciesSeed(p_speciesSeed);//gmagoon 10/4/07: added
LinkedHashMap speciesSet = new LinkedHashMap();
/*
* 7/Apr/2010: MRH
* Neither of these variables are utilized
*/
// LinkedHashMap speciesStatus = new LinkedHashMap();
// int speciesnum = 1;
//System.out.println(line);
if (line.startsWith("InitialStatus")) {
speciesSet = populateInitialStatusListWithReactiveSpecies(reader);
// line = ChemParser.readMeaningfulLine(reader);
// while (!line.equals("END")) {
// StringTokenizer st = new StringTokenizer(line);
// String index = st.nextToken();
// String name = null;
// if (!index.startsWith("(")) name = index;
// else name = st.nextToken();
// //if (restart) name += "("+speciesnum+")";
// // 24Jun2009: MRH
// // Check if the species name begins with a number.
// // If so, terminate the program and inform the user to choose
// // a different name. This is implemented so that the chem.inp
// // file generated will be valid when run in Chemkin
// try {
// int doesNameBeginWithNumber = Integer.parseInt(name.substring(0,1));
// System.out.println("\nA species name should not begin with a number." +
// " Please rename species: " + name + "\n");
// System.exit(0);
// } catch (NumberFormatException e) {
// // We're good
// }
// speciesnum ++;
// if (!(st.hasMoreTokens())) throw new InvalidSymbolException("Couldn't find concentration of species: "+name);
// String conc = st.nextToken();
// double concentration = Double.parseDouble(conc);
// String unit = st.nextToken();
// unit = ChemParser.removeBrace(unit);
// if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
// concentration /= 1000;
// unit = "mol/cm3";
// }
// else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
// concentration /= 1000000;
// unit = "mol/cm3";
// }
// else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
// concentration /= 6.022e23;
// }
// else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
// throw new InvalidUnitException("Species Concentration in condition.txt!");
// }
//
// //GJB to allow "unreactive" species that only follow user-defined library reactions.
// // They will not react according to RMG reaction families
// boolean IsReactive = true;
// boolean IsConstantConcentration = false;
// while (st.hasMoreTokens()) {
// String reactive = st.nextToken().trim();
// if (reactive.equalsIgnoreCase("unreactive"))
// IsReactive = false;
// if (reactive.equalsIgnoreCase("constantconcentration"))
// IsConstantConcentration=true;
// }
//
// Graph g = ChemParser.readChemGraph(reader);
// ChemGraph cg = null;
// try {
// cg = ChemGraph.make(g);
// }
// catch (ForbiddenStructureException e) {
// System.out.println("Forbidden Structure:\n" + e.getMessage());
// throw new InvalidSymbolException("A species in the input file has a forbidden structure.");
// }
// //System.out.println(name);
// Species species = Species.make(name,cg);
// species.setReactivity(IsReactive); // GJB
// species.setConstantConcentration(IsConstantConcentration);
// speciesSet.put(name, species);
// getSpeciesSeed().add(species);
// double flux = 0;
// int species_type = 1; // reacted species
// SpeciesStatus ss = new SpeciesStatus(species,species_type,concentration,flux);
// speciesStatus.put(species, ss);
// line = ChemParser.readMeaningfulLine(reader);
// }
// ReactionTime initial = new ReactionTime(0,"S");
// //10/23/07 gmagoon: modified for handling multiple temperature, pressure conditions; note: concentration within speciesStatus (and list of conversion values) should not need to be modified for each T,P since this is done within isTPCconsistent in ReactionSystem
// initialStatusList = new LinkedList();
// for (Iterator iter = tempList.iterator(); iter.hasNext(); ) {
// TemperatureModel tm = (TemperatureModel)iter.next();
// for (Iterator iter2 = presList.iterator(); iter2.hasNext(); ){
// PressureModel pm = (PressureModel)iter2.next();
// // LinkedHashMap speStat = (LinkedHashMap)speciesStatus.clone();//10/31/07 gmagoon: trying creating multiple instances of speciesStatus to address issues with concentration normalization (last normalization seems to apply to all)
// Set ks = speciesStatus.keySet();
// LinkedHashMap speStat = new LinkedHashMap();
// for (Iterator iter3 = ks.iterator(); iter3.hasNext();){//11/1/07 gmagoon: perform deep copy; (is there an easier or more elegant way to do this?)
// SpeciesStatus ssCopy = (SpeciesStatus)speciesStatus.get(iter3.next());
// speStat.put(ssCopy.getSpecies(),new SpeciesStatus(ssCopy.getSpecies(),ssCopy.getSpeciesType(),ssCopy.getConcentration(),ssCopy.getFlux()));
// }
// initialStatusList.add(new InitialStatus(speStat,tm.getTemperature(initial),pm.getPressure(initial)));
// }
// }
}
else throw new InvalidSymbolException("condition.txt: can't find InitialStatus!");
// read in inert gas concentration
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("InertGas:")) {
populateInitialStatusListWithInertSpecies(reader);
// line = ChemParser.readMeaningfulLine(reader);
// while (!line.equals("END")) {
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken().trim();
// String conc = st.nextToken();
// double inertConc = Double.parseDouble(conc);
// String unit = st.nextToken();
// unit = ChemParser.removeBrace(unit);
// if (unit.equals("mole/l") || unit.equals("mol/l") || unit.equals("mole/liter") || unit.equals("mol/liter")) {
// inertConc /= 1000;
// unit = "mol/cm3";
// }
// else if (unit.equals("mole/m3") || unit.equals("mol/m3")) {
// inertConc /= 1000000;
// unit = "mol/cm3";
// }
// else if (unit.equals("molecule/cm3") || unit.equals("molecules/cm3")) {
// inertConc /= 6.022e23;
// unit = "mol/cm3";
// }
// else if (!unit.equals("mole/cm3") && !unit.equals("mol/cm3")) {
// throw new InvalidUnitException("Inert Gas Concentration not recognized: " + unit);
// }
//
// //SystemSnapshot.putInertGas(name,inertConc);
// for(Iterator iter=initialStatusList.iterator();iter.hasNext(); ){//6/23/09 gmagoon: needed to change this to accommodate non-static inertConc
// ((InitialStatus)iter.next()).putInertGas(name,inertConc);
// }
// line = ChemParser.readMeaningfulLine(reader);
// }
}
else throw new InvalidSymbolException("condition.txt: can't find Inert gas concentration!");
// read in spectroscopic data estimator
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("SpectroscopicDataEstimator:")) {
setSpectroscopicDataMode(line);
// StringTokenizer st = new StringTokenizer(line);
// String name = st.nextToken();
// String sdeType = st.nextToken().toLowerCase();
// if (sdeType.equals("frequencygroups") || sdeType.equals("default")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.FREQUENCYGROUPS;
// }
// else if (sdeType.equals("therfit") || sdeType.equals("threefrequencymodel")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.THREEFREQUENCY;
// }
// else if (sdeType.equals("off") || sdeType.equals("none")) {
// SpectroscopicData.mode = SpectroscopicData.Mode.OFF;
// }
// else throw new InvalidSymbolException("condition.txt: Unknown SpectroscopicDataEstimator = " + sdeType);
}
else throw new InvalidSymbolException("condition.txt: can't find SpectroscopicDataEstimator!");
// pressure dependence and related flags
line = ChemParser.readMeaningfulLine(reader, true);
if (line.toLowerCase().startsWith("pressuredependence:"))
line = setPressureDependenceOptions(line,reader);
else
throw new InvalidSymbolException("condition.txt: can't find PressureDependence flag!");
if (readrestart) if (PDepNetwork.generateNetworks) readPDepNetworks();
// include species (optional)
/*
*
* MRH 3-APR-2010:
* This if statement is no longer necessary and was causing an error
* when the PressureDependence field was set to "off"
*/
// if (!PDepRateConstant.getMode().name().equals("CHEBYSHEV") &&
// !PDepRateConstant.getMode().name().equals("PDEPARRHENIUS"))
// line = ChemParser.readMeaningfulLine(reader);
// read in finish controller
if (line.startsWith("FinishController")) {
line = ChemParser.readMeaningfulLine(reader, true);
StringTokenizer st = new StringTokenizer(line);
String index = st.nextToken();
String goal = st.nextToken();
String type = st.nextToken();
TerminationTester tt;
if (type.startsWith("Conversion")) {
LinkedList spc = new LinkedList();
while (st.hasMoreTokens()) {
String name = st.nextToken();
Species spe = (Species)speciesSet.get(name);
if (spe == null) throw new InvalidConversionException("Unknown reactant in 'Goal Conversion' field of input file : " + name);
setLimitingReactantID(spe.getID());
String conv = st.nextToken();
double conversion;
try {
if (conv.endsWith("%")) {
conversion = Double.parseDouble(conv.substring(0,conv.length()-1))/100;
}
else {
conversion = Double.parseDouble(conv);
}
conversionSet[49] = conversion;
}
catch (NumberFormatException e) {
throw new NumberFormatException("wrong number format for conversion in initial condition file!");
}
SpeciesConversion sc = new SpeciesConversion(spe, conversion);
spc.add(sc);
}
tt = new ConversionTT(spc);
}
else if (type.startsWith("ReactionTime")) {
double time = Double.parseDouble(st.nextToken());
String unit = ChemParser.removeBrace(st.nextToken());
ReactionTime rt = new ReactionTime(time, unit);
tt = new ReactionTimeTT(rt);
}
else {
throw new InvalidSymbolException("condition.txt: Unknown FinishController = " + type);
}
line = ChemParser.readMeaningfulLine(reader, true);
st = new StringTokenizer(line, ":");
String temp = st.nextToken();
String tol = st.nextToken();
try {
if (tol.endsWith("%")) {
tolerance = Double.parseDouble(tol.substring(0,tol.length()-1))/100;
}
else {
tolerance = Double.parseDouble(tol);
}
}
catch (NumberFormatException e) {
throw new NumberFormatException("wrong number format for conversion in initial condition file!");
}
ValidityTester vt = null;
if (reactionModelEnlarger instanceof RateBasedRME) vt = new RateBasedVT(tolerance);
else if (reactionModelEnlarger instanceof RateBasedPDepRME) vt = new RateBasedPDepVT(tolerance);
else throw new InvalidReactionModelEnlargerException();
finishController = new FinishController(tt, vt);
}
else throw new InvalidSymbolException("condition.txt: can't find FinishController!");
// read in dynamic simulator
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("DynamicSimulator")) {
StringTokenizer st = new StringTokenizer(line,":");
String temp = st.nextToken();
String simulator = st.nextToken().trim();
//read in non-negative option if it exists: syntax would be something like this: "DynamicSimulator: DASSL: non-negative"
if (st.hasMoreTokens()){
if (st.nextToken().trim().toLowerCase().equals("non-negative")){
if(simulator.toLowerCase().equals("dassl")) JDAS.nonnegative = true;
else{
Logger.critical("Non-negative option is currently only supported for DASSL. Switch to DASSL solver or remove non-negative option.");
System.exit(0);
}
}
}
numConversions = 0;//5/6/08 gmagoon: moved declaration from initializeReactionSystem() to be an attribute so it can be accessed by modelGenerator()
//int numConversions = 0;
boolean autoflag = false;//5/2/08 gmagoon: updating the following if/else-if block to consider input where we want to check model validity within the ODE solver at each time step; this will be indicated by the use of a string beginning with "AUTO" after the "TimeStep" or "Conversions" line
// read in time step
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("TimeStep:")) {
if (!(finishController.terminationTester instanceof ReactionTimeTT))
throw new InvalidSymbolException("'TimeStep:' specified but finish controller goal is not reaction time.");
st = new StringTokenizer(line);
temp = st.nextToken();
while (st.hasMoreTokens()) {
temp = st.nextToken();
if (temp.startsWith("AUTO")){//note potential opportunity for making case insensitive by using: temp.toUpperCase().startsWith("AUTO")
autoflag=true;
}
else if (!autoflag){//use "else if" to make sure additional numbers are not read in case numbers are erroneously used following AUTO; note that there could still be a problem if numbers come before "AUTO"
double tStep = Double.parseDouble(temp);
String unit = "sec";
setTimeStep(new ReactionTime(tStep, unit));
}
}
((ReactionTimeTT)finishController.terminationTester).setTimeSteps(timeStep);
}
else if (line.startsWith("Conversions:")){
if (!(finishController.terminationTester instanceof ConversionTT))
throw new InvalidSymbolException("'Conversions:' specified but finish controller goal is not conversion.");
st = new StringTokenizer(line);
temp = st.nextToken();
int i=0;
SpeciesConversion sc = (SpeciesConversion)((ConversionTT)finishController.terminationTester).speciesGoalConversionSet.get(0);
Species convSpecies = sc.species;
Iterator iter = ((InitialStatus)(initialStatusList.get(0))).getSpeciesStatus();//10/23/07 gmagoon: changed to use first element of initialStatusList, as subsequent operations should not be affected by which one is chosen
double initialConc = 0;
while (iter.hasNext()){
SpeciesStatus sps = (SpeciesStatus)iter.next();
if (sps.species.equals(convSpecies)) initialConc = sps.concentration;
}
while (st.hasMoreTokens()){
temp=st.nextToken();
if (temp.startsWith("AUTO")){
autoflag=true;
}
else if (!autoflag){
double conv = Double.parseDouble(temp);
conversionSet[i] = (1-conv) * initialConc;
i++;
}
}
conversionSet[i] = (1 - conversionSet[49])* initialConc;
numConversions = i+1;
}
else throw new InvalidSymbolException("In condition file can't find 'TimeStep:' or 'Conversions:' for dynamic simulator.");
//
if (temp.startsWith("AUTOPRUNE")){//for the AUTOPRUNE case, read in additional lines for termTol and edgeTol
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("TerminationTolerance:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
termTol = Double.parseDouble(st.nextToken());
}
else {
Logger.critical("Cannot find TerminationTolerance in condition.txt");
System.exit(0);
}
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("PruningTolerance:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
edgeTol = Double.parseDouble(st.nextToken());
}
else {
Logger.critical("Cannot find PruningTolerance in condition.txt");
System.exit(0);
}
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("MinSpeciesForPruning:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
minSpeciesForPruning = Integer.parseInt(st.nextToken());
}
else {
Logger.critical("Cannot find MinSpeciesForPruning in condition.txt");
System.exit(0);
}
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("MaxEdgeSpeciesAfterPruning:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
maxEdgeSpeciesAfterPruning = Integer.parseInt(st.nextToken());
}
else {
Logger.critical("Cannot find MaxEdgeSpeciesAfterPruning in condition.txt");
System.exit(0);
}
//print header for pruning log (based on restart format)
BufferedWriter bw = null;
try {
File f = new File("Pruning/edgeReactions.txt");
bw = new BufferedWriter(new FileWriter("Pruning/edgeReactions.txt", true));
String EaUnits = ArrheniusKinetics.getEaUnits();
bw.write("UnitsOfEa: " + EaUnits);
bw.newLine();
} catch (FileNotFoundException ex) {
Logger.logStackTrace(ex);
} catch (IOException ex) {
Logger.logStackTrace(ex);
} finally {
try {
if (bw != null) {
bw.flush();
bw.close();
}
} catch (IOException ex) {
Logger.logStackTrace(ex);
}
}
}
else if (temp.startsWith("AUTO")){//in the non-autoprune case (i.e. original AUTO functionality), we set the new parameters to values that should reproduce original functionality
termTol = tolerance;
edgeTol = 0;
minSpeciesForPruning = 999999;//arbitrary high number (actually, the value here should not matter, since pruning should not be done)
maxEdgeSpeciesAfterPruning = 999999;
}
// read in atol
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Atol:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
atol = Double.parseDouble(st.nextToken());
}
else throw new InvalidSymbolException("condition.txt: can't find Atol for dynamic simulator!");
// read in rtol
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Rtol:")) {
st = new StringTokenizer(line);
temp = st.nextToken();
String rel_tol = st.nextToken();
if (rel_tol.endsWith("%"))
rtol = Double.parseDouble(rel_tol.substring(0,rel_tol.length()-1));
else
rtol = Double.parseDouble(rel_tol);
}
else throw new InvalidSymbolException("condition.txt: can't find Rtol for dynamic simulator!");
if (simulator.equals("DASPK")) {
paraInfor = 0;//svp
// read in SA
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Error bars")) {//svp
st = new StringTokenizer(line,":");
temp = st.nextToken();
String sa = st.nextToken().trim();
if (sa.compareToIgnoreCase("on")==0) {
paraInfor = 1;
error = true;
}
else if (sa.compareToIgnoreCase("off")==0) {
paraInfor = 0;
error = false;
}
else throw new InvalidSymbolException("condition.txt: can't find error on/off information!");
}
else throw new InvalidSymbolException("condition.txt: can't find SA information!");
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Display sensitivity coefficients")){//svp
st = new StringTokenizer(line,":");
temp = st.nextToken();
String sa = st.nextToken().trim();
if (sa.compareToIgnoreCase("on")==0){
paraInfor = 1;
sensitivity = true;
}
else if (sa.compareToIgnoreCase("off")==0){
if (paraInfor != 1){
paraInfor = 0;
}
sensitivity = false;
}
else throw new InvalidSymbolException("condition.txt: can't find SA on/off information!");
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
//6/25/08 gmagoon: changed loop to use i index, and updated DASPK constructor to pass i (mirroring changes to DASSL
//6/25/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null?
for (int i = 0;i < initialStatusList.size();i++) {
dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i,finishController.getValidityTester(), autoflag, termTol, tolerance));
}
}
species = new LinkedList();
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("Display sensitivity information") ){
line = ChemParser.readMeaningfulLine(reader, true);
Logger.info(line);
while (!line.equals("END")){
st = new StringTokenizer(line);
String name = st.nextToken();
if (name.toUpperCase().equals("ALL")) ReactionSystem.printAllSens = true; //gmagoon 12/22/09: if the line contains the word "all", turn on the flag to print out sensitivity information for everything
species.add(name);
line = ChemParser.readMeaningfulLine(reader, true);
}
}
}
else if (simulator.equals("DASSL")) {
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
// for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) {
// dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)iter.next()));
// }
//11/1/07 gmagoon: changed loop to use i index, and updated DASSL constructor to pass i
//5/5/08 gmagoon: updated to pass autoflag and validity tester; this requires FinishController block of input file to be present before DynamicSimulator block, but this requirement may have already existed anyway, particularly in construction of conversion/time step lists; *perhaps we should formalize this requirement by checking to make sure validityTester is not null?
for (int i = 0;i < initialStatusList.size();i++) {
dynamicSimulatorList.add(new JDASSL(rtol, atol, 0, (InitialStatus)initialStatusList.get(i), i, finishController.getValidityTester(), autoflag, termTol, tolerance));
}
}
else if (simulator.equals("Chemkin")) {
line = ChemParser.readMeaningfulLine(reader, true);
if (line.startsWith("ReactorType")) {
st = new StringTokenizer(line, ":");
temp = st.nextToken();
String reactorType = st.nextToken().trim();
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList
for (Iterator iter = initialStatusList.iterator(); iter.hasNext(); ) {
//dynamicSimulatorList.add(new JDASPK(rtol, atol, 0, (InitialStatus)iter.next()));
dynamicSimulatorList.add(new Chemkin(rtol, atol, reactorType));//11/4/07 gmagoon: fixing apparent cut/paste error
}
}
}
else throw new InvalidSymbolException("condition.txt: Unknown DynamicSimulator = " + simulator);
//10/23/07 gmagoon: changed below from dynamicSimulator to dynamicSimulatorList; note: although conversionSet should actually be different for each T,P condition, it will be modified in isTPCconsistent within ReactionSystem
for (Iterator iter = dynamicSimulatorList.iterator(); iter.hasNext(); ) {
double [] cs = conversionSet.clone();//11/1/07 gmagoon: trying to make sure multiple instances of conversionSet are used
((DynamicSimulator)(iter.next())).addConversion(cs, numConversions);
}
}
|
diff --git a/src/main/java/com/github/rnewson/couchdb/lucene/rhino/RhinoDocument.java b/src/main/java/com/github/rnewson/couchdb/lucene/rhino/RhinoDocument.java
index 2009e61..c0583c1 100644
--- a/src/main/java/com/github/rnewson/couchdb/lucene/rhino/RhinoDocument.java
+++ b/src/main/java/com/github/rnewson/couchdb/lucene/rhino/RhinoDocument.java
@@ -1,184 +1,185 @@
package com.github.rnewson.couchdb.lucene.rhino;
/**
* Copyright 2009 Robert Newson, Paul Davis
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.lucene.document.Document;
import org.apache.lucene.queryParser.ParseException;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Function;
import org.mozilla.javascript.NativeObject;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
import org.mozilla.javascript.Undefined;
import com.github.rnewson.couchdb.lucene.Tika;
import com.github.rnewson.couchdb.lucene.couchdb.Database;
import com.github.rnewson.couchdb.lucene.couchdb.FieldType;
import com.github.rnewson.couchdb.lucene.couchdb.ViewSettings;
import com.github.rnewson.couchdb.lucene.util.Utils;
/**
* Collect data from the user.
*
* @author rnewson
*
*/
public final class RhinoDocument extends ScriptableObject {
private static class RhinoAttachment {
private String attachmentName;
private String fieldName;
}
private static class RhinoField {
private NativeObject settings;
private Object value;
}
private static final long serialVersionUID = 1L;
public static Scriptable jsConstructor(final Context cx, final Object[] args, final Function ctorObj, final boolean inNewExpr) {
final RhinoDocument doc = new RhinoDocument();
if (args.length >= 2) {
jsFunction_add(cx, doc, args, ctorObj);
}
return doc;
}
public static void jsFunction_add(final Context cx, final Scriptable thisObj, final Object[] args, final Function funObj) {
final RhinoDocument doc = checkInstance(thisObj);
if (args.length < 1 || args.length > 2) {
throw Context.reportRuntimeError("Invalid number of arguments.");
}
if (args[0] == null) {
- throw Context.reportRuntimeError("first argument must be non-null.");
+ // Ignore.
+ return;
}
if (args[0] instanceof Undefined) {
// Ignore
return;
}
final String className = args[0].getClass().getName();
if (className.equals("org.mozilla.javascript.NativeDate")) {
args[0] = (Date) Context.jsToJava(args[0], Date.class);
}
if (!className.startsWith("java.lang.") &&
!className.equals("org.mozilla.javascript.NativeObject") &&
!className.equals("org.mozilla.javascript.NativeDate")) {
throw Context.reportRuntimeError(className + " is not supported.");
}
if (args.length == 2 && (args[1] == null || args[1] instanceof NativeObject == false)) {
throw Context.reportRuntimeError("second argument must be an object.");
}
final RhinoField field = new RhinoField();
field.value = args[0];
if (args.length == 2) {
field.settings = (NativeObject) args[1];
}
doc.fields.add(field);
}
public static void jsFunction_attachment(final Context cx, final Scriptable thisObj, final Object[] args, final Function funObj)
throws IOException {
final RhinoDocument doc = checkInstance(thisObj);
if (args.length < 2) {
throw Context.reportRuntimeError("Invalid number of arguments.");
}
final RhinoAttachment attachment = new RhinoAttachment();
attachment.fieldName = args[0].toString();
attachment.attachmentName = args[1].toString();
doc.attachments.add(attachment);
}
private static RhinoDocument checkInstance(final Scriptable obj) {
if (obj == null || !(obj instanceof RhinoDocument)) {
throw Context.reportRuntimeError("called on incompatible object.");
}
return (RhinoDocument) obj;
}
private final List<RhinoAttachment> attachments = new ArrayList<RhinoAttachment>();
private final List<RhinoField> fields = new ArrayList<RhinoField>();
public RhinoDocument() {
}
public Document toDocument(final String id, final ViewSettings defaults, final Database database) throws IOException,
ParseException {
final Document result = new Document();
// Add id.
result.add(Utils.token("_id", id, true));
// Add user-supplied fields.
for (final RhinoField field : fields) {
addField(field, defaults, result);
}
// Parse user-requested attachments.
for (final RhinoAttachment attachment : attachments) {
addAttachment(attachment, id, database, result);
}
return result;
}
@Override
public String getClassName() {
return "Document";
}
private void addAttachment(final RhinoAttachment attachment, final String id, final Database database, final Document out)
throws IOException {
final ResponseHandler<Void> handler = new ResponseHandler<Void>() {
public Void handleResponse(final HttpResponse response) throws ClientProtocolException, IOException {
final HttpEntity entity = response.getEntity();
Tika.INSTANCE.parse(entity.getContent(), entity.getContentType().getValue(), attachment.fieldName, out);
return null;
}
};
database.handleAttachment(id, attachment.attachmentName, handler);
}
private void addField(final RhinoField field, final ViewSettings defaults, final Document out) throws ParseException {
final ViewSettings settings = new ViewSettings(field.settings, defaults);
final FieldType type = settings.getFieldType();
out.add(type.toField(settings.getField(), field.value, settings));
}
}
| true | true | public static void jsFunction_add(final Context cx, final Scriptable thisObj, final Object[] args, final Function funObj) {
final RhinoDocument doc = checkInstance(thisObj);
if (args.length < 1 || args.length > 2) {
throw Context.reportRuntimeError("Invalid number of arguments.");
}
if (args[0] == null) {
throw Context.reportRuntimeError("first argument must be non-null.");
}
if (args[0] instanceof Undefined) {
// Ignore
return;
}
final String className = args[0].getClass().getName();
if (className.equals("org.mozilla.javascript.NativeDate")) {
args[0] = (Date) Context.jsToJava(args[0], Date.class);
}
if (!className.startsWith("java.lang.") &&
!className.equals("org.mozilla.javascript.NativeObject") &&
!className.equals("org.mozilla.javascript.NativeDate")) {
throw Context.reportRuntimeError(className + " is not supported.");
}
if (args.length == 2 && (args[1] == null || args[1] instanceof NativeObject == false)) {
throw Context.reportRuntimeError("second argument must be an object.");
}
final RhinoField field = new RhinoField();
field.value = args[0];
if (args.length == 2) {
field.settings = (NativeObject) args[1];
}
doc.fields.add(field);
}
| public static void jsFunction_add(final Context cx, final Scriptable thisObj, final Object[] args, final Function funObj) {
final RhinoDocument doc = checkInstance(thisObj);
if (args.length < 1 || args.length > 2) {
throw Context.reportRuntimeError("Invalid number of arguments.");
}
if (args[0] == null) {
// Ignore.
return;
}
if (args[0] instanceof Undefined) {
// Ignore
return;
}
final String className = args[0].getClass().getName();
if (className.equals("org.mozilla.javascript.NativeDate")) {
args[0] = (Date) Context.jsToJava(args[0], Date.class);
}
if (!className.startsWith("java.lang.") &&
!className.equals("org.mozilla.javascript.NativeObject") &&
!className.equals("org.mozilla.javascript.NativeDate")) {
throw Context.reportRuntimeError(className + " is not supported.");
}
if (args.length == 2 && (args[1] == null || args[1] instanceof NativeObject == false)) {
throw Context.reportRuntimeError("second argument must be an object.");
}
final RhinoField field = new RhinoField();
field.value = args[0];
if (args.length == 2) {
field.settings = (NativeObject) args[1];
}
doc.fields.add(field);
}
|
diff --git a/plugins/org.eclipse.etrice.generator/src/org/eclipse/etrice/generator/base/GeneratorBaseModule.java b/plugins/org.eclipse.etrice.generator/src/org/eclipse/etrice/generator/base/GeneratorBaseModule.java
index 16ecbfa0..3c5993ad 100644
--- a/plugins/org.eclipse.etrice.generator/src/org/eclipse/etrice/generator/base/GeneratorBaseModule.java
+++ b/plugins/org.eclipse.etrice.generator/src/org/eclipse/etrice/generator/base/GeneratorBaseModule.java
@@ -1,43 +1,44 @@
/*******************************************************************************
* Copyright (c) 2011 protos software gmbh (http://www.protos.de).
* 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:
* Thomas Schuetz and Henrik Rentz-Reichert (initial contribution)
*
*******************************************************************************/
package org.eclipse.etrice.generator.base;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.etrice.generator.etricegen.IDiagnostician;
import com.google.inject.Binder;
import com.google.inject.Module;
import com.google.inject.Singleton;
/**
* @author hrentz
*
*/
public class GeneratorBaseModule implements Module {
/* (non-Javadoc)
* @see com.google.inject.Module#configure(com.google.inject.Binder)
*/
@Override
public void configure(Binder binder) {
binder.bind(ResourceSet.class).to(ResourceSetImpl.class);
binder.bind(Logger.class).in(Singleton.class);
binder.bind(ILineOutputLogger.class).to(Logger.class);
+ binder.bind(ILogger.class).to(Logger.class);
binder.bind(Diagnostician.class).in(Singleton.class);
binder.bind(IDiagnostician.class).to(Diagnostician.class);
}
}
| true | true | public void configure(Binder binder) {
binder.bind(ResourceSet.class).to(ResourceSetImpl.class);
binder.bind(Logger.class).in(Singleton.class);
binder.bind(ILineOutputLogger.class).to(Logger.class);
binder.bind(Diagnostician.class).in(Singleton.class);
binder.bind(IDiagnostician.class).to(Diagnostician.class);
}
| public void configure(Binder binder) {
binder.bind(ResourceSet.class).to(ResourceSetImpl.class);
binder.bind(Logger.class).in(Singleton.class);
binder.bind(ILineOutputLogger.class).to(Logger.class);
binder.bind(ILogger.class).to(Logger.class);
binder.bind(Diagnostician.class).in(Singleton.class);
binder.bind(IDiagnostician.class).to(Diagnostician.class);
}
|
diff --git a/src/frontend/org/voltdb/RealVoltDB.java b/src/frontend/org/voltdb/RealVoltDB.java
index 53e574843..71e99ea81 100644
--- a/src/frontend/org/voltdb/RealVoltDB.java
+++ b/src/frontend/org/voltdb/RealVoltDB.java
@@ -1,2256 +1,2254 @@
/* This file is part of VoltDB.
* Copyright (C) 2008-2012 VoltDB Inc.
*
* VoltDB 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.
*
* VoltDB 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 VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.lang.management.ManagementFactory;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.Semaphore;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.zip.CRC32;
import org.apache.zookeeper_voltpatches.CreateMode;
import org.apache.zookeeper_voltpatches.KeeperException;
import org.apache.zookeeper_voltpatches.ZooDefs.Ids;
import org.apache.zookeeper_voltpatches.ZooKeeper;
import org.apache.zookeeper_voltpatches.data.Stat;
import org.json_voltpatches.JSONArray;
import org.json_voltpatches.JSONObject;
import org.json_voltpatches.JSONStringer;
import org.voltcore.logging.Level;
import org.voltcore.logging.VoltLogger;
import org.voltcore.messaging.HostMessenger;
import org.voltcore.messaging.Mailbox;
import org.voltcore.utils.COWMap;
import org.voltcore.utils.CoreUtils;
import org.voltcore.utils.Pair;
import org.voltcore.zk.ZKUtil;
import org.voltdb.iv2.Cartographer;
import org.voltdb.iv2.LeaderAppointer;
import org.voltdb.iv2.SpInitiator;
import org.voltdb.VoltDB.START_ACTION;
import org.voltdb.VoltZK.MailboxType;
import org.voltdb.catalog.Catalog;
import org.voltdb.catalog.Cluster;
import org.voltdb.catalog.Database;
import org.voltdb.compiler.AsyncCompilerAgent;
import org.voltdb.compiler.ClusterConfig;
import org.voltdb.compiler.deploymentfile.DeploymentType;
import org.voltdb.compiler.deploymentfile.HeartbeatType;
import org.voltdb.compiler.deploymentfile.UsersType;
import org.voltdb.dtxn.DtxnInitiatorMailbox;
import org.voltdb.dtxn.ExecutorTxnIdSafetyState;
import org.voltdb.dtxn.MailboxPublisher;
import org.voltdb.dtxn.MailboxTracker;
import org.voltdb.dtxn.MailboxUpdateHandler;
import org.voltdb.dtxn.SimpleDtxnInitiator;
import org.voltdb.dtxn.SiteTracker;
import org.voltdb.dtxn.TransactionInitiator;
import org.voltdb.export.ExportManager;
import org.voltdb.fault.FaultDistributor;
import org.voltdb.fault.FaultDistributorInterface;
import org.voltdb.fault.SiteFailureFault;
import org.voltdb.fault.VoltFault.FaultType;
import org.voltdb.iv2.Initiator;
import org.voltdb.iv2.MpInitiator;
import org.voltdb.licensetool.LicenseApi;
import org.voltdb.messaging.VoltDbMessageFactory;
import org.voltdb.rejoin.RejoinCoordinator;
import org.voltdb.rejoin.SequentialRejoinCoordinator;
import org.voltdb.utils.CatalogUtil;
import org.voltdb.utils.HTTPAdminListener;
import org.voltdb.utils.LogKeys;
import org.voltdb.utils.MiscUtils;
import org.voltdb.utils.PlatformProperties;
import org.voltdb.utils.ResponseSampler;
import org.voltdb.utils.SystemStatsCollector;
import org.voltdb.utils.VoltSampler;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.ListeningExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.common.util.concurrent.SettableFuture;
/**
* RealVoltDB initializes global server components, like the messaging
* layer, ExecutionSite(s), and ClientInterface. It provides accessors
* or references to those global objects. It is basically the global
* namespace. A lot of the global namespace is described by VoltDBInterface
* to allow test mocking.
*/
public class RealVoltDB implements VoltDBInterface, RestoreAgent.Callback, MailboxUpdateHandler
{
private static final VoltLogger log = new VoltLogger(VoltDB.class.getName());
private static final VoltLogger hostLog = new VoltLogger("HOST");
private static final VoltLogger consoleLog = new VoltLogger("CONSOLE");
/** Default deployment file contents if path to deployment is null */
private static final String[] defaultDeploymentXML = {
"<?xml version=\"1.0\"?>",
"<!-- IMPORTANT: This file is an auto-generated default deployment configuration.",
" Changes to this file will be overwritten. Copy it elsewhere if you",
" want to use it as a starting point for a custom configuration. -->",
"<deployment>",
" <cluster hostcount=\"1\" sitesperhost=\"2\" />",
" <httpd enabled=\"true\">",
" <jsonapi enabled=\"true\" />",
" </httpd>",
"</deployment>"
};
public VoltDB.Configuration m_config = new VoltDB.Configuration();
private volatile boolean m_validateConfiguredNumberOfPartitionsOnMailboxUpdate;
private int m_configuredNumberOfPartitions;
CatalogContext m_catalogContext;
volatile SiteTracker m_siteTracker;
MailboxPublisher m_mailboxPublisher;
MailboxTracker m_mailboxTracker;
private String m_buildString;
private static final String m_defaultVersionString = "2.8";
private String m_versionString = m_defaultVersionString;
HostMessenger m_messenger = null;
final ArrayList<ClientInterface> m_clientInterfaces = new ArrayList<ClientInterface>();
final ArrayList<SimpleDtxnInitiator> m_dtxns = new ArrayList<SimpleDtxnInitiator>();
private Map<Long, ExecutionSite> m_localSites;
HTTPAdminListener m_adminListener;
private Map<Long, Thread> m_siteThreads;
private ArrayList<ExecutionSiteRunner> m_runners;
private ExecutionSite m_currentThreadSite;
private StatsAgent m_statsAgent = new StatsAgent();
private AsyncCompilerAgent m_asyncCompilerAgent = new AsyncCompilerAgent();
public AsyncCompilerAgent getAsyncCompilerAgent() { return m_asyncCompilerAgent; }
FaultDistributor m_faultManager;
private PartitionCountStats m_partitionCountStats = null;
private IOStats m_ioStats = null;
private MemoryStats m_memoryStats = null;
private StatsManager m_statsManager = null;
private SnapshotCompletionMonitor m_snapshotCompletionMonitor;
int m_myHostId;
long m_depCRC = -1;
String m_serializedCatalog;
String m_httpPortExtraLogMessage = null;
boolean m_jsonEnabled;
DeploymentType m_deployment;
// IV2 things
List<Initiator> m_iv2Initiators = new ArrayList<Initiator>();
Cartographer m_cartographer = null;
LeaderAppointer m_leaderAppointer = null;
GlobalServiceElector m_globalServiceElector = null;
// Should the execution sites be started in recovery mode
// (used for joining a node to an existing cluster)
// If CL is enabled this will be set to true
// by the CL when the truncation snapshot completes
// and this node is viable for replay
volatile boolean m_rejoining = false;
boolean m_replicationActive = false;
//Only restrict recovery completion during test
static Semaphore m_testBlockRecoveryCompletion = new Semaphore(Integer.MAX_VALUE);
private long m_executionSiteRecoveryFinish;
private long m_executionSiteRecoveryTransferred;
// Rejoin coordinator
private RejoinCoordinator m_rejoinCoordinator = null;
// id of the leader, or the host restore planner says has the catalog
int m_hostIdWithStartupCatalog;
String m_pathToStartupCatalog;
// Synchronize initialize and shutdown.
private final Object m_startAndStopLock = new Object();
// Synchronize updates of catalog contexts with context accessors.
private final Object m_catalogUpdateLock = new Object();
// add a random number to the sampler output to make it likely to be unique for this process.
private final VoltSampler m_sampler = new VoltSampler(10, "sample" + String.valueOf(new Random().nextInt() % 10000) + ".txt");
private final AtomicBoolean m_hasStartedSampler = new AtomicBoolean(false);
final VoltDBSiteFailureFaultHandler m_faultHandler = new VoltDBSiteFailureFaultHandler(this);
RestoreAgent m_restoreAgent = null;
private volatile boolean m_isRunning = false;
@Override
public boolean rejoining() { return m_rejoining; }
private long m_recoveryStartTime;
CommandLog m_commandLog;
private volatile OperationMode m_mode = OperationMode.INITIALIZING;
private OperationMode m_startMode = null;
volatile String m_localMetadata = "";
private ListeningExecutorService m_computationService;
// methods accessed via the singleton
@Override
public void startSampler() {
if (m_hasStartedSampler.compareAndSet(false, true)) {
m_sampler.start();
}
}
HeartbeatThread heartbeatThread;
private ScheduledThreadPoolExecutor m_periodicWorkThread;
// The configured license api: use to decide enterprise/cvommunity edition feature enablement
LicenseApi m_licenseApi;
@Override
public LicenseApi getLicenseApi() {
return m_licenseApi;
}
@Override
public boolean isIV2Enabled() {
return m_config.m_enableIV2;
}
/**
* Initialize all the global components, then initialize all the m_sites.
*/
@Override
public void initialize(VoltDB.Configuration config) {
synchronized(m_startAndStopLock) {
// check that this is a 64 bit VM
if (System.getProperty("java.vm.name").contains("64") == false) {
hostLog.fatal("You are running on an unsupported (probably 32 bit) JVM. Exiting.");
System.exit(-1);
}
consoleLog.l7dlog( Level.INFO, LogKeys.host_VoltDB_StartupString.name(), null);
if (config.m_enableIV2) {
consoleLog.warn("ENABLE IV2: " + config.m_enableIV2 + ". NOT SUPPORTED IN PRODUCTION.");
}
// If there's no deployment provide a default and put it under voltdbroot.
if (config.m_pathToDeployment == null) {
try {
config.m_pathToDeployment = setupDefaultDeployment();
} catch (IOException e) {
VoltDB.crashLocalVoltDB("Failed to write default deployment.", false, null);
}
}
// set the mode first thing
m_mode = OperationMode.INITIALIZING;
m_config = config;
m_startMode = null;
// set a bunch of things to null/empty/new for tests
// which reusue the process
m_clientInterfaces.clear();
m_dtxns.clear();
m_adminListener = null;
m_commandLog = new DummyCommandLog();
m_deployment = null;
m_messenger = null;
m_startMode = null;
m_statsAgent = new StatsAgent();
m_asyncCompilerAgent = new AsyncCompilerAgent();
m_faultManager = null;
m_validateConfiguredNumberOfPartitionsOnMailboxUpdate = false;
m_snapshotCompletionMonitor = null;
m_catalogContext = null;
m_partitionCountStats = null;
m_ioStats = null;
m_memoryStats = null;
m_statsManager = null;
m_restoreAgent = null;
m_siteTracker = null;
m_mailboxTracker = null;
m_recoveryStartTime = System.currentTimeMillis();
m_hostIdWithStartupCatalog = 0;
m_pathToStartupCatalog = m_config.m_pathToCatalog;
m_replicationActive = false;
// set up site structure
m_localSites = new COWMap<Long, ExecutionSite>();
m_siteThreads = new HashMap<Long, Thread>();
m_runners = new ArrayList<ExecutionSiteRunner>();
m_computationService = MoreExecutors.listeningDecorator(
Executors.newFixedThreadPool(
Math.max(2, CoreUtils.availableProcessors() / 4),
new ThreadFactory() {
private int threadIndex = 0;
@Override
public synchronized Thread newThread(Runnable r) {
Thread t = new Thread(null, r, "Computation service thread - " + threadIndex++, 131072);
t.setDaemon(true);
return t;
}
})
);
// determine if this is a rejoining node
// (used for license check and later the actual rejoin)
boolean isRejoin = false;
if (config.m_startAction == START_ACTION.REJOIN ||
config.m_startAction == START_ACTION.LIVE_REJOIN) {
isRejoin = true;
}
m_rejoining = isRejoin;
// Set std-out/err to use the UTF-8 encoding and fail if UTF-8 isn't supported
try {
System.setOut(new PrintStream(System.out, true, "UTF-8"));
System.setErr(new PrintStream(System.err, true, "UTF-8"));
} catch (UnsupportedEncodingException e) {
hostLog.fatal("Support for the UTF-8 encoding is required for VoltDB. This means you are likely running an unsupported JVM. Exiting.");
System.exit(-1);
}
m_snapshotCompletionMonitor = new SnapshotCompletionMonitor();
readBuildInfo(config.m_isEnterprise ? "Enterprise Edition" : "Community Edition");
// start up the response sampler if asked to by setting the env var
// VOLTDB_RESPONSE_SAMPLE_PATH to a valid path
ResponseSampler.initializeIfEnabled();
buildClusterMesh(isRejoin);
//Start validating the build string in the background
final Future<?> buildStringValidation = validateBuildString(getBuildString(), m_messenger.getZK());
m_mailboxPublisher = new MailboxPublisher(VoltZK.mailboxes + "/" + m_messenger.getHostId());
final int numberOfNodes = readDeploymentAndCreateStarterCatalogContext();
if (!isRejoin) {
m_messenger.waitForGroupJoin(numberOfNodes);
}
m_faultManager = new FaultDistributor(this);
m_faultManager.registerFaultHandler(SiteFailureFault.SITE_FAILURE_CATALOG,
m_faultHandler,
FaultType.SITE_FAILURE);
if (!m_faultManager.testPartitionDetectionDirectory(
m_catalogContext.cluster.getFaultsnapshots().get("CLUSTER_PARTITION"))) {
VoltDB.crashLocalVoltDB("Unable to create partition detection snapshot directory at" +
m_catalogContext.cluster.getFaultsnapshots().get("CLUSTER_PARTITION"), false, null);
}
// Create the thread pool here. It's needed by buildClusterMesh()
m_periodicWorkThread = CoreUtils.getScheduledThreadPoolExecutor("Periodic Work", 1, 1024 * 128);
m_licenseApi = MiscUtils.licenseApiFactory(m_config.m_pathToLicense);
if (m_licenseApi == null) {
VoltDB.crashLocalVoltDB("Failed to initialize license verifier. " +
"See previous log message for details.", false, null);
}
// Create the GlobalServiceElector. Do this here so we can register the MPI with it
// when we construct it below
m_globalServiceElector = new GlobalServiceElector(m_messenger.getZK(), m_messenger.getHostId());
/*
* Construct all the mailboxes for things that need to be globally addressable so they can be published
* in one atomic shot.
*
* The starting state for partition assignments are statically derived from the host id generated
* by host messenger and the k-factor/host count/sites per host. This starting state
* is published to ZK as the toplogy metadata node.
*
* On rejoin the rejoining node has to inspect the topology meta node to find out what is missing
* and then update the topology listing itself as a replacement for one of the missing host ids.
* Then it does a compare and set of the topology.
*/
ArrayDeque<Mailbox> siteMailboxes = null;
ClusterConfig clusterConfig = null;
DtxnInitiatorMailbox initiatorMailbox = null;
long initiatorHSId = 0;
JSONObject topo = getTopology(isRejoin);
try {
// IV2 mailbox stuff
if (isIV2Enabled()) {
ClusterConfig iv2config = new ClusterConfig(topo);
m_cartographer = new Cartographer(m_messenger.getZK(), iv2config.getPartitionCount());
if (isRejoin) {
List<Integer> partitionsToReplace = m_cartographer.getIv2PartitionsToReplace(topo);
m_iv2Initiators = createIv2Initiators(partitionsToReplace);
}
else {
List<Integer> partitions =
ClusterConfig.partitionsForHost(topo, m_messenger.getHostId());
m_iv2Initiators = createIv2Initiators(partitions);
}
// each node has an MPInitiator (and exactly 1 node has the master MPI).
long mpiBuddyHSId = m_iv2Initiators.get(0).getInitiatorHSId();
MpInitiator initiator = new MpInitiator(m_messenger, mpiBuddyHSId);
m_iv2Initiators.add(initiator);
m_globalServiceElector.registerService(initiator);
}
/*
* Start mailbox tracker early here because it is required
* on rejoin to find the hosts that are missing from the cluster
*/
m_mailboxTracker = new MailboxTracker(m_messenger.getZK(), this);
m_mailboxTracker.start();
/*
* Will count this down at the right point on regular startup as well as rejoin
*/
CountDownLatch rejoinCompleteLatch = new CountDownLatch(1);
Pair<ArrayDeque<Mailbox>, ClusterConfig> p;
if (isRejoin) {
/*
* Need to lock the topology metadata
* so that it can be changed atomically with publishing the mailbox node
* for this process on a rejoin.
*/
createRejoinBarrierAndWatchdog(rejoinCompleteLatch);
p = createMailboxesForSitesRejoin(topo);
} else {
p = createMailboxesForSitesStartup(topo);
}
siteMailboxes = p.getFirst();
clusterConfig = p.getSecond();
// This will set up site tracker
initiatorHSId = registerInitiatorMailbox();
final long statsHSId = m_messenger.getHSIdForLocalSite(HostMessenger.STATS_SITE_ID);
m_messenger.generateMailboxId(statsHSId);
hostLog.info("Registering stats mailbox id " + CoreUtils.hsIdToString(statsHSId));
m_mailboxPublisher.registerMailbox(MailboxType.StatsAgent, new MailboxNodeContent(statsHSId, null));
if (isRejoin && isIV2Enabled()) {
// Make a list of HDIds to rejoin
List<Long> hsidsToRejoin = new ArrayList<Long>();
for (Initiator init : m_iv2Initiators) {
if (init.isRejoinable()) {
hsidsToRejoin.add(init.getInitiatorHSId());
}
}
SnapshotSaveAPI.recoveringSiteCount.set(hsidsToRejoin.size());
hostLog.info("Set recovering site count to " + hsidsToRejoin.size());
m_rejoinCoordinator = new SequentialRejoinCoordinator(m_messenger, hsidsToRejoin,
m_catalogContext.cluster.getVoltroot());
m_messenger.registerMailbox(m_rejoinCoordinator);
hostLog.info("Using iv2 community rejoin");
}
else if (isRejoin && m_config.m_startAction == START_ACTION.LIVE_REJOIN) {
SnapshotSaveAPI.recoveringSiteCount.set(siteMailboxes.size());
hostLog.info("Set recovering site count to " + siteMailboxes.size());
// Construct and publish rejoin coordinator mailbox
ArrayList<Long> sites = new ArrayList<Long>();
for (Mailbox siteMailbox : siteMailboxes) {
sites.add(siteMailbox.getHSId());
}
m_rejoinCoordinator =
new SequentialRejoinCoordinator(m_messenger, sites, m_catalogContext.cluster.getVoltroot());
m_messenger.registerMailbox(m_rejoinCoordinator);
m_mailboxPublisher.registerMailbox(MailboxType.OTHER,
new MailboxNodeContent(m_rejoinCoordinator.getHSId(), null));
} else if (isRejoin) {
SnapshotSaveAPI.recoveringSiteCount.set(siteMailboxes.size());
}
// All mailboxes should be set up, publish it
m_mailboxPublisher.publish(m_messenger.getZK());
/*
* Now that we have published our changes to the toplogy it is safe for
* another node to come in and manipulate the toplogy metadata
*/
rejoinCompleteLatch.countDown();
if (isRejoin) {
m_messenger.getZK().delete(VoltZK.rejoinLock, -1, new ZKUtil.VoidCallback(), null);
}
} catch (Exception e) {
VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
}
/*
* Before this barrier pretty much every remotely visible mailbox id has to have been
* registered with host messenger and published with mailbox publisher
*/
boolean siteTrackerInit = false;
for (int ii = 0; ii < 4000; ii++) {
boolean predicate = true;
if (isRejoin) {
predicate = !m_siteTracker.getAllHosts().contains(m_messenger.getHostId());
} else {
predicate = m_siteTracker.getAllHosts().size() < m_deployment.getCluster().getHostcount();
}
if (predicate) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
siteTrackerInit = true;
break;
}
}
if (!siteTrackerInit) {
VoltDB.crashLocalVoltDB(
"Failed to initialize site tracker with all hosts before timeout", true, null);
}
initiatorMailbox = createInitiatorMailbox(initiatorHSId);
// do the many init tasks in the Inits class
Inits inits = new Inits(this, 1);
inits.doInitializationWork();
if (config.m_backend.isIPC) {
int eeCount = m_siteTracker.getLocalSites().length;
if (config.m_ipcPorts.size() != eeCount) {
hostLog.fatal("Specified an IPC backend but only supplied " + config.m_ipcPorts.size() +
" backend ports when " + eeCount + " are required");
System.exit(-1);
}
}
collectLocalNetworkMetadata();
/*
* Construct an adhoc planner for the initial catalog
*/
final CatalogSpecificPlanner csp = new CatalogSpecificPlanner(m_asyncCompilerAgent, m_catalogContext);
/*
* Configure and start all the IV2 sites
*/
if (isIV2Enabled()) {
try {
if (m_myHostId == 0) {
m_leaderAppointer = new LeaderAppointer(
m_messenger.getZK(),
new CountDownLatch(clusterConfig.getPartitionCount()),
m_deployment.getCluster().getKfactor(),
topo);
m_leaderAppointer.acceptPromotion();
}
for (Initiator iv2init : m_iv2Initiators) {
iv2init.configure(
getBackendTargetType(),
m_serializedCatalog,
m_catalogContext,
m_deployment.getCluster().getKfactor(),
csp,
clusterConfig.getPartitionCount(),
m_rejoining);
}
} catch (Exception e) {
Throwable toLog = e;
if (e instanceof ExecutionException) {
toLog = ((ExecutionException)e).getCause();
}
VoltDB.crashLocalVoltDB("Error configuring IV2 initiator.", true, toLog);
}
}
else {
/*
* Create execution sites runners (and threads) for all exec
* sites except the first one. This allows the sites to be set
* up in the thread that will end up running them. Cache the
* first Site from the catalog and only do the setup once the
* other threads have been started.
*/
Mailbox localThreadMailbox = siteMailboxes.poll();
((org.voltcore.messaging.SiteMailbox)localThreadMailbox).setCommandLog(m_commandLog);
m_currentThreadSite = null;
for (Mailbox mailbox : siteMailboxes) {
long site = mailbox.getHSId();
int sitesHostId = SiteTracker.getHostForSite(site);
// start a local site
if (sitesHostId == m_myHostId) {
((org.voltcore.messaging.SiteMailbox)mailbox).setCommandLog(m_commandLog);
ExecutionSiteRunner runner =
new ExecutionSiteRunner(mailbox,
m_catalogContext,
m_serializedCatalog,
m_rejoining,
m_replicationActive,
hostLog,
m_configuredNumberOfPartitions,
csp);
m_runners.add(runner);
Thread runnerThread = new Thread(runner, "Site " +
org.voltcore.utils.CoreUtils.hsIdToString(site));
runnerThread.start();
log.l7dlog(Level.TRACE, LogKeys.org_voltdb_VoltDB_CreatingThreadForSite.name(), new Object[] { site }, null);
m_siteThreads.put(site, runnerThread);
}
}
/*
* Now that the runners have been started and are doing setup of the other sites in parallel
* this thread can set up its own execution site.
*/
try {
ExecutionSite siteObj =
new ExecutionSite(VoltDB.instance(),
localThreadMailbox,
m_serializedCatalog,
null,
m_rejoining,
m_replicationActive,
m_catalogContext.m_transactionId,
m_configuredNumberOfPartitions,
csp);
m_localSites.put(localThreadMailbox.getHSId(), siteObj);
m_currentThreadSite = siteObj;
} catch (Exception e) {
VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
}
/*
* Stop and wait for the runners to finish setting up and then put
* the constructed ExecutionSites in the local site map.
*/
for (ExecutionSiteRunner runner : m_runners) {
try {
runner.m_siteIsLoaded.await();
} catch (InterruptedException e) {
VoltDB.crashLocalVoltDB("Unable to wait on starting execution site.", true, e);
}
assert(runner.m_siteObj != null);
m_localSites.put(runner.m_siteId, runner.m_siteObj);
}
}
// Start the GlobalServiceElector. Not sure where this will actually belong.
try {
m_globalServiceElector.start();
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Unable to start GlobalServiceElector", true, e);
}
/*
* At this point all of the execution sites have been published to m_localSites
* It is possible that while they were being created the mailbox tracker found additional
* sites, but was unable to deliver the notification to some or all of the execution sites.
* Since notifying them of new sites is idempotent (version number check), let's do that here so there
* are no lost updates for additional sites. But... it must be done from the
* mailbox tracker thread or there is a race with failure detection and handling.
* Generally speaking it seems like retrieving a reference to a site tracker not via a message
* from the mailbox tracker thread that builds the site tracker is bug. If it isn't delivered to you by
* a site tracker then you lose sequential consistency.
*/
try {
m_mailboxTracker.executeTask(new Runnable() {
@Override
public void run() {
for (ExecutionSite es : m_localSites.values()) {
es.notifySitesAdded(m_siteTracker);
}
}
}).get();
} catch (InterruptedException e) {
VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
} catch (ExecutionException e) {
VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
}
// Create the client interface
int portOffset = 0;
- // TODO: fix
- //for (long site : m_siteTracker.getMailboxTracker().getAllInitiators()) {
for (int i = 0; i < 1; i++) {
// create DTXN and CI for each local non-EE site
SimpleDtxnInitiator initiator =
new SimpleDtxnInitiator(initiatorMailbox,
m_catalogContext,
m_messenger,
m_myHostId,
m_myHostId, // fake initiator ID
m_config.m_timestampTestingSalt);
try {
ClientInterface ci =
ClientInterface.create(m_messenger,
m_catalogContext,
m_config.m_replicationRole,
initiator,
m_cartographer,
clusterConfig.getPartitionCount(),
config.m_port + portOffset,
config.m_adminPort + portOffset,
m_config.m_timestampTestingSalt);
portOffset += 2;
m_clientInterfaces.add(ci);
} catch (Exception e) {
VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
}
portOffset += 2;
m_dtxns.add(initiator);
}
m_partitionCountStats = new PartitionCountStats( clusterConfig.getPartitionCount());
m_statsAgent.registerStatsSource(SysProcSelector.PARTITIONCOUNT,
0, m_partitionCountStats);
m_ioStats = new IOStats();
m_statsAgent.registerStatsSource(SysProcSelector.IOSTATS,
0, m_ioStats);
m_memoryStats = new MemoryStats();
m_statsAgent.registerStatsSource(SysProcSelector.MEMORY,
0, m_memoryStats);
if (isIV2Enabled()) {
m_statsAgent.registerStatsSource(SysProcSelector.TOPO, 0, m_cartographer);
}
// Create the statistics manager and register it to JMX registry
m_statsManager = null;
try {
final Class<?> statsManagerClass =
Class.forName("org.voltdb.management.JMXStatsManager");
m_statsManager = (StatsManager)statsManagerClass.newInstance();
m_statsManager.initialize(new ArrayList<Long>(m_localSites.keySet()));
} catch (Exception e) {}
try {
m_snapshotCompletionMonitor.init(m_messenger.getZK());
} catch (Exception e) {
hostLog.fatal("Error initializing snapshot completion monitor", e);
VoltDB.crashLocalVoltDB("Error initializing snapshot completion monitor", true, e);
}
if (m_commandLog != null && isRejoin) {
m_commandLog.initForRejoin(
m_catalogContext, Long.MIN_VALUE, true);
}
/*
* Make sure the build string successfully validated
* before continuing to do operations
* that might return wrongs answers or lose data.
*/
try {
buildStringValidation.get();
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Failed to validate cluster build string", false, e);
}
if (!isRejoin) {
try {
m_messenger.waitForAllHostsToBeReady(m_deployment.getCluster().getHostcount());
} catch (Exception e) {
hostLog.fatal("Failed to announce ready state.");
VoltDB.crashLocalVoltDB("Failed to announce ready state.", false, null);
}
}
m_validateConfiguredNumberOfPartitionsOnMailboxUpdate = true;
if (m_siteTracker.m_numberOfPartitions != m_configuredNumberOfPartitions) {
for (Map.Entry<Integer, ImmutableList<Long>> entry :
m_siteTracker.m_partitionsToSitesImmutable.entrySet()) {
hostLog.info(entry.getKey() + " -- "
+ CoreUtils.hsIdCollectionToString(entry.getValue()));
}
VoltDB.crashGlobalVoltDB("Mismatch between configured number of partitions (" +
m_configuredNumberOfPartitions + ") and actual (" +
m_siteTracker.m_numberOfPartitions + ")",
true, null);
}
heartbeatThread = new HeartbeatThread(m_clientInterfaces);
heartbeatThread.start();
schedulePeriodicWorks();
// print out a bunch of useful system info
logDebuggingInfo(m_config.m_adminPort, m_config.m_httpPort, m_httpPortExtraLogMessage, m_jsonEnabled);
if (clusterConfig.getReplicationFactor() == 0) {
hostLog.warn("Running without redundancy (k=0) is not recommended for production use.");
}
assert(m_clientInterfaces.size() > 0);
ClientInterface ci = m_clientInterfaces.get(0);
ci.initializeSnapshotDaemon(m_messenger.getZK());
// set additional restore agent stuff
TransactionInitiator initiator = m_dtxns.get(0);
if (m_restoreAgent != null) {
m_restoreAgent.setCatalogContext(m_catalogContext);
m_restoreAgent.setSiteTracker(m_siteTracker);
m_restoreAgent.setInitiator(initiator);
}
}
}
private void createRejoinBarrierAndWatchdog(final CountDownLatch cdl) {
ZooKeeper zk = m_messenger.getZK();
String lockPath = null;
for (int ii = 0; ii < 120; ii++) {
try {
lockPath = zk.create(VoltZK.rejoinLock, null, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);
break;
} catch (KeeperException.NodeExistsException e) {
try {
Thread.sleep(500);
} catch (InterruptedException e1) {
throw new RuntimeException(e1);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
if (lockPath == null) {
VoltDB.crashLocalVoltDB("Unable to acquire rejoin lock in ZK, " +
"it may be necessary to delete the lock from the ZK CLI if " +
"you are sure no other rejoin is in progress", false, null);
}
new Thread() {
@Override
public void run() {
try {
if (!cdl.await(1, TimeUnit.MINUTES)) {
VoltDB.crashLocalVoltDB("Rejoin watchdog timed out after 60 seconds, rejoin hung", false, null);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
}
private Pair<ArrayDeque<Mailbox>, ClusterConfig> createMailboxesForSitesRejoin(JSONObject topology)
throws Exception
{
ZooKeeper zk = m_messenger.getZK();
ArrayDeque<Mailbox> mailboxes = new ArrayDeque<Mailbox>();
hostLog.debug(zk.getChildren("/db", false));
// We're waiting for m_mailboxTracker to start(), which will
// cause it to do an initial read of the mailboxes from ZK and
// then create a new and up-to-date m_siteTracker when handleMailboxUpdate()
// gets called
while (m_siteTracker == null) {
Thread.sleep(1);
}
Set<Integer> hostIdsInTopology = new HashSet<Integer>();
JSONArray partitions = topology.getJSONArray("partitions");
for (int ii = 0; ii < partitions.length(); ii++) {
JSONObject partition = partitions.getJSONObject(ii);
JSONArray replicas = partition.getJSONArray("replicas");
for (int zz = 0; zz < replicas.length(); zz++) {
hostIdsInTopology.add(replicas.getInt(zz));
}
}
/*
* Remove all the hosts that are still live
*/
hostIdsInTopology.removeAll(m_siteTracker.m_allHostsImmutable);
/*
* Nothing to replace!
*/
if (hostIdsInTopology.isEmpty()) {
VoltDB.crashLocalVoltDB("Rejoin failed because there is no failed node to replace", false, null);
}
Integer hostToReplace = hostIdsInTopology.iterator().next();
/*
* Log all the partitions to replicate and replace the failed host with self
*/
Set<Integer> partitionsToReplicate = new TreeSet<Integer>();
for (int ii = 0; ii < partitions.length(); ii++) {
JSONObject partition = partitions.getJSONObject(ii);
JSONArray replicas = partition.getJSONArray("replicas");
for (int zz = 0; zz < replicas.length(); zz++) {
if (replicas.getInt(zz) == hostToReplace.intValue()) {
partitionsToReplicate.add(partition.getInt("partition_id"));
replicas.put(zz, m_messenger.getHostId());
}
}
}
zk.setData(VoltZK.topology, topology.toString(4).getBytes("UTF-8"), -1, new ZKUtil.StatCallback(), null);
final int sites_per_host = topology.getInt("sites_per_host");
ClusterConfig clusterConfig = new ClusterConfig(topology);
m_configuredNumberOfPartitions = clusterConfig.getPartitionCount();
assert(partitionsToReplicate.size() == sites_per_host);
for (Integer partition : partitionsToReplicate)
{
Mailbox mailbox = m_messenger.createMailbox();
mailboxes.add(mailbox);
MailboxNodeContent mnc = new MailboxNodeContent(mailbox.getHSId(), partition);
m_mailboxPublisher.registerMailbox(MailboxType.ExecutionSite, mnc);
}
return Pair.of( mailboxes, clusterConfig);
}
private Pair<ArrayDeque<Mailbox>, ClusterConfig> createMailboxesForSitesStartup(JSONObject topo)
throws Exception
{
ArrayDeque<Mailbox> mailboxes = new ArrayDeque<Mailbox>();
ClusterConfig clusterConfig = new ClusterConfig(topo);
if (!clusterConfig.validate()) {
VoltDB.crashLocalVoltDB(clusterConfig.getErrorMsg(), false, null);
}
List<Integer> partitions =
ClusterConfig.partitionsForHost(topo, m_messenger.getHostId());
m_configuredNumberOfPartitions = clusterConfig.getPartitionCount();
assert(partitions.size() == clusterConfig.getSitesPerHost());
for (Integer partition : partitions)
{
Mailbox mailbox = m_messenger.createMailbox();
mailboxes.add(mailbox);
MailboxNodeContent mnc = new MailboxNodeContent(mailbox.getHSId(), partition);
m_mailboxPublisher.registerMailbox(MailboxType.ExecutionSite, mnc);
}
return Pair.of( mailboxes, clusterConfig);
}
// Get topology information. If rejoining, get it directly from
// ZK. Otherwise, try to do the write/read race to ZK on startup.
private JSONObject getTopology(boolean isRejoin)
{
JSONObject topo = null;
if (!isRejoin) {
int sitesperhost = m_deployment.getCluster().getSitesperhost();
int hostcount = m_deployment.getCluster().getHostcount();
int kfactor = m_deployment.getCluster().getKfactor();
ClusterConfig clusterConfig = new ClusterConfig(hostcount, sitesperhost, kfactor);
if (!clusterConfig.validate()) {
VoltDB.crashLocalVoltDB(clusterConfig.getErrorMsg(), false, null);
}
topo = registerClusterConfig(clusterConfig);
}
else {
Stat stat = new Stat();
try {
topo =
new JSONObject(new String(m_messenger.getZK().getData(VoltZK.topology, false, stat), "UTF-8"));
}
catch (Exception e) {
VoltDB.crashLocalVoltDB("Unable to get topology from ZK", true, e);
}
}
return topo;
}
private List<Initiator> createIv2Initiators(Collection<Integer> partitions)
{
List<Initiator> initiators = new ArrayList<Initiator>();
for (Integer partition : partitions)
{
Initiator initiator = new SpInitiator(m_messenger, partition);
initiators.add(initiator);
}
return initiators;
}
private JSONObject registerClusterConfig(ClusterConfig config)
{
// First, race to write the topology to ZK using Highlander rules
// (In the end, there can be only one)
JSONObject topo = null;
try
{
topo = config.getTopology(m_messenger.getLiveHostIds());
byte[] payload = topo.toString(4).getBytes("UTF-8");
m_messenger.getZK().create(VoltZK.topology, payload,
Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT);
}
catch (KeeperException.NodeExistsException nee)
{
// It's fine if we didn't win, we'll pick up the topology below
}
catch (Exception e)
{
VoltDB.crashLocalVoltDB("Unable to write topology to ZK, dying",
true, e);
}
// Then, have everyone read the topology data back from ZK
try
{
byte[] data = m_messenger.getZK().getData(VoltZK.topology, false, null);
topo = new JSONObject(new String(data, "UTF-8"));
}
catch (Exception e)
{
VoltDB.crashLocalVoltDB("Unable to read topology from ZK, dying",
true, e);
}
return topo;
}
/*
* First register, then create.
*/
private long registerInitiatorMailbox() throws Exception {
long hsid = m_messenger.generateMailboxId(null);
MailboxNodeContent mnc = new MailboxNodeContent(hsid, null);
m_mailboxPublisher.registerMailbox(MailboxType.Initiator, mnc);
return hsid;
}
private DtxnInitiatorMailbox createInitiatorMailbox(long hsid) {
Map<Long, Integer> siteMap = m_siteTracker.getSitesToPartitions();
ExecutorTxnIdSafetyState safetyState = new ExecutorTxnIdSafetyState(siteMap);
DtxnInitiatorMailbox mailbox = new DtxnInitiatorMailbox(safetyState, m_messenger);
mailbox.setHSId(hsid);
m_messenger.registerMailbox(mailbox);
return mailbox;
}
/**
* Schedule all the periodic works
*/
private void schedulePeriodicWorks() {
// JMX stats broadcast
scheduleWork(new Runnable() {
@Override
public void run() {
m_statsManager.sendNotification();
}
}, 0, StatsManager.POLL_INTERVAL, TimeUnit.MILLISECONDS);
// small stats samples
scheduleWork(new Runnable() {
@Override
public void run() {
SystemStatsCollector.asyncSampleSystemNow(false, false);
}
}, 0, 5, TimeUnit.SECONDS);
// medium stats samples
scheduleWork(new Runnable() {
@Override
public void run() {
SystemStatsCollector.asyncSampleSystemNow(true, false);
}
}, 0, 1, TimeUnit.MINUTES);
// large stats samples
scheduleWork(new Runnable() {
@Override
public void run() {
SystemStatsCollector.asyncSampleSystemNow(true, true);
}
}, 0, 6, TimeUnit.MINUTES);
}
int readDeploymentAndCreateStarterCatalogContext() {
/*
* Debate with the cluster what the deployment file should be
*/
try {
ZooKeeper zk = m_messenger.getZK();
byte deploymentBytes[] = org.voltcore.utils.CoreUtils.urlToBytes(m_config.m_pathToDeployment);
try {
if (deploymentBytes != null) {
zk.create(VoltZK.deploymentBytes, deploymentBytes, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
hostLog.info("URL of deployment info: " + m_config.m_pathToDeployment);
} else {
throw new KeeperException.NodeExistsException();
}
} catch (KeeperException.NodeExistsException e) {
byte deploymentBytesTemp[] = zk.getData(VoltZK.deploymentBytes, false, null);
if (deploymentBytesTemp == null) {
throw new RuntimeException(
"Deployment file could not be found locally or remotely at "
+ m_config.m_pathToDeployment);
}
CRC32 crc = new CRC32();
crc.update(deploymentBytes);
final long checksumHere = crc.getValue();
crc.reset();
crc.update(deploymentBytesTemp);
if (checksumHere != crc.getValue()) {
hostLog.info("Deployment configuration was pulled from ZK, and the checksum did not match " +
"the locally supplied file");
} else {
hostLog.info("Deployment configuration pulled from ZK");
}
deploymentBytes = deploymentBytesTemp;
}
m_deployment = CatalogUtil.getDeployment(new ByteArrayInputStream(deploymentBytes));
// wasn't a valid xml deployment file
if (m_deployment == null) {
hostLog.error("Not a valid XML deployment file at URL: " + m_config.m_pathToDeployment);
VoltDB.crashLocalVoltDB("Not a valid XML deployment file at URL: "
+ m_config.m_pathToDeployment, false, null);
}
// note the heatbeats are specified in seconds in xml, but ms internally
HeartbeatType hbt = m_deployment.getHeartbeat();
if (hbt != null)
m_config.m_deadHostTimeoutMS = hbt.getTimeout() * 1000;
// create a dummy catalog to load deployment info into
Catalog catalog = new Catalog();
Cluster cluster = catalog.getClusters().add("cluster");
Database db = cluster.getDatabases().add("database");
// create groups as needed for users
if (m_deployment.getUsers() != null) {
for (UsersType.User user : m_deployment.getUsers().getUser()) {
String groupsCSV = user.getGroups();
if (groupsCSV == null || groupsCSV.isEmpty()) {
continue;
}
String[] groups = groupsCSV.split(",");
for (String group : groups) {
if (db.getGroups().get(group) == null) {
db.getGroups().add(group);
}
}
}
}
long depCRC = CatalogUtil.compileDeploymentAndGetCRC(catalog, m_deployment,
true, true);
assert(depCRC != -1);
m_catalogContext = new CatalogContext(0, catalog, null, depCRC, 0, -1);
int numberOfNodes = m_deployment.getCluster().getHostcount();
if (numberOfNodes <= 0) {
hostLog.l7dlog( Level.FATAL, LogKeys.host_VoltDB_InvalidHostCount.name(),
new Object[] { numberOfNodes }, null);
VoltDB.crashLocalVoltDB("Invalid cluster size: " + numberOfNodes, false, null);
}
return numberOfNodes;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
void collectLocalNetworkMetadata() {
boolean threw = false;
JSONStringer stringer = new JSONStringer();
try {
stringer.object();
stringer.key("interfaces").array();
/*
* If no interface was specified, do a ton of work
* to identify all ipv4 or ipv6 interfaces and
* marshal them into JSON. Always put the ipv4 address first
* so that the export client will use it
*/
if (m_config.m_externalInterface.equals("")) {
LinkedList<NetworkInterface> interfaces = new LinkedList<NetworkInterface>();
try {
Enumeration<NetworkInterface> intfEnum = NetworkInterface.getNetworkInterfaces();
while (intfEnum.hasMoreElements()) {
NetworkInterface intf = intfEnum.nextElement();
if (intf.isLoopback() || !intf.isUp()) {
continue;
}
interfaces.offer(intf);
}
} catch (SocketException e) {
throw new RuntimeException(e);
}
if (interfaces.isEmpty()) {
stringer.value("localhost");
} else {
boolean addedIp = false;
while (!interfaces.isEmpty()) {
NetworkInterface intf = interfaces.poll();
Enumeration<InetAddress> inetAddrs = intf.getInetAddresses();
Inet6Address inet6addr = null;
Inet4Address inet4addr = null;
while (inetAddrs.hasMoreElements()) {
InetAddress addr = inetAddrs.nextElement();
if (addr instanceof Inet6Address) {
inet6addr = (Inet6Address)addr;
if (inet6addr.isLinkLocalAddress()) {
inet6addr = null;
}
} else if (addr instanceof Inet4Address) {
inet4addr = (Inet4Address)addr;
}
}
if (inet4addr != null) {
stringer.value(inet4addr.getHostAddress());
addedIp = true;
}
if (inet6addr != null) {
stringer.value(inet6addr.getHostAddress());
addedIp = true;
}
}
if (!addedIp) {
stringer.value("localhost");
}
}
} else {
stringer.value(m_config.m_externalInterface);
}
} catch (Exception e) {
threw = true;
hostLog.warn("Error while collecting data about local network interfaces", e);
}
try {
if (threw) {
stringer = new JSONStringer();
stringer.object();
stringer.key("interfaces").array();
stringer.value("localhost");
stringer.endArray();
} else {
stringer.endArray();
}
stringer.key("clientPort").value(m_config.m_port);
stringer.key("adminPort").value(m_config.m_adminPort);
stringer.key("httpPort").value(m_config.m_httpPort);
stringer.key("drPort").value(m_config.m_drAgentPortStart);
stringer.endObject();
JSONObject obj = new JSONObject(stringer.toString());
// possibly atomic swap from null to realz
m_localMetadata = obj.toString(4);
} catch (Exception e) {
hostLog.warn("Failed to collect data about lcoal network interfaces", e);
}
}
/**
* Start the voltcore HostMessenger. This joins the node
* to the existing cluster. In the non rejoin case, this
* function will return when the mesh is complete. If
* rejoining, it will return when the node and agreement
* site are synched to the existing cluster.
*/
void buildClusterMesh(boolean isRejoin) {
final String leaderAddress = m_config.m_leader;
String hostname = MiscUtils.getHostnameFromHostnameColonPort(leaderAddress);
int port = MiscUtils.getPortFromHostnameColonPort(leaderAddress, m_config.m_internalPort);
org.voltcore.messaging.HostMessenger.Config hmconfig;
hmconfig = new org.voltcore.messaging.HostMessenger.Config(hostname, port);
hmconfig.internalPort = m_config.m_internalPort;
hmconfig.internalInterface = m_config.m_internalInterface;
hmconfig.zkInterface = m_config.m_zkInterface;
hmconfig.deadHostTimeout = m_config.m_deadHostTimeoutMS;
hmconfig.factory = new VoltDbMessageFactory();
m_messenger = new org.voltcore.messaging.HostMessenger(hmconfig);
hostLog.info(String.format("Beginning inter-node communication on port %d.", m_config.m_internalPort));
try {
m_messenger.start();
} catch (Exception e) {
VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
}
VoltZK.createPersistentZKNodes(m_messenger.getZK());
// Use the host messenger's hostId.
m_myHostId = m_messenger.getHostId();
}
void logDebuggingInfo(int adminPort, int httpPort, String httpPortExtraLogMessage, boolean jsonEnabled) {
String startAction = m_config.m_startAction.toString();
String startActionLog = "Database start action is " + (startAction.substring(0, 1).toUpperCase() +
startAction.substring(1).toLowerCase()) + ".";
if (m_config.m_startAction == START_ACTION.START) {
startActionLog += " Will create a new database if there is nothing to recover from.";
}
if (!m_rejoining) {
hostLog.info(startActionLog);
}
// print out awesome network stuff
hostLog.info(String.format("Listening for native wire protocol clients on port %d.", m_config.m_port));
hostLog.info(String.format("Listening for admin wire protocol clients on port %d.", adminPort));
if (m_startMode == OperationMode.PAUSED) {
hostLog.info(String.format("Started in admin mode. Clients on port %d will be rejected in admin mode.", m_config.m_port));
}
if (m_config.m_replicationRole == ReplicationRole.REPLICA) {
hostLog.info("Started as " + m_config.m_replicationRole.toString().toLowerCase() + " cluster. " +
"Clients can only call read-only procedures.");
}
if (httpPortExtraLogMessage != null) {
hostLog.info(httpPortExtraLogMessage);
}
if (httpPort != -1) {
hostLog.info(String.format("Local machine HTTP monitoring is listening on port %d.", httpPort));
}
else {
hostLog.info(String.format("Local machine HTTP monitoring is disabled."));
}
if (jsonEnabled) {
hostLog.info(String.format("Json API over HTTP enabled at path /api/1.0/, listening on port %d.", httpPort));
}
else {
hostLog.info("Json API disabled.");
}
// replay command line args that we can see
List<String> iargs = ManagementFactory.getRuntimeMXBean().getInputArguments();
StringBuilder sb = new StringBuilder("Available JVM arguments:");
for (String iarg : iargs)
sb.append(" ").append(iarg);
if (iargs.size() > 0) hostLog.info(sb.toString());
else hostLog.info("No JVM command line args known.");
// java heap size
long javamaxheapmem = ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getMax();
javamaxheapmem /= (1024 * 1024);
hostLog.info(String.format("Maximum usable Java heap set to %d mb.", javamaxheapmem));
m_catalogContext.logDebuggingInfoFromCatalog();
// print out a bunch of useful system info
PlatformProperties pp = PlatformProperties.getPlatformProperties();
String[] lines = pp.toLogLines().split("\n");
for (String line : lines) {
hostLog.info(line.trim());
}
final ZooKeeper zk = m_messenger.getZK();
ZKUtil.ByteArrayCallback operationModeFuture = new ZKUtil.ByteArrayCallback();
/*
* Publish our cluster metadata, and then retrieve the metadata
* for the rest of the cluster
*/
try {
zk.create(
VoltZK.cluster_metadata + "/" + m_messenger.getHostId(),
getLocalMetadata().getBytes("UTF-8"),
Ids.OPEN_ACL_UNSAFE,
CreateMode.EPHEMERAL,
new ZKUtil.StringCallback(),
null);
zk.getData(VoltZK.operationMode, false, operationModeFuture, null);
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Error creating \"/cluster_metadata\" node in ZK", true, e);
}
Map<Integer, String> clusterMetadata = new HashMap<Integer, String>(0);
/*
* Spin and attempt to retrieve cluster metadata for all nodes in the cluster.
*/
HashSet<Integer> metadataToRetrieve = new HashSet<Integer>(m_siteTracker.getAllHosts());
metadataToRetrieve.remove(m_messenger.getHostId());
while (!metadataToRetrieve.isEmpty()) {
Map<Integer, ZKUtil.ByteArrayCallback> callbacks = new HashMap<Integer, ZKUtil.ByteArrayCallback>();
for (Integer hostId : metadataToRetrieve) {
ZKUtil.ByteArrayCallback cb = new ZKUtil.ByteArrayCallback();
zk.getData(VoltZK.cluster_metadata + "/" + hostId, false, cb, null);
callbacks.put(hostId, cb);
}
for (Map.Entry<Integer, ZKUtil.ByteArrayCallback> entry : callbacks.entrySet()) {
try {
ZKUtil.ByteArrayCallback cb = entry.getValue();
Integer hostId = entry.getKey();
clusterMetadata.put(hostId, new String(cb.getData(), "UTF-8"));
metadataToRetrieve.remove(hostId);
} catch (KeeperException.NoNodeException e) {}
catch (Exception e) {
VoltDB.crashLocalVoltDB("Error retrieving cluster metadata", true, e);
}
}
}
// print out cluster membership
hostLog.info("About to list cluster interfaces for all nodes with format [ip1 ip2 ... ipN] client-port:admin-port:http-port");
for (int hostId : m_siteTracker.getAllHosts()) {
if (hostId == m_messenger.getHostId()) {
hostLog.info(
String.format(
" Host id: %d with interfaces: %s [SELF]",
hostId,
MiscUtils.formatHostMetadataFromJSON(getLocalMetadata())));
}
else {
String hostMeta = clusterMetadata.get(hostId);
hostLog.info(
String.format(
" Host id: %d with interfaces: %s [PEER]",
hostId,
MiscUtils.formatHostMetadataFromJSON(hostMeta)));
}
}
try {
if (operationModeFuture.getData() != null) {
String operationModeStr = new String(operationModeFuture.getData(), "UTF-8");
m_startMode = OperationMode.valueOf(operationModeStr);
}
} catch (KeeperException.NoNodeException e) {}
catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String[] extractBuildInfo() {
StringBuilder sb = new StringBuilder(64);
String buildString = "VoltDB";
String versionString = m_defaultVersionString;
byte b = -1;
try {
InputStream buildstringStream =
ClassLoader.getSystemResourceAsStream("buildstring.txt");
if (buildstringStream == null) {
throw new RuntimeException("Unreadable or missing buildstring.txt file.");
}
while ((b = (byte) buildstringStream.read()) != -1) {
sb.append((char)b);
}
sb.append("\n");
String parts[] = sb.toString().split(" ", 2);
if (parts.length != 2) {
throw new RuntimeException("Invalid buildstring.txt file.");
}
versionString = parts[0].trim();
buildString = parts[1].trim();
} catch (Exception ignored) {
try {
InputStream buildstringStream = new FileInputStream("version.txt");
while ((b = (byte) buildstringStream.read()) != -1) {
sb.append((char)b);
}
versionString = sb.toString().trim();
}
catch (Exception ignored2) {
log.l7dlog( Level.ERROR, LogKeys.org_voltdb_VoltDB_FailedToRetrieveBuildString.name(), null);
}
}
return new String[] { versionString, buildString };
}
@Override
public void readBuildInfo(String editionTag) {
String buildInfo[] = extractBuildInfo();
m_versionString = buildInfo[0];
m_buildString = buildInfo[1];
consoleLog.info(String.format("Build: %s %s %s", m_versionString, m_buildString, editionTag));
}
/**
* Start all the site's event loops. That's it.
*/
@Override
public void run() {
if (!isIV2Enabled()) {
// start the separate EE threads
for (ExecutionSiteRunner r : m_runners) {
r.m_shouldStartRunning.countDown();
}
}
if (m_restoreAgent != null) {
// start restore process
m_restoreAgent.restore();
}
else {
onRestoreCompletion(Long.MIN_VALUE);
}
// Start the rejoin coordinator
if (m_rejoinCoordinator != null) {
m_rejoinCoordinator.startRejoin();
}
// start one site in the current thread
Thread.currentThread().setName("ExecutionSiteAndVoltDB");
m_isRunning = true;
try
{
if (!isIV2Enabled()) {
m_currentThreadSite.run();
}
else {
while (m_isRunning) {
Thread.sleep(3000);
}
}
}
catch (Throwable thrown)
{
String errmsg = " encountered an unexpected error and will die, taking this VoltDB node down.";
hostLog.error(errmsg);
// It's too easy for stdout to get lost, especially if we are crashing, so log FATAL, instead.
// Logging also automatically prefixes lines with "ExecutionSite [X:Y] "
// thrown.printStackTrace();
hostLog.fatal("Stack trace of thrown exception: " + thrown.toString());
for (StackTraceElement ste : thrown.getStackTrace()) {
hostLog.fatal(ste.toString());
}
VoltDB.crashLocalVoltDB(errmsg, true, thrown);
}
}
/**
* Try to shut everything down so they system is ready to call
* initialize again.
* @param mainSiteThread The thread that m_inititalized the VoltDB or
* null if called from that thread.
*/
@Override
public boolean shutdown(Thread mainSiteThread) throws InterruptedException {
synchronized(m_startAndStopLock) {
boolean did_it = false;
if (m_mode != OperationMode.SHUTTINGDOWN) {
did_it = true;
m_mode = OperationMode.SHUTTINGDOWN;
m_mailboxTracker.shutdown();
// Things are going pear-shaped, tell the fault distributor to
// shut its fat mouth
m_faultManager.shutDown();
m_snapshotCompletionMonitor.shutdown();
m_periodicWorkThread.shutdown();
heartbeatThread.interrupt();
heartbeatThread.join();
m_globalServiceElector.shutdown();
if (m_hasStartedSampler.get()) {
m_sampler.setShouldStop();
m_sampler.join();
}
// shutdown the web monitoring / json
if (m_adminListener != null)
m_adminListener.stop();
// shut down the client interface
for (ClientInterface ci : m_clientInterfaces) {
ci.shutdown();
}
// shut down Export and its connectors.
ExportManager.instance().shutdown();
if (!isIV2Enabled()) {
// tell all m_sites to stop their runloops
if (m_localSites != null) {
for (ExecutionSite site : m_localSites.values())
site.startShutdown();
}
}
// tell the iv2 sites to stop their runloop
if (m_iv2Initiators != null) {
for (Initiator init : m_iv2Initiators)
init.shutdown();
}
if (m_cartographer != null) {
m_cartographer.shutdown();
}
if (!isIV2Enabled()) {
// try to join all threads but the main one
// probably want to check if one of these is the current thread
if (m_siteThreads != null) {
for (Thread siteThread : m_siteThreads.values()) {
if (Thread.currentThread().equals(siteThread) == false) {
// don't interrupt here. the site will start shutdown when
// it sees the shutdown flag set.
siteThread.join();
}
}
}
// try to join the main thread (possibly this one)
if (mainSiteThread != null) {
if (Thread.currentThread().equals(mainSiteThread) == false) {
// don't interrupt here. the site will start shutdown when
// it sees the shutdown flag set.
mainSiteThread.join();
}
}
}
// After sites are terminated, shutdown the InvocationBufferServer.
// The IBS is shared by all sites; don't kill it while any site is active.
PartitionDRGateway.shutdown();
// help the gc along
m_localSites = null;
m_currentThreadSite = null;
m_siteThreads = null;
m_runners = null;
// shut down the network/messaging stuff
// Close the host messenger first, which should close down all of
// the ForeignHost sockets cleanly
if (m_messenger != null)
{
m_messenger.shutdown();
}
m_messenger = null;
//Also for test code that expects a fresh stats agent
if (m_statsAgent != null) {
m_statsAgent.shutdown();
m_statsAgent = null;
}
if (m_asyncCompilerAgent != null) {
m_asyncCompilerAgent.shutdown();
m_asyncCompilerAgent = null;
}
// The network iterates this list. Clear it after network's done.
m_clientInterfaces.clear();
ExportManager.instance().shutdown();
m_computationService.shutdown();
m_computationService.awaitTermination(1, TimeUnit.DAYS);
m_computationService = null;
m_siteTracker = null;
m_catalogContext = null;
m_mailboxPublisher = null;
// probably unnecessary
System.gc();
m_isRunning = false;
}
return did_it;
}
}
/** Last transaction ID at which the logging config updated.
* Also, use the intrinsic lock to safeguard access from multiple
* execution site threads */
private static Long lastLogUpdate_txnId = 0L;
@Override
synchronized public void logUpdate(String xmlConfig, long currentTxnId)
{
// another site already did this work.
if (currentTxnId == lastLogUpdate_txnId) {
return;
}
else if (currentTxnId < lastLogUpdate_txnId) {
throw new RuntimeException(
"Trying to update logging config at transaction " + lastLogUpdate_txnId
+ " with an older transaction: " + currentTxnId);
}
hostLog.info("Updating RealVoltDB logging config from txnid: " +
lastLogUpdate_txnId + " to " + currentTxnId);
lastLogUpdate_txnId = currentTxnId;
VoltLogger.configure(xmlConfig);
}
/** Struct to associate a context with a counter of served sites */
private static class ContextTracker {
ContextTracker(CatalogContext context, CatalogSpecificPlanner csp) {
m_dispensedSites = 1;
m_context = context;
m_csp = csp;
}
long m_dispensedSites;
final CatalogContext m_context;
final CatalogSpecificPlanner m_csp;
}
/** Associate transaction ids to contexts */
private final HashMap<Long, ContextTracker>m_txnIdToContextTracker =
new HashMap<Long, ContextTracker>();
@Override
public Pair<CatalogContext, CatalogSpecificPlanner> catalogUpdate(
String diffCommands,
byte[] newCatalogBytes,
int expectedCatalogVersion,
long currentTxnId,
long deploymentCRC)
{
synchronized(m_catalogUpdateLock) {
// A site is catching up with catalog updates
if (currentTxnId <= m_catalogContext.m_transactionId && !m_txnIdToContextTracker.isEmpty()) {
ContextTracker contextTracker = m_txnIdToContextTracker.get(currentTxnId);
// This 'dispensed' concept is a little crazy fragile. Maybe it would be better
// to keep a rolling N catalogs? Or perhaps to keep catalogs for N minutes? Open
// to opinions here.
contextTracker.m_dispensedSites++;
int ttlsites = m_siteTracker.getSitesForHost(m_messenger.getHostId()).size();
if (contextTracker.m_dispensedSites == ttlsites) {
m_txnIdToContextTracker.remove(currentTxnId);
}
return Pair.of( contextTracker.m_context, contextTracker.m_csp);
}
else if (m_catalogContext.catalogVersion != expectedCatalogVersion) {
throw new RuntimeException("Trying to update main catalog context with diff " +
"commands generated for an out-of date catalog. Expected catalog version: " +
expectedCatalogVersion + " does not match actual version: " + m_catalogContext.catalogVersion);
}
// 0. A new catalog! Update the global context and the context tracker
m_catalogContext =
m_catalogContext.update(currentTxnId, newCatalogBytes, diffCommands, true, deploymentCRC);
final CatalogSpecificPlanner csp = new CatalogSpecificPlanner( m_asyncCompilerAgent, m_catalogContext);
m_txnIdToContextTracker.put(currentTxnId,
new ContextTracker(
m_catalogContext,
csp));
m_catalogContext.logDebuggingInfoFromCatalog();
// 1. update the export manager.
ExportManager.instance().updateCatalog(m_catalogContext);
// 2. update client interface (asynchronously)
// CI in turn updates the planner thread.
for (ClientInterface ci : m_clientInterfaces) {
ci.notifyOfCatalogUpdate();
}
// 3. update HTTPClientInterface (asynchronously)
// This purges cached connection state so that access with
// stale auth info is prevented.
if (m_adminListener != null)
{
m_adminListener.notifyOfCatalogUpdate();
}
return Pair.of(m_catalogContext, csp);
}
}
@Override
public VoltDB.Configuration getConfig() {
return m_config;
}
@Override
public String getBuildString() {
return m_buildString;
}
@Override
public String getVersionString() {
return m_versionString;
}
@Override
public HostMessenger getHostMessenger() {
return m_messenger;
}
@Override
public ArrayList<ClientInterface> getClientInterfaces() {
return m_clientInterfaces;
}
@Override
public Map<Long, ExecutionSite> getLocalSites() {
return m_localSites;
}
@Override
public StatsAgent getStatsAgent() {
return m_statsAgent;
}
@Override
public MemoryStats getMemoryStatsSource() {
return m_memoryStats;
}
@Override
public FaultDistributorInterface getFaultDistributor()
{
return m_faultManager;
}
@Override
public CatalogContext getCatalogContext() {
synchronized(m_catalogUpdateLock) {
return m_catalogContext;
}
}
/**
* Tells if the VoltDB is running. m_isRunning needs to be set to true
* when the run() method is called, and set to false when shutting down.
*
* @return true if the VoltDB is running.
*/
@Override
public boolean isRunning() {
return m_isRunning;
}
/**
* Debugging function - creates a record of the current state of the system.
* @param out PrintStream to write report to.
*/
public void createRuntimeReport(PrintStream out) {
// This function may be running in its own thread.
out.print("MIME-Version: 1.0\n");
out.print("Content-type: multipart/mixed; boundary=\"reportsection\"");
out.print("\n\n--reportsection\nContent-Type: text/plain\n\nClientInterface Report\n");
for (ClientInterface ci : getClientInterfaces()) {
out.print(ci.toString() + "\n");
}
out.print("\n\n--reportsection\nContent-Type: text/plain\n\nLocalSite Report\n");
for(ExecutionSite es : getLocalSites().values()) {
out.print(es.toString() + "\n");
}
out.print("\n\n--reportsection--");
}
@Override
public BackendTarget getBackendTargetType() {
return m_config.m_backend;
}
@Override
public synchronized void onExecutionSiteRejoinCompletion(long transferred) {
m_executionSiteRecoveryFinish = System.currentTimeMillis();
m_executionSiteRecoveryTransferred = transferred;
onRejoinCompletion();
}
private void onRejoinCompletion() {
// null out the rejoin coordinator
if (m_rejoinCoordinator != null) {
m_rejoinCoordinator.close();
}
m_rejoinCoordinator = null;
try {
m_testBlockRecoveryCompletion.acquire();
} catch (InterruptedException e) {}
final long delta = ((m_executionSiteRecoveryFinish - m_recoveryStartTime) / 1000);
final long megabytes = m_executionSiteRecoveryTransferred / (1024 * 1024);
final double megabytesPerSecond = megabytes / ((m_executionSiteRecoveryFinish - m_recoveryStartTime) / 1000.0);
for (ClientInterface intf : getClientInterfaces()) {
intf.mayActivateSnapshotDaemon();
try {
intf.startAcceptingConnections();
} catch (IOException e) {
hostLog.l7dlog(Level.FATAL,
LogKeys.host_VoltDB_ErrorStartAcceptingConnections.name(),
e);
VoltDB.crashLocalVoltDB("Error starting client interface.", true, e);
}
}
if (m_config.m_startAction == START_ACTION.REJOIN) {
consoleLog.info(
"Node data recovery completed after " + delta + " seconds with " + megabytes +
" megabytes transferred at a rate of " +
megabytesPerSecond + " megabytes/sec");
}
try {
final ZooKeeper zk = m_messenger.getZK();
boolean logRecoveryCompleted = false;
if (getCommandLog().getClass().getName().equals("org.voltdb.CommandLogImpl")) {
try {
zk.create(VoltZK.request_truncation_snapshot, null, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
} catch (KeeperException.NodeExistsException e) {}
} else {
logRecoveryCompleted = true;
}
if (logRecoveryCompleted) {
m_rejoining = false;
consoleLog.info("Node rejoin completed");
}
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Unable to log host rejoin completion to ZK", true, e);
}
hostLog.info("Logging host rejoin completion to ZK");
}
@Override
public CommandLog getCommandLog() {
return m_commandLog;
}
@Override
public OperationMode getMode()
{
return m_mode;
}
@Override
public void setMode(OperationMode mode)
{
if (m_mode != mode)
{
if (mode == OperationMode.PAUSED)
{
hostLog.info("Server is entering admin mode and pausing.");
}
else if (m_mode == OperationMode.PAUSED)
{
hostLog.info("Server is exiting admin mode and resuming operation.");
}
}
m_mode = mode;
}
@Override
public void setStartMode(OperationMode mode) {
m_startMode = mode;
}
@Override
public OperationMode getStartMode()
{
return m_startMode;
}
@Override
public void setReplicationRole(ReplicationRole role)
{
if (role == ReplicationRole.NONE && m_config.m_replicationRole == ReplicationRole.REPLICA) {
consoleLog.info("Promoting replication role from replica to master.");
}
m_config.m_replicationRole = role;
for (ClientInterface ci : m_clientInterfaces) {
ci.setReplicationRole(m_config.m_replicationRole);
}
}
@Override
public ReplicationRole getReplicationRole()
{
return m_config.m_replicationRole;
}
/**
* Metadata is a JSON object
*/
@Override
public String getLocalMetadata() {
return m_localMetadata;
}
@Override
public void onRestoreCompletion(long txnId) {
/*
* Command log is already initialized if this is a rejoin
*/
if ((m_commandLog != null) && (m_commandLog.needsInitialization())) {
// Initialize command logger
m_commandLog.init(m_catalogContext, txnId);
}
/*
* Enable the initiator to send normal heartbeats and accept client
* connections
*/
for (SimpleDtxnInitiator dtxn : m_dtxns) {
dtxn.setSendHeartbeats(true);
}
if (!m_rejoining) {
for (ClientInterface ci : m_clientInterfaces) {
try {
ci.startAcceptingConnections();
} catch (IOException e) {
hostLog.l7dlog(Level.FATAL,
LogKeys.host_VoltDB_ErrorStartAcceptingConnections.name(),
e);
VoltDB.crashLocalVoltDB("Error starting client interface.", true, e);
}
}
}
// Start listening on the DR ports
prepareReplication();
if (m_startMode != null) {
m_mode = m_startMode;
} else {
// Shouldn't be here, but to be safe
m_mode = OperationMode.RUNNING;
}
consoleLog.l7dlog( Level.INFO, LogKeys.host_VoltDB_ServerCompletedInitialization.name(), null);
}
@Override
public SnapshotCompletionMonitor getSnapshotCompletionMonitor() {
return m_snapshotCompletionMonitor;
}
@Override
public synchronized void recoveryComplete() {
m_rejoining = false;
consoleLog.info("Node rejoin completed");
}
@Override
public ScheduledFuture<?> scheduleWork(Runnable work,
long initialDelay,
long delay,
TimeUnit unit) {
if (delay > 0) {
return m_periodicWorkThread.scheduleWithFixedDelay(work,
initialDelay, delay,
unit);
} else {
return m_periodicWorkThread.schedule(work, initialDelay, unit);
}
}
@Override
public ListeningExecutorService getComputationService() {
return m_computationService;
}
private void prepareReplication() {
if (m_localSites != null && !m_localSites.isEmpty()) {
// get any site and start the DR server, it's static
ExecutionSite site = m_localSites.values().iterator().next();
site.getPartitionDRGateway().start();
}
}
@Override
public void setReplicationActive(boolean active)
{
if (m_replicationActive != active) {
m_replicationActive = active;
if (m_localSites != null) {
for (ExecutionSite s : m_localSites.values()) {
s.getPartitionDRGateway().setActive(active);
}
}
}
}
@Override
public boolean getReplicationActive()
{
return m_replicationActive;
}
@Override
public void handleMailboxUpdate(Map<MailboxType, List<MailboxNodeContent>> mailboxes) {
SiteTracker oldTracker = m_siteTracker;
m_siteTracker = new SiteTracker(m_myHostId, mailboxes, oldTracker != null ? oldTracker.m_version + 1 : 0);
if (!isIV2Enabled()) {
if (m_validateConfiguredNumberOfPartitionsOnMailboxUpdate) {
if (m_siteTracker.m_numberOfPartitions != m_configuredNumberOfPartitions) {
VoltDB.crashGlobalVoltDB(
"Configured number of partitions " + m_configuredNumberOfPartitions +
" is not the same as the number of partitions present " + m_siteTracker.m_numberOfPartitions,
true, null);
}
if (m_siteTracker.m_numberOfPartitions != oldTracker.m_numberOfPartitions) {
VoltDB.crashGlobalVoltDB(
"Configured number of partitions in new tracker" + m_siteTracker.m_numberOfPartitions +
" is not the same as the number of partitions present " + oldTracker.m_numberOfPartitions,
true, null);
}
}
if (oldTracker != null) {
/*
* Handle node failures first, then node additions. It is NOT
* guaranteed that if a node failure and a node addition happen
* concurrently, they'll appear separately in two watch fires,
* because the new tracker contains the most up-to-date view of the
* mailboxes, which may contain both changes. Consequently, we have
* to handle both cases here.
*/
HashSet<Long> deltaRemoved = new HashSet<Long>(oldTracker.m_allSitesImmutable);
deltaRemoved.removeAll(m_siteTracker.m_allSitesImmutable);
if (!deltaRemoved.isEmpty()) {
m_faultManager.reportFault(new SiteFailureFault(new ArrayList<Long>(deltaRemoved)));
}
HashSet<Long> deltaAdded = new HashSet<Long>(m_siteTracker.m_allSitesImmutable);
deltaAdded.removeAll(oldTracker.m_allSitesImmutable);
if (!deltaAdded.isEmpty()) {
for (SimpleDtxnInitiator dtxn : m_dtxns)
{
Set<Long> copy = new HashSet<Long>(m_siteTracker.m_allExecutionSitesImmutable);
copy.retainAll(deltaAdded);
dtxn.notifyExecutionSiteRejoin(new ArrayList<Long>(copy));
}
for (ExecutionSite es : getLocalSites().values()) {
es.notifySitesAdded(m_siteTracker);
}
if (ExportManager.instance() != null) {
//Notify the export manager the cluster topology has changed
ExportManager.instance().notifyOfClusterTopologyChange();
}
}
}
}
}
@Override
public SiteTracker getSiteTracker() {
return m_siteTracker;
}
@Override
public SiteTracker getSiteTrackerForSnapshot()
{
if (isIV2Enabled()) {
return new SiteTracker(m_messenger.getHostId(), m_cartographer.getSiteTrackerMailboxMap(), 0);
}
else {
return m_siteTracker;
}
}
@Override
public MailboxPublisher getMailboxPublisher() {
return m_mailboxPublisher;
}
/**
* Create default deployment.xml file in voltdbroot if the deployment path is null.
*
* @return path to default deployment file
* @throws IOException
*/
static String setupDefaultDeployment() throws IOException {
// Since there's apparently no deployment to override the path to voltdbroot it should be
// safe to assume it's under the working directory.
// CatalogUtil.getVoltDbRoot() creates the voltdbroot directory as needed.
File voltDbRoot = CatalogUtil.getVoltDbRoot(null);
String pathToDeployment = voltDbRoot.getPath() + File.separator + "deployment.xml";
File deploymentXMLFile = new File(pathToDeployment);
hostLog.info("Generating default deployment file \"" + deploymentXMLFile.getAbsolutePath() + "\"");
BufferedWriter bw = new BufferedWriter(new FileWriter(deploymentXMLFile));
for (String line : defaultDeploymentXML) {
bw.write(line);
bw.newLine();
}
bw.flush();
bw.close();
return deploymentXMLFile.getAbsolutePath();
}
/*
* Validate the build string with the rest of the cluster
* by racing to publish it to ZK and then comparing the one this process
* has to the one in ZK. They should all match. The method returns a future
* so that init can continue while the ZK call is pending since it ZK is pretty
* slow.
*/
private Future<?> validateBuildString(final String buildString, ZooKeeper zk) {
final SettableFuture<Object> retval = SettableFuture.create();
byte buildStringBytes[] = null;
try {
buildStringBytes = buildString.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new AssertionError(e);
}
final byte buildStringBytesFinal[] = buildStringBytes;
//Can use a void callback because ZK will execute the create and then the get in order
//It's a race so it doesn't have to succeed
zk.create(
VoltZK.buildstring,
buildStringBytes,
Ids.OPEN_ACL_UNSAFE,
CreateMode.PERSISTENT,
new ZKUtil.StringCallback(),
null);
zk.getData(VoltZK.buildstring, false, new org.apache.zookeeper_voltpatches.AsyncCallback.DataCallback() {
@Override
public void processResult(int rc, String path, Object ctx,
byte[] data, Stat stat) {
KeeperException.Code code = KeeperException.Code.get(rc);
if (code == KeeperException.Code.OK) {
if (Arrays.equals(buildStringBytesFinal, data)) {
retval.set(null);
} else {
try {
VoltDB.crashGlobalVoltDB("Local build string \"" + buildString +
"\" does not match cluster build string \"" +
new String(data, "UTF-8") + "\"", false, null);
} catch (UnsupportedEncodingException e) {
retval.setException(new AssertionError(e));
}
}
} else {
retval.setException(KeeperException.create(code));
}
}
}, null);
return retval;
}
}
| true | true | public void initialize(VoltDB.Configuration config) {
synchronized(m_startAndStopLock) {
// check that this is a 64 bit VM
if (System.getProperty("java.vm.name").contains("64") == false) {
hostLog.fatal("You are running on an unsupported (probably 32 bit) JVM. Exiting.");
System.exit(-1);
}
consoleLog.l7dlog( Level.INFO, LogKeys.host_VoltDB_StartupString.name(), null);
if (config.m_enableIV2) {
consoleLog.warn("ENABLE IV2: " + config.m_enableIV2 + ". NOT SUPPORTED IN PRODUCTION.");
}
// If there's no deployment provide a default and put it under voltdbroot.
if (config.m_pathToDeployment == null) {
try {
config.m_pathToDeployment = setupDefaultDeployment();
} catch (IOException e) {
VoltDB.crashLocalVoltDB("Failed to write default deployment.", false, null);
}
}
// set the mode first thing
m_mode = OperationMode.INITIALIZING;
m_config = config;
m_startMode = null;
// set a bunch of things to null/empty/new for tests
// which reusue the process
m_clientInterfaces.clear();
m_dtxns.clear();
m_adminListener = null;
m_commandLog = new DummyCommandLog();
m_deployment = null;
m_messenger = null;
m_startMode = null;
m_statsAgent = new StatsAgent();
m_asyncCompilerAgent = new AsyncCompilerAgent();
m_faultManager = null;
m_validateConfiguredNumberOfPartitionsOnMailboxUpdate = false;
m_snapshotCompletionMonitor = null;
m_catalogContext = null;
m_partitionCountStats = null;
m_ioStats = null;
m_memoryStats = null;
m_statsManager = null;
m_restoreAgent = null;
m_siteTracker = null;
m_mailboxTracker = null;
m_recoveryStartTime = System.currentTimeMillis();
m_hostIdWithStartupCatalog = 0;
m_pathToStartupCatalog = m_config.m_pathToCatalog;
m_replicationActive = false;
// set up site structure
m_localSites = new COWMap<Long, ExecutionSite>();
m_siteThreads = new HashMap<Long, Thread>();
m_runners = new ArrayList<ExecutionSiteRunner>();
m_computationService = MoreExecutors.listeningDecorator(
Executors.newFixedThreadPool(
Math.max(2, CoreUtils.availableProcessors() / 4),
new ThreadFactory() {
private int threadIndex = 0;
@Override
public synchronized Thread newThread(Runnable r) {
Thread t = new Thread(null, r, "Computation service thread - " + threadIndex++, 131072);
t.setDaemon(true);
return t;
}
})
);
// determine if this is a rejoining node
// (used for license check and later the actual rejoin)
boolean isRejoin = false;
if (config.m_startAction == START_ACTION.REJOIN ||
config.m_startAction == START_ACTION.LIVE_REJOIN) {
isRejoin = true;
}
m_rejoining = isRejoin;
// Set std-out/err to use the UTF-8 encoding and fail if UTF-8 isn't supported
try {
System.setOut(new PrintStream(System.out, true, "UTF-8"));
System.setErr(new PrintStream(System.err, true, "UTF-8"));
} catch (UnsupportedEncodingException e) {
hostLog.fatal("Support for the UTF-8 encoding is required for VoltDB. This means you are likely running an unsupported JVM. Exiting.");
System.exit(-1);
}
m_snapshotCompletionMonitor = new SnapshotCompletionMonitor();
readBuildInfo(config.m_isEnterprise ? "Enterprise Edition" : "Community Edition");
// start up the response sampler if asked to by setting the env var
// VOLTDB_RESPONSE_SAMPLE_PATH to a valid path
ResponseSampler.initializeIfEnabled();
buildClusterMesh(isRejoin);
//Start validating the build string in the background
final Future<?> buildStringValidation = validateBuildString(getBuildString(), m_messenger.getZK());
m_mailboxPublisher = new MailboxPublisher(VoltZK.mailboxes + "/" + m_messenger.getHostId());
final int numberOfNodes = readDeploymentAndCreateStarterCatalogContext();
if (!isRejoin) {
m_messenger.waitForGroupJoin(numberOfNodes);
}
m_faultManager = new FaultDistributor(this);
m_faultManager.registerFaultHandler(SiteFailureFault.SITE_FAILURE_CATALOG,
m_faultHandler,
FaultType.SITE_FAILURE);
if (!m_faultManager.testPartitionDetectionDirectory(
m_catalogContext.cluster.getFaultsnapshots().get("CLUSTER_PARTITION"))) {
VoltDB.crashLocalVoltDB("Unable to create partition detection snapshot directory at" +
m_catalogContext.cluster.getFaultsnapshots().get("CLUSTER_PARTITION"), false, null);
}
// Create the thread pool here. It's needed by buildClusterMesh()
m_periodicWorkThread = CoreUtils.getScheduledThreadPoolExecutor("Periodic Work", 1, 1024 * 128);
m_licenseApi = MiscUtils.licenseApiFactory(m_config.m_pathToLicense);
if (m_licenseApi == null) {
VoltDB.crashLocalVoltDB("Failed to initialize license verifier. " +
"See previous log message for details.", false, null);
}
// Create the GlobalServiceElector. Do this here so we can register the MPI with it
// when we construct it below
m_globalServiceElector = new GlobalServiceElector(m_messenger.getZK(), m_messenger.getHostId());
/*
* Construct all the mailboxes for things that need to be globally addressable so they can be published
* in one atomic shot.
*
* The starting state for partition assignments are statically derived from the host id generated
* by host messenger and the k-factor/host count/sites per host. This starting state
* is published to ZK as the toplogy metadata node.
*
* On rejoin the rejoining node has to inspect the topology meta node to find out what is missing
* and then update the topology listing itself as a replacement for one of the missing host ids.
* Then it does a compare and set of the topology.
*/
ArrayDeque<Mailbox> siteMailboxes = null;
ClusterConfig clusterConfig = null;
DtxnInitiatorMailbox initiatorMailbox = null;
long initiatorHSId = 0;
JSONObject topo = getTopology(isRejoin);
try {
// IV2 mailbox stuff
if (isIV2Enabled()) {
ClusterConfig iv2config = new ClusterConfig(topo);
m_cartographer = new Cartographer(m_messenger.getZK(), iv2config.getPartitionCount());
if (isRejoin) {
List<Integer> partitionsToReplace = m_cartographer.getIv2PartitionsToReplace(topo);
m_iv2Initiators = createIv2Initiators(partitionsToReplace);
}
else {
List<Integer> partitions =
ClusterConfig.partitionsForHost(topo, m_messenger.getHostId());
m_iv2Initiators = createIv2Initiators(partitions);
}
// each node has an MPInitiator (and exactly 1 node has the master MPI).
long mpiBuddyHSId = m_iv2Initiators.get(0).getInitiatorHSId();
MpInitiator initiator = new MpInitiator(m_messenger, mpiBuddyHSId);
m_iv2Initiators.add(initiator);
m_globalServiceElector.registerService(initiator);
}
/*
* Start mailbox tracker early here because it is required
* on rejoin to find the hosts that are missing from the cluster
*/
m_mailboxTracker = new MailboxTracker(m_messenger.getZK(), this);
m_mailboxTracker.start();
/*
* Will count this down at the right point on regular startup as well as rejoin
*/
CountDownLatch rejoinCompleteLatch = new CountDownLatch(1);
Pair<ArrayDeque<Mailbox>, ClusterConfig> p;
if (isRejoin) {
/*
* Need to lock the topology metadata
* so that it can be changed atomically with publishing the mailbox node
* for this process on a rejoin.
*/
createRejoinBarrierAndWatchdog(rejoinCompleteLatch);
p = createMailboxesForSitesRejoin(topo);
} else {
p = createMailboxesForSitesStartup(topo);
}
siteMailboxes = p.getFirst();
clusterConfig = p.getSecond();
// This will set up site tracker
initiatorHSId = registerInitiatorMailbox();
final long statsHSId = m_messenger.getHSIdForLocalSite(HostMessenger.STATS_SITE_ID);
m_messenger.generateMailboxId(statsHSId);
hostLog.info("Registering stats mailbox id " + CoreUtils.hsIdToString(statsHSId));
m_mailboxPublisher.registerMailbox(MailboxType.StatsAgent, new MailboxNodeContent(statsHSId, null));
if (isRejoin && isIV2Enabled()) {
// Make a list of HDIds to rejoin
List<Long> hsidsToRejoin = new ArrayList<Long>();
for (Initiator init : m_iv2Initiators) {
if (init.isRejoinable()) {
hsidsToRejoin.add(init.getInitiatorHSId());
}
}
SnapshotSaveAPI.recoveringSiteCount.set(hsidsToRejoin.size());
hostLog.info("Set recovering site count to " + hsidsToRejoin.size());
m_rejoinCoordinator = new SequentialRejoinCoordinator(m_messenger, hsidsToRejoin,
m_catalogContext.cluster.getVoltroot());
m_messenger.registerMailbox(m_rejoinCoordinator);
hostLog.info("Using iv2 community rejoin");
}
else if (isRejoin && m_config.m_startAction == START_ACTION.LIVE_REJOIN) {
SnapshotSaveAPI.recoveringSiteCount.set(siteMailboxes.size());
hostLog.info("Set recovering site count to " + siteMailboxes.size());
// Construct and publish rejoin coordinator mailbox
ArrayList<Long> sites = new ArrayList<Long>();
for (Mailbox siteMailbox : siteMailboxes) {
sites.add(siteMailbox.getHSId());
}
m_rejoinCoordinator =
new SequentialRejoinCoordinator(m_messenger, sites, m_catalogContext.cluster.getVoltroot());
m_messenger.registerMailbox(m_rejoinCoordinator);
m_mailboxPublisher.registerMailbox(MailboxType.OTHER,
new MailboxNodeContent(m_rejoinCoordinator.getHSId(), null));
} else if (isRejoin) {
SnapshotSaveAPI.recoveringSiteCount.set(siteMailboxes.size());
}
// All mailboxes should be set up, publish it
m_mailboxPublisher.publish(m_messenger.getZK());
/*
* Now that we have published our changes to the toplogy it is safe for
* another node to come in and manipulate the toplogy metadata
*/
rejoinCompleteLatch.countDown();
if (isRejoin) {
m_messenger.getZK().delete(VoltZK.rejoinLock, -1, new ZKUtil.VoidCallback(), null);
}
} catch (Exception e) {
VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
}
/*
* Before this barrier pretty much every remotely visible mailbox id has to have been
* registered with host messenger and published with mailbox publisher
*/
boolean siteTrackerInit = false;
for (int ii = 0; ii < 4000; ii++) {
boolean predicate = true;
if (isRejoin) {
predicate = !m_siteTracker.getAllHosts().contains(m_messenger.getHostId());
} else {
predicate = m_siteTracker.getAllHosts().size() < m_deployment.getCluster().getHostcount();
}
if (predicate) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
siteTrackerInit = true;
break;
}
}
if (!siteTrackerInit) {
VoltDB.crashLocalVoltDB(
"Failed to initialize site tracker with all hosts before timeout", true, null);
}
initiatorMailbox = createInitiatorMailbox(initiatorHSId);
// do the many init tasks in the Inits class
Inits inits = new Inits(this, 1);
inits.doInitializationWork();
if (config.m_backend.isIPC) {
int eeCount = m_siteTracker.getLocalSites().length;
if (config.m_ipcPorts.size() != eeCount) {
hostLog.fatal("Specified an IPC backend but only supplied " + config.m_ipcPorts.size() +
" backend ports when " + eeCount + " are required");
System.exit(-1);
}
}
collectLocalNetworkMetadata();
/*
* Construct an adhoc planner for the initial catalog
*/
final CatalogSpecificPlanner csp = new CatalogSpecificPlanner(m_asyncCompilerAgent, m_catalogContext);
/*
* Configure and start all the IV2 sites
*/
if (isIV2Enabled()) {
try {
if (m_myHostId == 0) {
m_leaderAppointer = new LeaderAppointer(
m_messenger.getZK(),
new CountDownLatch(clusterConfig.getPartitionCount()),
m_deployment.getCluster().getKfactor(),
topo);
m_leaderAppointer.acceptPromotion();
}
for (Initiator iv2init : m_iv2Initiators) {
iv2init.configure(
getBackendTargetType(),
m_serializedCatalog,
m_catalogContext,
m_deployment.getCluster().getKfactor(),
csp,
clusterConfig.getPartitionCount(),
m_rejoining);
}
} catch (Exception e) {
Throwable toLog = e;
if (e instanceof ExecutionException) {
toLog = ((ExecutionException)e).getCause();
}
VoltDB.crashLocalVoltDB("Error configuring IV2 initiator.", true, toLog);
}
}
else {
/*
* Create execution sites runners (and threads) for all exec
* sites except the first one. This allows the sites to be set
* up in the thread that will end up running them. Cache the
* first Site from the catalog and only do the setup once the
* other threads have been started.
*/
Mailbox localThreadMailbox = siteMailboxes.poll();
((org.voltcore.messaging.SiteMailbox)localThreadMailbox).setCommandLog(m_commandLog);
m_currentThreadSite = null;
for (Mailbox mailbox : siteMailboxes) {
long site = mailbox.getHSId();
int sitesHostId = SiteTracker.getHostForSite(site);
// start a local site
if (sitesHostId == m_myHostId) {
((org.voltcore.messaging.SiteMailbox)mailbox).setCommandLog(m_commandLog);
ExecutionSiteRunner runner =
new ExecutionSiteRunner(mailbox,
m_catalogContext,
m_serializedCatalog,
m_rejoining,
m_replicationActive,
hostLog,
m_configuredNumberOfPartitions,
csp);
m_runners.add(runner);
Thread runnerThread = new Thread(runner, "Site " +
org.voltcore.utils.CoreUtils.hsIdToString(site));
runnerThread.start();
log.l7dlog(Level.TRACE, LogKeys.org_voltdb_VoltDB_CreatingThreadForSite.name(), new Object[] { site }, null);
m_siteThreads.put(site, runnerThread);
}
}
/*
* Now that the runners have been started and are doing setup of the other sites in parallel
* this thread can set up its own execution site.
*/
try {
ExecutionSite siteObj =
new ExecutionSite(VoltDB.instance(),
localThreadMailbox,
m_serializedCatalog,
null,
m_rejoining,
m_replicationActive,
m_catalogContext.m_transactionId,
m_configuredNumberOfPartitions,
csp);
m_localSites.put(localThreadMailbox.getHSId(), siteObj);
m_currentThreadSite = siteObj;
} catch (Exception e) {
VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
}
/*
* Stop and wait for the runners to finish setting up and then put
* the constructed ExecutionSites in the local site map.
*/
for (ExecutionSiteRunner runner : m_runners) {
try {
runner.m_siteIsLoaded.await();
} catch (InterruptedException e) {
VoltDB.crashLocalVoltDB("Unable to wait on starting execution site.", true, e);
}
assert(runner.m_siteObj != null);
m_localSites.put(runner.m_siteId, runner.m_siteObj);
}
}
// Start the GlobalServiceElector. Not sure where this will actually belong.
try {
m_globalServiceElector.start();
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Unable to start GlobalServiceElector", true, e);
}
/*
* At this point all of the execution sites have been published to m_localSites
* It is possible that while they were being created the mailbox tracker found additional
* sites, but was unable to deliver the notification to some or all of the execution sites.
* Since notifying them of new sites is idempotent (version number check), let's do that here so there
* are no lost updates for additional sites. But... it must be done from the
* mailbox tracker thread or there is a race with failure detection and handling.
* Generally speaking it seems like retrieving a reference to a site tracker not via a message
* from the mailbox tracker thread that builds the site tracker is bug. If it isn't delivered to you by
* a site tracker then you lose sequential consistency.
*/
try {
m_mailboxTracker.executeTask(new Runnable() {
@Override
public void run() {
for (ExecutionSite es : m_localSites.values()) {
es.notifySitesAdded(m_siteTracker);
}
}
}).get();
} catch (InterruptedException e) {
VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
} catch (ExecutionException e) {
VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
}
// Create the client interface
int portOffset = 0;
// TODO: fix
//for (long site : m_siteTracker.getMailboxTracker().getAllInitiators()) {
for (int i = 0; i < 1; i++) {
// create DTXN and CI for each local non-EE site
SimpleDtxnInitiator initiator =
new SimpleDtxnInitiator(initiatorMailbox,
m_catalogContext,
m_messenger,
m_myHostId,
m_myHostId, // fake initiator ID
m_config.m_timestampTestingSalt);
try {
ClientInterface ci =
ClientInterface.create(m_messenger,
m_catalogContext,
m_config.m_replicationRole,
initiator,
m_cartographer,
clusterConfig.getPartitionCount(),
config.m_port + portOffset,
config.m_adminPort + portOffset,
m_config.m_timestampTestingSalt);
portOffset += 2;
m_clientInterfaces.add(ci);
} catch (Exception e) {
VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
}
portOffset += 2;
m_dtxns.add(initiator);
}
m_partitionCountStats = new PartitionCountStats( clusterConfig.getPartitionCount());
m_statsAgent.registerStatsSource(SysProcSelector.PARTITIONCOUNT,
0, m_partitionCountStats);
m_ioStats = new IOStats();
m_statsAgent.registerStatsSource(SysProcSelector.IOSTATS,
0, m_ioStats);
m_memoryStats = new MemoryStats();
m_statsAgent.registerStatsSource(SysProcSelector.MEMORY,
0, m_memoryStats);
if (isIV2Enabled()) {
m_statsAgent.registerStatsSource(SysProcSelector.TOPO, 0, m_cartographer);
}
// Create the statistics manager and register it to JMX registry
m_statsManager = null;
try {
final Class<?> statsManagerClass =
Class.forName("org.voltdb.management.JMXStatsManager");
m_statsManager = (StatsManager)statsManagerClass.newInstance();
m_statsManager.initialize(new ArrayList<Long>(m_localSites.keySet()));
} catch (Exception e) {}
try {
m_snapshotCompletionMonitor.init(m_messenger.getZK());
} catch (Exception e) {
hostLog.fatal("Error initializing snapshot completion monitor", e);
VoltDB.crashLocalVoltDB("Error initializing snapshot completion monitor", true, e);
}
if (m_commandLog != null && isRejoin) {
m_commandLog.initForRejoin(
m_catalogContext, Long.MIN_VALUE, true);
}
/*
* Make sure the build string successfully validated
* before continuing to do operations
* that might return wrongs answers or lose data.
*/
try {
buildStringValidation.get();
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Failed to validate cluster build string", false, e);
}
if (!isRejoin) {
try {
m_messenger.waitForAllHostsToBeReady(m_deployment.getCluster().getHostcount());
} catch (Exception e) {
hostLog.fatal("Failed to announce ready state.");
VoltDB.crashLocalVoltDB("Failed to announce ready state.", false, null);
}
}
m_validateConfiguredNumberOfPartitionsOnMailboxUpdate = true;
if (m_siteTracker.m_numberOfPartitions != m_configuredNumberOfPartitions) {
for (Map.Entry<Integer, ImmutableList<Long>> entry :
m_siteTracker.m_partitionsToSitesImmutable.entrySet()) {
hostLog.info(entry.getKey() + " -- "
+ CoreUtils.hsIdCollectionToString(entry.getValue()));
}
VoltDB.crashGlobalVoltDB("Mismatch between configured number of partitions (" +
m_configuredNumberOfPartitions + ") and actual (" +
m_siteTracker.m_numberOfPartitions + ")",
true, null);
}
heartbeatThread = new HeartbeatThread(m_clientInterfaces);
heartbeatThread.start();
schedulePeriodicWorks();
// print out a bunch of useful system info
logDebuggingInfo(m_config.m_adminPort, m_config.m_httpPort, m_httpPortExtraLogMessage, m_jsonEnabled);
if (clusterConfig.getReplicationFactor() == 0) {
hostLog.warn("Running without redundancy (k=0) is not recommended for production use.");
}
assert(m_clientInterfaces.size() > 0);
ClientInterface ci = m_clientInterfaces.get(0);
ci.initializeSnapshotDaemon(m_messenger.getZK());
// set additional restore agent stuff
TransactionInitiator initiator = m_dtxns.get(0);
if (m_restoreAgent != null) {
m_restoreAgent.setCatalogContext(m_catalogContext);
m_restoreAgent.setSiteTracker(m_siteTracker);
m_restoreAgent.setInitiator(initiator);
}
}
}
| public void initialize(VoltDB.Configuration config) {
synchronized(m_startAndStopLock) {
// check that this is a 64 bit VM
if (System.getProperty("java.vm.name").contains("64") == false) {
hostLog.fatal("You are running on an unsupported (probably 32 bit) JVM. Exiting.");
System.exit(-1);
}
consoleLog.l7dlog( Level.INFO, LogKeys.host_VoltDB_StartupString.name(), null);
if (config.m_enableIV2) {
consoleLog.warn("ENABLE IV2: " + config.m_enableIV2 + ". NOT SUPPORTED IN PRODUCTION.");
}
// If there's no deployment provide a default and put it under voltdbroot.
if (config.m_pathToDeployment == null) {
try {
config.m_pathToDeployment = setupDefaultDeployment();
} catch (IOException e) {
VoltDB.crashLocalVoltDB("Failed to write default deployment.", false, null);
}
}
// set the mode first thing
m_mode = OperationMode.INITIALIZING;
m_config = config;
m_startMode = null;
// set a bunch of things to null/empty/new for tests
// which reusue the process
m_clientInterfaces.clear();
m_dtxns.clear();
m_adminListener = null;
m_commandLog = new DummyCommandLog();
m_deployment = null;
m_messenger = null;
m_startMode = null;
m_statsAgent = new StatsAgent();
m_asyncCompilerAgent = new AsyncCompilerAgent();
m_faultManager = null;
m_validateConfiguredNumberOfPartitionsOnMailboxUpdate = false;
m_snapshotCompletionMonitor = null;
m_catalogContext = null;
m_partitionCountStats = null;
m_ioStats = null;
m_memoryStats = null;
m_statsManager = null;
m_restoreAgent = null;
m_siteTracker = null;
m_mailboxTracker = null;
m_recoveryStartTime = System.currentTimeMillis();
m_hostIdWithStartupCatalog = 0;
m_pathToStartupCatalog = m_config.m_pathToCatalog;
m_replicationActive = false;
// set up site structure
m_localSites = new COWMap<Long, ExecutionSite>();
m_siteThreads = new HashMap<Long, Thread>();
m_runners = new ArrayList<ExecutionSiteRunner>();
m_computationService = MoreExecutors.listeningDecorator(
Executors.newFixedThreadPool(
Math.max(2, CoreUtils.availableProcessors() / 4),
new ThreadFactory() {
private int threadIndex = 0;
@Override
public synchronized Thread newThread(Runnable r) {
Thread t = new Thread(null, r, "Computation service thread - " + threadIndex++, 131072);
t.setDaemon(true);
return t;
}
})
);
// determine if this is a rejoining node
// (used for license check and later the actual rejoin)
boolean isRejoin = false;
if (config.m_startAction == START_ACTION.REJOIN ||
config.m_startAction == START_ACTION.LIVE_REJOIN) {
isRejoin = true;
}
m_rejoining = isRejoin;
// Set std-out/err to use the UTF-8 encoding and fail if UTF-8 isn't supported
try {
System.setOut(new PrintStream(System.out, true, "UTF-8"));
System.setErr(new PrintStream(System.err, true, "UTF-8"));
} catch (UnsupportedEncodingException e) {
hostLog.fatal("Support for the UTF-8 encoding is required for VoltDB. This means you are likely running an unsupported JVM. Exiting.");
System.exit(-1);
}
m_snapshotCompletionMonitor = new SnapshotCompletionMonitor();
readBuildInfo(config.m_isEnterprise ? "Enterprise Edition" : "Community Edition");
// start up the response sampler if asked to by setting the env var
// VOLTDB_RESPONSE_SAMPLE_PATH to a valid path
ResponseSampler.initializeIfEnabled();
buildClusterMesh(isRejoin);
//Start validating the build string in the background
final Future<?> buildStringValidation = validateBuildString(getBuildString(), m_messenger.getZK());
m_mailboxPublisher = new MailboxPublisher(VoltZK.mailboxes + "/" + m_messenger.getHostId());
final int numberOfNodes = readDeploymentAndCreateStarterCatalogContext();
if (!isRejoin) {
m_messenger.waitForGroupJoin(numberOfNodes);
}
m_faultManager = new FaultDistributor(this);
m_faultManager.registerFaultHandler(SiteFailureFault.SITE_FAILURE_CATALOG,
m_faultHandler,
FaultType.SITE_FAILURE);
if (!m_faultManager.testPartitionDetectionDirectory(
m_catalogContext.cluster.getFaultsnapshots().get("CLUSTER_PARTITION"))) {
VoltDB.crashLocalVoltDB("Unable to create partition detection snapshot directory at" +
m_catalogContext.cluster.getFaultsnapshots().get("CLUSTER_PARTITION"), false, null);
}
// Create the thread pool here. It's needed by buildClusterMesh()
m_periodicWorkThread = CoreUtils.getScheduledThreadPoolExecutor("Periodic Work", 1, 1024 * 128);
m_licenseApi = MiscUtils.licenseApiFactory(m_config.m_pathToLicense);
if (m_licenseApi == null) {
VoltDB.crashLocalVoltDB("Failed to initialize license verifier. " +
"See previous log message for details.", false, null);
}
// Create the GlobalServiceElector. Do this here so we can register the MPI with it
// when we construct it below
m_globalServiceElector = new GlobalServiceElector(m_messenger.getZK(), m_messenger.getHostId());
/*
* Construct all the mailboxes for things that need to be globally addressable so they can be published
* in one atomic shot.
*
* The starting state for partition assignments are statically derived from the host id generated
* by host messenger and the k-factor/host count/sites per host. This starting state
* is published to ZK as the toplogy metadata node.
*
* On rejoin the rejoining node has to inspect the topology meta node to find out what is missing
* and then update the topology listing itself as a replacement for one of the missing host ids.
* Then it does a compare and set of the topology.
*/
ArrayDeque<Mailbox> siteMailboxes = null;
ClusterConfig clusterConfig = null;
DtxnInitiatorMailbox initiatorMailbox = null;
long initiatorHSId = 0;
JSONObject topo = getTopology(isRejoin);
try {
// IV2 mailbox stuff
if (isIV2Enabled()) {
ClusterConfig iv2config = new ClusterConfig(topo);
m_cartographer = new Cartographer(m_messenger.getZK(), iv2config.getPartitionCount());
if (isRejoin) {
List<Integer> partitionsToReplace = m_cartographer.getIv2PartitionsToReplace(topo);
m_iv2Initiators = createIv2Initiators(partitionsToReplace);
}
else {
List<Integer> partitions =
ClusterConfig.partitionsForHost(topo, m_messenger.getHostId());
m_iv2Initiators = createIv2Initiators(partitions);
}
// each node has an MPInitiator (and exactly 1 node has the master MPI).
long mpiBuddyHSId = m_iv2Initiators.get(0).getInitiatorHSId();
MpInitiator initiator = new MpInitiator(m_messenger, mpiBuddyHSId);
m_iv2Initiators.add(initiator);
m_globalServiceElector.registerService(initiator);
}
/*
* Start mailbox tracker early here because it is required
* on rejoin to find the hosts that are missing from the cluster
*/
m_mailboxTracker = new MailboxTracker(m_messenger.getZK(), this);
m_mailboxTracker.start();
/*
* Will count this down at the right point on regular startup as well as rejoin
*/
CountDownLatch rejoinCompleteLatch = new CountDownLatch(1);
Pair<ArrayDeque<Mailbox>, ClusterConfig> p;
if (isRejoin) {
/*
* Need to lock the topology metadata
* so that it can be changed atomically with publishing the mailbox node
* for this process on a rejoin.
*/
createRejoinBarrierAndWatchdog(rejoinCompleteLatch);
p = createMailboxesForSitesRejoin(topo);
} else {
p = createMailboxesForSitesStartup(topo);
}
siteMailboxes = p.getFirst();
clusterConfig = p.getSecond();
// This will set up site tracker
initiatorHSId = registerInitiatorMailbox();
final long statsHSId = m_messenger.getHSIdForLocalSite(HostMessenger.STATS_SITE_ID);
m_messenger.generateMailboxId(statsHSId);
hostLog.info("Registering stats mailbox id " + CoreUtils.hsIdToString(statsHSId));
m_mailboxPublisher.registerMailbox(MailboxType.StatsAgent, new MailboxNodeContent(statsHSId, null));
if (isRejoin && isIV2Enabled()) {
// Make a list of HDIds to rejoin
List<Long> hsidsToRejoin = new ArrayList<Long>();
for (Initiator init : m_iv2Initiators) {
if (init.isRejoinable()) {
hsidsToRejoin.add(init.getInitiatorHSId());
}
}
SnapshotSaveAPI.recoveringSiteCount.set(hsidsToRejoin.size());
hostLog.info("Set recovering site count to " + hsidsToRejoin.size());
m_rejoinCoordinator = new SequentialRejoinCoordinator(m_messenger, hsidsToRejoin,
m_catalogContext.cluster.getVoltroot());
m_messenger.registerMailbox(m_rejoinCoordinator);
hostLog.info("Using iv2 community rejoin");
}
else if (isRejoin && m_config.m_startAction == START_ACTION.LIVE_REJOIN) {
SnapshotSaveAPI.recoveringSiteCount.set(siteMailboxes.size());
hostLog.info("Set recovering site count to " + siteMailboxes.size());
// Construct and publish rejoin coordinator mailbox
ArrayList<Long> sites = new ArrayList<Long>();
for (Mailbox siteMailbox : siteMailboxes) {
sites.add(siteMailbox.getHSId());
}
m_rejoinCoordinator =
new SequentialRejoinCoordinator(m_messenger, sites, m_catalogContext.cluster.getVoltroot());
m_messenger.registerMailbox(m_rejoinCoordinator);
m_mailboxPublisher.registerMailbox(MailboxType.OTHER,
new MailboxNodeContent(m_rejoinCoordinator.getHSId(), null));
} else if (isRejoin) {
SnapshotSaveAPI.recoveringSiteCount.set(siteMailboxes.size());
}
// All mailboxes should be set up, publish it
m_mailboxPublisher.publish(m_messenger.getZK());
/*
* Now that we have published our changes to the toplogy it is safe for
* another node to come in and manipulate the toplogy metadata
*/
rejoinCompleteLatch.countDown();
if (isRejoin) {
m_messenger.getZK().delete(VoltZK.rejoinLock, -1, new ZKUtil.VoidCallback(), null);
}
} catch (Exception e) {
VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
}
/*
* Before this barrier pretty much every remotely visible mailbox id has to have been
* registered with host messenger and published with mailbox publisher
*/
boolean siteTrackerInit = false;
for (int ii = 0; ii < 4000; ii++) {
boolean predicate = true;
if (isRejoin) {
predicate = !m_siteTracker.getAllHosts().contains(m_messenger.getHostId());
} else {
predicate = m_siteTracker.getAllHosts().size() < m_deployment.getCluster().getHostcount();
}
if (predicate) {
try {
Thread.sleep(5);
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
siteTrackerInit = true;
break;
}
}
if (!siteTrackerInit) {
VoltDB.crashLocalVoltDB(
"Failed to initialize site tracker with all hosts before timeout", true, null);
}
initiatorMailbox = createInitiatorMailbox(initiatorHSId);
// do the many init tasks in the Inits class
Inits inits = new Inits(this, 1);
inits.doInitializationWork();
if (config.m_backend.isIPC) {
int eeCount = m_siteTracker.getLocalSites().length;
if (config.m_ipcPorts.size() != eeCount) {
hostLog.fatal("Specified an IPC backend but only supplied " + config.m_ipcPorts.size() +
" backend ports when " + eeCount + " are required");
System.exit(-1);
}
}
collectLocalNetworkMetadata();
/*
* Construct an adhoc planner for the initial catalog
*/
final CatalogSpecificPlanner csp = new CatalogSpecificPlanner(m_asyncCompilerAgent, m_catalogContext);
/*
* Configure and start all the IV2 sites
*/
if (isIV2Enabled()) {
try {
if (m_myHostId == 0) {
m_leaderAppointer = new LeaderAppointer(
m_messenger.getZK(),
new CountDownLatch(clusterConfig.getPartitionCount()),
m_deployment.getCluster().getKfactor(),
topo);
m_leaderAppointer.acceptPromotion();
}
for (Initiator iv2init : m_iv2Initiators) {
iv2init.configure(
getBackendTargetType(),
m_serializedCatalog,
m_catalogContext,
m_deployment.getCluster().getKfactor(),
csp,
clusterConfig.getPartitionCount(),
m_rejoining);
}
} catch (Exception e) {
Throwable toLog = e;
if (e instanceof ExecutionException) {
toLog = ((ExecutionException)e).getCause();
}
VoltDB.crashLocalVoltDB("Error configuring IV2 initiator.", true, toLog);
}
}
else {
/*
* Create execution sites runners (and threads) for all exec
* sites except the first one. This allows the sites to be set
* up in the thread that will end up running them. Cache the
* first Site from the catalog and only do the setup once the
* other threads have been started.
*/
Mailbox localThreadMailbox = siteMailboxes.poll();
((org.voltcore.messaging.SiteMailbox)localThreadMailbox).setCommandLog(m_commandLog);
m_currentThreadSite = null;
for (Mailbox mailbox : siteMailboxes) {
long site = mailbox.getHSId();
int sitesHostId = SiteTracker.getHostForSite(site);
// start a local site
if (sitesHostId == m_myHostId) {
((org.voltcore.messaging.SiteMailbox)mailbox).setCommandLog(m_commandLog);
ExecutionSiteRunner runner =
new ExecutionSiteRunner(mailbox,
m_catalogContext,
m_serializedCatalog,
m_rejoining,
m_replicationActive,
hostLog,
m_configuredNumberOfPartitions,
csp);
m_runners.add(runner);
Thread runnerThread = new Thread(runner, "Site " +
org.voltcore.utils.CoreUtils.hsIdToString(site));
runnerThread.start();
log.l7dlog(Level.TRACE, LogKeys.org_voltdb_VoltDB_CreatingThreadForSite.name(), new Object[] { site }, null);
m_siteThreads.put(site, runnerThread);
}
}
/*
* Now that the runners have been started and are doing setup of the other sites in parallel
* this thread can set up its own execution site.
*/
try {
ExecutionSite siteObj =
new ExecutionSite(VoltDB.instance(),
localThreadMailbox,
m_serializedCatalog,
null,
m_rejoining,
m_replicationActive,
m_catalogContext.m_transactionId,
m_configuredNumberOfPartitions,
csp);
m_localSites.put(localThreadMailbox.getHSId(), siteObj);
m_currentThreadSite = siteObj;
} catch (Exception e) {
VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
}
/*
* Stop and wait for the runners to finish setting up and then put
* the constructed ExecutionSites in the local site map.
*/
for (ExecutionSiteRunner runner : m_runners) {
try {
runner.m_siteIsLoaded.await();
} catch (InterruptedException e) {
VoltDB.crashLocalVoltDB("Unable to wait on starting execution site.", true, e);
}
assert(runner.m_siteObj != null);
m_localSites.put(runner.m_siteId, runner.m_siteObj);
}
}
// Start the GlobalServiceElector. Not sure where this will actually belong.
try {
m_globalServiceElector.start();
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Unable to start GlobalServiceElector", true, e);
}
/*
* At this point all of the execution sites have been published to m_localSites
* It is possible that while they were being created the mailbox tracker found additional
* sites, but was unable to deliver the notification to some or all of the execution sites.
* Since notifying them of new sites is idempotent (version number check), let's do that here so there
* are no lost updates for additional sites. But... it must be done from the
* mailbox tracker thread or there is a race with failure detection and handling.
* Generally speaking it seems like retrieving a reference to a site tracker not via a message
* from the mailbox tracker thread that builds the site tracker is bug. If it isn't delivered to you by
* a site tracker then you lose sequential consistency.
*/
try {
m_mailboxTracker.executeTask(new Runnable() {
@Override
public void run() {
for (ExecutionSite es : m_localSites.values()) {
es.notifySitesAdded(m_siteTracker);
}
}
}).get();
} catch (InterruptedException e) {
VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
} catch (ExecutionException e) {
VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
}
// Create the client interface
int portOffset = 0;
for (int i = 0; i < 1; i++) {
// create DTXN and CI for each local non-EE site
SimpleDtxnInitiator initiator =
new SimpleDtxnInitiator(initiatorMailbox,
m_catalogContext,
m_messenger,
m_myHostId,
m_myHostId, // fake initiator ID
m_config.m_timestampTestingSalt);
try {
ClientInterface ci =
ClientInterface.create(m_messenger,
m_catalogContext,
m_config.m_replicationRole,
initiator,
m_cartographer,
clusterConfig.getPartitionCount(),
config.m_port + portOffset,
config.m_adminPort + portOffset,
m_config.m_timestampTestingSalt);
portOffset += 2;
m_clientInterfaces.add(ci);
} catch (Exception e) {
VoltDB.crashLocalVoltDB(e.getMessage(), true, e);
}
portOffset += 2;
m_dtxns.add(initiator);
}
m_partitionCountStats = new PartitionCountStats( clusterConfig.getPartitionCount());
m_statsAgent.registerStatsSource(SysProcSelector.PARTITIONCOUNT,
0, m_partitionCountStats);
m_ioStats = new IOStats();
m_statsAgent.registerStatsSource(SysProcSelector.IOSTATS,
0, m_ioStats);
m_memoryStats = new MemoryStats();
m_statsAgent.registerStatsSource(SysProcSelector.MEMORY,
0, m_memoryStats);
if (isIV2Enabled()) {
m_statsAgent.registerStatsSource(SysProcSelector.TOPO, 0, m_cartographer);
}
// Create the statistics manager and register it to JMX registry
m_statsManager = null;
try {
final Class<?> statsManagerClass =
Class.forName("org.voltdb.management.JMXStatsManager");
m_statsManager = (StatsManager)statsManagerClass.newInstance();
m_statsManager.initialize(new ArrayList<Long>(m_localSites.keySet()));
} catch (Exception e) {}
try {
m_snapshotCompletionMonitor.init(m_messenger.getZK());
} catch (Exception e) {
hostLog.fatal("Error initializing snapshot completion monitor", e);
VoltDB.crashLocalVoltDB("Error initializing snapshot completion monitor", true, e);
}
if (m_commandLog != null && isRejoin) {
m_commandLog.initForRejoin(
m_catalogContext, Long.MIN_VALUE, true);
}
/*
* Make sure the build string successfully validated
* before continuing to do operations
* that might return wrongs answers or lose data.
*/
try {
buildStringValidation.get();
} catch (Exception e) {
VoltDB.crashLocalVoltDB("Failed to validate cluster build string", false, e);
}
if (!isRejoin) {
try {
m_messenger.waitForAllHostsToBeReady(m_deployment.getCluster().getHostcount());
} catch (Exception e) {
hostLog.fatal("Failed to announce ready state.");
VoltDB.crashLocalVoltDB("Failed to announce ready state.", false, null);
}
}
m_validateConfiguredNumberOfPartitionsOnMailboxUpdate = true;
if (m_siteTracker.m_numberOfPartitions != m_configuredNumberOfPartitions) {
for (Map.Entry<Integer, ImmutableList<Long>> entry :
m_siteTracker.m_partitionsToSitesImmutable.entrySet()) {
hostLog.info(entry.getKey() + " -- "
+ CoreUtils.hsIdCollectionToString(entry.getValue()));
}
VoltDB.crashGlobalVoltDB("Mismatch between configured number of partitions (" +
m_configuredNumberOfPartitions + ") and actual (" +
m_siteTracker.m_numberOfPartitions + ")",
true, null);
}
heartbeatThread = new HeartbeatThread(m_clientInterfaces);
heartbeatThread.start();
schedulePeriodicWorks();
// print out a bunch of useful system info
logDebuggingInfo(m_config.m_adminPort, m_config.m_httpPort, m_httpPortExtraLogMessage, m_jsonEnabled);
if (clusterConfig.getReplicationFactor() == 0) {
hostLog.warn("Running without redundancy (k=0) is not recommended for production use.");
}
assert(m_clientInterfaces.size() > 0);
ClientInterface ci = m_clientInterfaces.get(0);
ci.initializeSnapshotDaemon(m_messenger.getZK());
// set additional restore agent stuff
TransactionInitiator initiator = m_dtxns.get(0);
if (m_restoreAgent != null) {
m_restoreAgent.setCatalogContext(m_catalogContext);
m_restoreAgent.setSiteTracker(m_siteTracker);
m_restoreAgent.setInitiator(initiator);
}
}
}
|
diff --git a/src/main/java/com/attask/jenkins/ScriptBuilder.java b/src/main/java/com/attask/jenkins/ScriptBuilder.java
index 5243ff5..cc33076 100644
--- a/src/main/java/com/attask/jenkins/ScriptBuilder.java
+++ b/src/main/java/com/attask/jenkins/ScriptBuilder.java
@@ -1,369 +1,369 @@
package com.attask.jenkins;
import hudson.*;
import hudson.model.*;
import hudson.tasks.*;
import hudson.tasks.Messages;
import hudson.util.ListBoxModel;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.StaplerRequest;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.util.*;
/**
* User: Joel Johnson
* Date: 8/29/12
* Time: 5:23 PM
*/
@ExportedBean
public class ScriptBuilder extends Builder {
public static final boolean CONTINUE = true;
public static final boolean ABORT = false;
private final String scriptName; //will be an absolute path
private final List<Parameter> parameters;
private final boolean abortOnFailure;
private final ErrorMode errorMode;
private final String errorRange;
private final ErrorMode unstableMode;
private final String unstableRange;
private final String injectProperties;
private final boolean runOnMaster;
@DataBoundConstructor
public ScriptBuilder(String scriptName, List<Parameter> parameters, boolean abortOnFailure, ErrorMode errorMode, String errorRange, ErrorMode unstableMode, String unstableRange, String injectProperties, boolean runOnMaster) {
this.scriptName = scriptName;
if (parameters == null) {
this.parameters = Collections.emptyList();
} else {
this.parameters = Collections.unmodifiableList(new ArrayList<Parameter>(parameters));
}
this.abortOnFailure = abortOnFailure;
this.errorMode = errorMode;
this.errorRange = errorRange;
this.unstableMode = unstableMode;
this.unstableRange = unstableRange;
this.injectProperties = injectProperties;
this.runOnMaster = runOnMaster;
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, final BuildListener listener) throws InterruptedException, IOException {
return runScript(build, launcher, listener);
}
private boolean runScript(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws IOException, InterruptedException {
Result result;
final Map<String, Script> runnableScripts = findRunnableScripts();
Script script = runnableScripts.get(scriptName);
if (script != null) {
//If we want to run it on master, do so. But if the job is already running on master, just run it as if the run on master flag isn't set.
if (this.runOnMaster && !(launcher instanceof Launcher.LocalLauncher)) {
FilePath workspace = Jenkins.getInstance().getRootPath().createTempDir("Workspace", "Temp");
try {
Launcher masterLauncher = new Launcher.RemoteLauncher(listener, workspace.getChannel(), true);
result = execute(build, masterLauncher, listener, script);
} finally {
workspace.deleteRecursive();
}
} else {
result = execute(build, launcher, listener, script);
}
} else {
listener.error("'" + scriptName + "' doesn't exist anymore. Failing.");
result = Result.FAILURE;
}
injectProperties(build, listener);
build.setResult(result);
boolean failed = result.isWorseOrEqualTo(Result.FAILURE);
if(failed) {
if(abortOnFailure) {
listener.getLogger().println("Abort on Failure is enabled: Aborting.");
return ABORT;
} else {
listener.getLogger().println("Abort on Failure is disabled: Continuing.");
return CONTINUE;
}
} else {
return CONTINUE;
}
}
private Map<String, String> injectParameters(List<Parameter> parameters, EnvVars envVars) {
Map<String, String> result = new HashMap<String, String>();
for (Parameter parameter : parameters) {
String key = parameter.getParameterKey();
String value = envVars.expand(parameter.getParameterValue());
result.put(key, value);
}
return result;
}
private Result execute(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener, Script script) throws IOException, InterruptedException {
String scriptContents = script.findScriptContents();
int exitCode;
CommandInterpreter commandInterpreter;
if (launcher.isUnix()) {
commandInterpreter = new Shell(scriptContents);
} else {
commandInterpreter = new BatchFile(scriptContents);
}
PrintStream logger = listener.getLogger();
logger.println("========================================");
logger.println("Executing: " + script.getFile().getName());
logger.println("----------------------------------------");
long startTime = System.currentTimeMillis();
exitCode = executeScript(build, launcher, listener, commandInterpreter);
long runTime = System.currentTimeMillis() - startTime;
Result result = ExitCodeParser.findResult(exitCode, errorMode, errorRange, unstableMode, unstableRange);
logger.println("----------------------------------------");
logger.println(script.getFile().getName() + " finished in " + runTime + "ms.");
logger.println("Exit code was " + exitCode + ". " + result + ".");
return result;
}
/**
* <p>
* This method is simply an inline of
* {@link CommandInterpreter#perform(hudson.model.AbstractBuild, hudson.Launcher, hudson.model.TaskListener)},
* but returning the exit code instead of a boolean.
* Also, I've cleaned up the code a bit.
* Tried to remove any inspection warnings, renamed variables so they would be useful, and added curly braces.
* </p>
* <p>
* If that method ever gets updated, this one should be too.
* Obviously the better solution is to change the CommandInterpreter to have two public methods,
* one that returns the integer value.
* </p>
* <p>
* The reason I do this is because the exit code provides useful user customization.
* So now the user can define if the script fails or goes unstable or even remains successful for certain exit codes.
* </p>
*/
private int executeScript(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener, CommandInterpreter command) throws InterruptedException, IOException {
FilePath ws = build.getWorkspace();
FilePath script = null;
try {
try {
script = command.createScriptFile(ws);
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError(Messages.CommandInterpreter_UnableToProduceScript()));
return -2;
}
int exitCode;
try {
EnvVars envVars = build.getEnvironment(listener);
Map<String, String> varsToInject = injectParameters(parameters, envVars);
envVars.putAll(varsToInject);
- envVars.put("BUILD_RESULT", build.getResult().toString());
+ envVars.put("BUILD_RESULT", String.valueOf(build.getResult()));
// on Windows environment variables are converted to all upper case,
// but no such conversions are done on Unix, so to make this cross-platform,
// convert variables to all upper cases.
for (Map.Entry<String, String> e : build.getBuildVariables().entrySet()) {
envVars.put(e.getKey(), e.getValue());
}
exitCode = launcher.launch().cmds(command.buildCommandLine(script)).envs(envVars).stdout(listener).pwd(ws).join();
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError(Messages.CommandInterpreter_CommandFailed()));
throw e;
}
return exitCode;
} finally {
try {
if (script != null) {
script.delete();
}
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError(Messages.CommandInterpreter_UnableToDelete(script)));
}
}
}
private void injectProperties(AbstractBuild<?, ?> build, BuildListener listener) throws IOException {
PrintStream logger = listener.getLogger();
if (getInjectProperties() != null && !getInjectProperties().isEmpty()) {
logger.println("injecting properties from " + getInjectProperties());
FilePath filePath = new FilePath(build.getWorkspace(), getInjectProperties());
Properties injectedProperties = new Properties();
InputStream read = filePath.read();
try {
injectedProperties.load(read);
} finally {
read.close();
}
Map<String, String> result = new HashMap<String, String>(injectedProperties.size());
for (Map.Entry<Object, Object> entry : injectedProperties.entrySet()) {
logger.println("\t" + entry.getKey() + " => " + entry.getValue());
result.put(String.valueOf(entry.getKey()), String.valueOf(entry.getValue()));
}
build.addAction(new InjectPropertiesAction(result));
}
logger.println("========================================");
logger.println();
}
@Exported
public String getScriptName() {
return scriptName;
}
@Exported
public List<Parameter> getParameters() {
return parameters;
}
@Exported
public boolean getAbortOnFailure() {
return abortOnFailure;
}
@Exported
public ErrorMode getErrorMode() {
return errorMode;
}
@Exported
public String getErrorRange() {
return errorRange;
}
@Exported
public ErrorMode getUnstableMode() {
return unstableMode;
}
@Exported
public String getUnstableRange() {
return unstableRange;
}
@Exported
public String getInjectProperties() {
return injectProperties;
}
/**
* If true the script runs on the master node in a temporary directory rather than on the machine the build is running on.
*/
@Exported
public boolean getRunOnMaster() {
return runOnMaster;
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
public Map<String, Script> findRunnableScripts() throws IOException, InterruptedException {
FilePath rootPath = Jenkins.getInstance().getRootPath();
FilePath userContent = new FilePath(rootPath, "userContent");
DescriptorImpl descriptor = getDescriptor();
return descriptor.findRunnableScripts(userContent);
}
@Extension
public static final class DescriptorImpl extends BuildStepDescriptor<Builder> {
public String fileTypes;
@Override
public boolean configure(StaplerRequest request, JSONObject formData) throws FormException {
fileTypes = formData.getString("fileTypes");
save();
return super.configure(request, formData);
}
public String getFileTypes() {
load();
if (fileTypes == null || fileTypes.isEmpty()) {
return ".*";
}
return fileTypes;
}
@Exported
public ListBoxModel doFillScriptNameItems() {
FilePath rootPath = Jenkins.getInstance().getRootPath();
FilePath userContent = new FilePath(rootPath, "userContent");
ListBoxModel items = new ListBoxModel();
for (Script script : findRunnableScripts(userContent).values()) {
//Pretty up the name
String path = script.getFile().getRemote();
path = path.substring(userContent.getRemote().length() + 1);
items.add(path, script.getFile().getRemote());
}
return items;
}
@Exported
public String getGuid() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
private Map<String, Script> findRunnableScripts(FilePath userContent) {
final List<String> fileTypes = Arrays.asList(this.getFileTypes().split("\\s+"));
try {
return userContent.act(new FindScriptsOnMaster(userContent, fileTypes));
} catch (IOException e) {
throw new RuntimeException(e);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public ListBoxModel doFillErrorModeItems() {
ListBoxModel items = new ListBoxModel();
for (ErrorMode errorMode : ErrorMode.values()) {
items.add(errorMode.getHumanReadable(), errorMode.toString());
}
return items;
}
@Exported
public ListBoxModel doFillUnstableModeItems() {
return doFillErrorModeItems();
}
@Override
public boolean isApplicable(Class<? extends AbstractProject> jobType) {
return true;
}
@Override
public String getDisplayName() {
return "Execute UserContent Script";
}
}
}
| true | true | private int executeScript(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener, CommandInterpreter command) throws InterruptedException, IOException {
FilePath ws = build.getWorkspace();
FilePath script = null;
try {
try {
script = command.createScriptFile(ws);
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError(Messages.CommandInterpreter_UnableToProduceScript()));
return -2;
}
int exitCode;
try {
EnvVars envVars = build.getEnvironment(listener);
Map<String, String> varsToInject = injectParameters(parameters, envVars);
envVars.putAll(varsToInject);
envVars.put("BUILD_RESULT", build.getResult().toString());
// on Windows environment variables are converted to all upper case,
// but no such conversions are done on Unix, so to make this cross-platform,
// convert variables to all upper cases.
for (Map.Entry<String, String> e : build.getBuildVariables().entrySet()) {
envVars.put(e.getKey(), e.getValue());
}
exitCode = launcher.launch().cmds(command.buildCommandLine(script)).envs(envVars).stdout(listener).pwd(ws).join();
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError(Messages.CommandInterpreter_CommandFailed()));
throw e;
}
return exitCode;
} finally {
try {
if (script != null) {
script.delete();
}
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError(Messages.CommandInterpreter_UnableToDelete(script)));
}
}
}
| private int executeScript(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener, CommandInterpreter command) throws InterruptedException, IOException {
FilePath ws = build.getWorkspace();
FilePath script = null;
try {
try {
script = command.createScriptFile(ws);
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError(Messages.CommandInterpreter_UnableToProduceScript()));
return -2;
}
int exitCode;
try {
EnvVars envVars = build.getEnvironment(listener);
Map<String, String> varsToInject = injectParameters(parameters, envVars);
envVars.putAll(varsToInject);
envVars.put("BUILD_RESULT", String.valueOf(build.getResult()));
// on Windows environment variables are converted to all upper case,
// but no such conversions are done on Unix, so to make this cross-platform,
// convert variables to all upper cases.
for (Map.Entry<String, String> e : build.getBuildVariables().entrySet()) {
envVars.put(e.getKey(), e.getValue());
}
exitCode = launcher.launch().cmds(command.buildCommandLine(script)).envs(envVars).stdout(listener).pwd(ws).join();
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError(Messages.CommandInterpreter_CommandFailed()));
throw e;
}
return exitCode;
} finally {
try {
if (script != null) {
script.delete();
}
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError(Messages.CommandInterpreter_UnableToDelete(script)));
}
}
}
|
diff --git a/src/common/com/github/AbrarSyed/SecretRooms/BlockCamoFull.java b/src/common/com/github/AbrarSyed/SecretRooms/BlockCamoFull.java
index 619f3dd..c6226c9 100644
--- a/src/common/com/github/AbrarSyed/SecretRooms/BlockCamoFull.java
+++ b/src/common/com/github/AbrarSyed/SecretRooms/BlockCamoFull.java
@@ -1,441 +1,442 @@
package com.github.AbrarSyed.SecretRooms;
import java.util.ArrayList;
import java.util.Random;
import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.Side;
import cpw.mods.fml.common.network.PacketDispatcher;
import net.minecraft.src.Block;
import net.minecraft.src.BlockContainer;
import net.minecraft.src.CreativeTabs;
import net.minecraft.src.IBlockAccess;
import net.minecraft.src.ItemStack;
import net.minecraft.src.Material;
import net.minecraft.src.ModLoader;
import net.minecraft.src.TileEntity;
import net.minecraft.src.World;
/**
* @author AbrarSyed
*/
public class BlockCamoFull extends BlockContainer
{
protected BlockCamoFull(int par1)
{
super(par1, Material.wood);
blockIndexInTexture = 0;
this.setLightOpacity(15);
this.setCreativeTab(CreativeTabs.tabBlock);
}
protected BlockCamoFull(int par1, Material material)
{
super(par1, material);
blockIndexInTexture = 0;
this.setLightOpacity(15);
this.setCreativeTab(CreativeTabs.tabBlock);
}
@Override
public TileEntity createNewTileEntity(World world)
{
return new TileEntityCamoFull();
}
@Override
public int quantityDropped(Random random)
{
return 1;
}
@Override
public boolean isOpaqueCube()
{
return false;
}
@Override
public int getRenderType()
{
return SecretRooms.camoRenderId;
}
@Override
public int getBlockTexture(IBlockAccess world, int x, int y, int z, int dir)
{
if (!SecretRooms.displayCamo)
return getBlockTextureFromSide(dir);
TileEntityCamoFull entity = ((TileEntityCamoFull)world.getBlockTileEntity(x, y, z));
int id;
if (entity == null)
id = 1;
else if (entity.getCopyID() <= 0)
id = 1;
else
{
id = entity.getCopyID();
x = entity.getCopyCoordX();
y = entity.getCopyCoordY();
z = entity.getCopyCoordZ();
}
return Block.blocksList[id].getBlockTexture(world, x, y, z, dir);
}
@Override
public int getBlockTextureFromSide(int i)
{
if (i == 2)
return 0;
return blockIndexInTexture;
}
/**
* Returns the ID of the items to drop on destruction.
*/
@Override
public int idDropped(int par1, Random par2Random, int par3)
{
return blockID;
}
@Override
public void updateBlockMetadata(World world, int i, int j, int k, int side, float something1, float something2, float something3)
{
if (alreadyExists(world, i, j, k))
return;
if (!world.isRemote)
{
// CAMO STUFF
int[] IdAndCoords = getIdCamoStyle(world, i, j , k);
TileEntityCamoFull entity = (TileEntityCamoFull) world.getBlockTileEntity(i, j, k);
if (IdAndCoords.length <= 4)
{
entity.setCopyCoordX(IdAndCoords[1]);
entity.setCopyCoordY(IdAndCoords[2]);
entity.setCopyCoordZ(IdAndCoords[3]);
}
entity.setCopyID(IdAndCoords[0]);
FMLCommonHandler.instance().getMinecraftServerInstance().getConfigurationManager().sendPacketToAllPlayers(entity.getAuxillaryInfoPacket());
}
else
{
// CAMO STUFF
int[] IdAndCoords = getIdCamoStyle(world, i, j , k);
TileEntityCamoFull entity = (TileEntityCamoFull) world.getBlockTileEntity(i, j, k);
if (IdAndCoords.length <= 4)
{
entity.setCopyCoordX(IdAndCoords[1]);
entity.setCopyCoordY(IdAndCoords[2]);
entity.setCopyCoordZ(IdAndCoords[3]);
}
entity.setCopyID(IdAndCoords[0]);
}
}
private boolean alreadyExists(World world, int i, int j, int k)
{
TileEntity entityU = world.getBlockTileEntity(i, j, k);
if (entityU != null && entityU instanceof TileEntityCamoFull)
{
TileEntityCamoFull entity = (TileEntityCamoFull)entityU;
if (entity.getCopyID() != 0)
{
if (entity.hasCoords())
{
int ID = world.getBlockId(entity.getCopyCoordX(), entity.getCopyCoordY(), entity.getCopyCoordZ());
if (ID == 0)
return false;
}
return true;
}
}
return false;
}
@Override
public int colorMultiplier(IBlockAccess par1IBlockAccess, int par2, int par3, int par4)
{
if (!SecretRooms.displayCamo)
return 0xffffff;
TileEntityCamoFull entity = (TileEntityCamoFull)par1IBlockAccess.getBlockTileEntity(par2, par3, par4);
if (entity == null)
return 0xffffff;
int id = entity.getCopyID();
if (id == Block.grass.blockID)
{
int i = 0;
int j = 0;
int k = 0;
for (int l = -1; l <= 1; l++)
{
for (int i1 = -1; i1 <= 1; i1++)
{
int j1 = par1IBlockAccess.getBiomeGenForCoords(par2 + i1, par4 + l).getBiomeGrassColor();
i += (j1 & 0xff0000) >> 16;
j += (j1 & 0xff00) >> 8;
k += j1 & 0xff;
}
}
return (i / 9 & 0xff) << 16 | (j / 9 & 0xff) << 8 | k / 9 & 0xff;
}
return 0xffffff;
}
/**
* annalyses surrounding blocks and decides on a BlockID for the Camo Block to copy.
* @param world
* @param x coord
* @param y coord
* @param z coord
* @return the ID of the block to be copied
*/
private int[] getIdCamoStyle(World world, int x, int y, int z)
{
int[] id = new int[]{0, 0, 0 , 0};
int[][] plusIds = new int[6][4];
Block block;
// Only PLUS sign id checks.
plusIds[0] = getInfo(world, x, y-1, z); // y-1
plusIds[1] = getInfo(world, x, y+1, z); // y+1
plusIds[2] = getInfo(world, x-1, y, z); // x-1
plusIds[3] = getInfo(world, x+1, y, z); // x+1
plusIds[4] = getInfo(world, x, y, z-1); // z-1
plusIds[5] = getInfo(world, x, y, z+1); // z+1
// if there is only 1 in the PLUS SIGN checked.
if (isOneLeft(truncateArrayINT(plusIds)))
{
plusIds = truncateArrayINT(plusIds);
return plusIds[0];
}
int[][] intChecks = new int[3][4];
// checks Y's
if (plusIds[0] == plusIds[1])
intChecks[1] = plusIds[0];
//checks X's
if (plusIds[2] == plusIds[3])
intChecks[0] = plusIds[1];
// checks Z's
if (plusIds[4] == plusIds[5])
intChecks[2] = plusIds[4];
// part of XY wall?
if (intChecks[1][0] == intChecks[0][0] && intChecks[0][0] > 0)
id = intChecks[0];
// part of YZ wall?
else if (intChecks[1][0] == intChecks[2][0] && intChecks[2][0] > 0)
id = intChecks[1];
// part of XZ floor or ceiling?
else if (intChecks[2][0] == intChecks[0][0] && intChecks[0][0] > 0)
id = intChecks[0];
if (id[0] != 0) return id;
// GET MODE
plusIds = this.truncateArrayINT(plusIds);
try
{
id = tallyMode(plusIds);
}
catch(Exception e)
{
- if (id.length >= 1)
- id = truncateArrayINT(plusIds)[0];
+ int[][] test = truncateArrayINT(plusIds);
+ if (test.length >= 1)
+ id = test[0];
}
if (id[0] == 0)
return new int[] {1, 0, 0, 0, 0};
return id;
}
private int[] tallyMode(int[][] nums2) throws Exception
{
int[] nums = new int[nums2.length];
for (int i = 0; i < nums2.length; i++)
{
nums[i] = nums2[i][0];
}
// create array of tallies, all initialized to zero
int[] tally = new int[256];
// for each array entry, increment corresponding tally box
for (int i = 0; i < nums.length; i++)
{
int value = nums[i];
tally[value]++;
}
// now find the index of the largest tally - this is the mode
int maxIndex = 0;
for (int i = 1; i < tally.length; i++)
{
if (tally[i] == tally[maxIndex] && tally[i] != 0)
{
throw new Exception("NULL");
}
else if (tally[i] > tally[maxIndex])
{
maxIndex = i;
}
}
return nums2[maxIndex];
}
/**
* Used to specially get Ids. It returns zero if the texture cannot be copied, or if it is air.
* @param world The world
* @param x X coordinate
* @param y Y Coordinate
* @param z Z Coordinate
* @return
*/
private static int[] getInfo(World world, int x, int y, int z)
{
// if its an air block, return 0
if (world.isAirBlock(x, y, z))
return new int[] {0, 0, 0, 0};
else
{
int id = world.getBlockId(x, y, z);
Block block = Block.blocksList[id];
if (block instanceof BlockCamoFull)
{
TileEntityCamoFull entity = (TileEntityCamoFull)world.getBlockTileEntity(x, y, z);
if (entity != null)
return new int[] {entity.getCopyID(), entity.getCopyCoordX(), entity.getCopyCoordY(), entity.getCopyCoordZ()};;
return new int[] {0, 0, 0, 0};
}
else
{
if (block instanceof BlockOneWay)
return new int[] {id, x, y, z};
else
{
block.setBlockBoundsBasedOnState(world, x, y, z);
double[] bounds = new double[]
{
block.minX,
block.minY,
block.minZ,
block.maxX,
block.maxY,
block.maxZ
};
if (block.minX == 0
&& block.minY == 0
&& block.minZ == 0
&& block.maxX == 1
&& block.maxY == 1
&& block.maxZ == 1
)
return new int[] {id, x, y, z};
else
return new int[] {0, 0, 0, 0};
}
}
}
}
/**
* This truncates an int Array so that it contains only values above zero. The size of the array is also cut down so that all of them are full.
* @param array The array to be truncated
* @return the truncated array.
*/
private static int[][] truncateArrayINT(int[][] array)
{
int num = 0;
for (int[] obj: array)
{
if (obj[0] > 0)
{
num++;
}
}
int[][] truncated = new int[num][4];
num = 0;
for (int[] obj: array)
{
if (obj[0] > 0)
{
truncated[num] = obj;
num++;
}
}
return truncated;
}
private boolean isOneLeft(int[][] textures)
{
if (!checkAllNull(textures))
{
if (truncateArrayINT(textures).length == 1)
{
return true;
}
}
return false;
}
private boolean checkAllNull(int[][] textures)
{
boolean flag = true;
for (int[] num: textures)
{
if (num[0] > 0)
{
flag = false;
}
}
return flag;
}
}
| true | true | private int[] getIdCamoStyle(World world, int x, int y, int z)
{
int[] id = new int[]{0, 0, 0 , 0};
int[][] plusIds = new int[6][4];
Block block;
// Only PLUS sign id checks.
plusIds[0] = getInfo(world, x, y-1, z); // y-1
plusIds[1] = getInfo(world, x, y+1, z); // y+1
plusIds[2] = getInfo(world, x-1, y, z); // x-1
plusIds[3] = getInfo(world, x+1, y, z); // x+1
plusIds[4] = getInfo(world, x, y, z-1); // z-1
plusIds[5] = getInfo(world, x, y, z+1); // z+1
// if there is only 1 in the PLUS SIGN checked.
if (isOneLeft(truncateArrayINT(plusIds)))
{
plusIds = truncateArrayINT(plusIds);
return plusIds[0];
}
int[][] intChecks = new int[3][4];
// checks Y's
if (plusIds[0] == plusIds[1])
intChecks[1] = plusIds[0];
//checks X's
if (plusIds[2] == plusIds[3])
intChecks[0] = plusIds[1];
// checks Z's
if (plusIds[4] == plusIds[5])
intChecks[2] = plusIds[4];
// part of XY wall?
if (intChecks[1][0] == intChecks[0][0] && intChecks[0][0] > 0)
id = intChecks[0];
// part of YZ wall?
else if (intChecks[1][0] == intChecks[2][0] && intChecks[2][0] > 0)
id = intChecks[1];
// part of XZ floor or ceiling?
else if (intChecks[2][0] == intChecks[0][0] && intChecks[0][0] > 0)
id = intChecks[0];
if (id[0] != 0) return id;
// GET MODE
plusIds = this.truncateArrayINT(plusIds);
try
{
id = tallyMode(plusIds);
}
catch(Exception e)
{
if (id.length >= 1)
id = truncateArrayINT(plusIds)[0];
}
if (id[0] == 0)
return new int[] {1, 0, 0, 0, 0};
return id;
}
| private int[] getIdCamoStyle(World world, int x, int y, int z)
{
int[] id = new int[]{0, 0, 0 , 0};
int[][] plusIds = new int[6][4];
Block block;
// Only PLUS sign id checks.
plusIds[0] = getInfo(world, x, y-1, z); // y-1
plusIds[1] = getInfo(world, x, y+1, z); // y+1
plusIds[2] = getInfo(world, x-1, y, z); // x-1
plusIds[3] = getInfo(world, x+1, y, z); // x+1
plusIds[4] = getInfo(world, x, y, z-1); // z-1
plusIds[5] = getInfo(world, x, y, z+1); // z+1
// if there is only 1 in the PLUS SIGN checked.
if (isOneLeft(truncateArrayINT(plusIds)))
{
plusIds = truncateArrayINT(plusIds);
return plusIds[0];
}
int[][] intChecks = new int[3][4];
// checks Y's
if (plusIds[0] == plusIds[1])
intChecks[1] = plusIds[0];
//checks X's
if (plusIds[2] == plusIds[3])
intChecks[0] = plusIds[1];
// checks Z's
if (plusIds[4] == plusIds[5])
intChecks[2] = plusIds[4];
// part of XY wall?
if (intChecks[1][0] == intChecks[0][0] && intChecks[0][0] > 0)
id = intChecks[0];
// part of YZ wall?
else if (intChecks[1][0] == intChecks[2][0] && intChecks[2][0] > 0)
id = intChecks[1];
// part of XZ floor or ceiling?
else if (intChecks[2][0] == intChecks[0][0] && intChecks[0][0] > 0)
id = intChecks[0];
if (id[0] != 0) return id;
// GET MODE
plusIds = this.truncateArrayINT(plusIds);
try
{
id = tallyMode(plusIds);
}
catch(Exception e)
{
int[][] test = truncateArrayINT(plusIds);
if (test.length >= 1)
id = test[0];
}
if (id[0] == 0)
return new int[] {1, 0, 0, 0, 0};
return id;
}
|
diff --git a/src/test/java/org/atlasapi/beans/JaxbXmlTranslatorTest.java b/src/test/java/org/atlasapi/beans/JaxbXmlTranslatorTest.java
index b297e211f..1b4f7d866 100644
--- a/src/test/java/org/atlasapi/beans/JaxbXmlTranslatorTest.java
+++ b/src/test/java/org/atlasapi/beans/JaxbXmlTranslatorTest.java
@@ -1,120 +1,121 @@
/* Copyright 2009 Meta Broadcast Ltd
Licensed under the Apache License, Version 2.0 (the "License"); you
may not use this file except in compliance with the License. You may
obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied. See the License for the specific language governing
permissions and limitations under the License. */
package org.atlasapi.beans;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import java.util.Set;
import junit.framework.TestCase;
import org.atlasapi.media.entity.simple.Broadcast;
import org.atlasapi.media.entity.simple.ContentQueryResult;
import org.atlasapi.media.entity.simple.Description;
import org.atlasapi.media.entity.simple.Item;
import org.atlasapi.media.entity.simple.ContentIdentifier.ItemIdentifier;
import org.atlasapi.media.entity.simple.Location;
import org.atlasapi.media.entity.simple.Playlist;
import org.joda.time.DateTime;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Sets;
import com.metabroadcast.common.servlet.StubHttpServletRequest;
import com.metabroadcast.common.servlet.StubHttpServletResponse;
/**
* @author Robert Chatley ([email protected])
*/
public class JaxbXmlTranslatorTest extends TestCase {
private StubHttpServletRequest request;
private StubHttpServletResponse response;
@Override
public void setUp() throws Exception {
this.request = new StubHttpServletRequest();
this.response = new StubHttpServletResponse();
}
public void testCanOutputSimpleItemObjectModelAsXml() throws Exception {
Set<Object> graph = Sets.newHashSet();
Item item = new Item();
item.setTitle("Blue Peter");
item.setUri("http://www.bbc.co.uk/programmes/bluepeter");
item.setAliases(Sets.newHashSet("http://www.bbc.co.uk/p/bluepeter"));
Location location = new Location();
location.setUri("http://www.bbc.co.uk/bluepeter");
location.setEmbedCode("<object><embed></embed></object>");
item.addLocation(location);
DateTime transmitted = new DateTime(1990, 1, 1, 1, 1, 1, 1);
item.addBroadcast(new Broadcast("channel", transmitted, transmitted.plusHours(1)));
ContentQueryResult result = new ContentQueryResult();
result.add(item);
graph.add(result);
new JaxbXmlTranslator().writeTo(request, response, graph, AtlasModelType.CONTENT);
String output = response.getResponseAsString();
assertThat(output, containsString("<play:item>" +
"<uri>http://www.bbc.co.uk/programmes/bluepeter</uri>" +
"<aliases>" +
"<alias>http://www.bbc.co.uk/p/bluepeter</alias>" +
"</aliases>" +
"<clips/>" +
"<play:genres/>" +
"<play:sameAs/>" +
"<play:tags/>" +
"<title>Blue Peter</title>" +
"<play:broadcasts>" +
"<play:broadcast>" +
"<broadcastDuration>3600</broadcastDuration>" +
"<broadcastOn>channel</broadcastOn><transmissionEndTime>1990-01-01T02:01:01.001Z</transmissionEndTime>" +
"<transmissionTime>1990-01-01T01:01:01.001Z</transmissionTime>" +
"</play:broadcast>" +
"</play:broadcasts>" +
+ "<play:countriesOfOrigin/>" +
"<play:locations>" +
"<play:location>" +
"<available>true</available>" +
"<play:availableCountries/>" +
"<embedCode><object><embed></embed></object></embedCode>" +
"<uri>http://www.bbc.co.uk/bluepeter</uri>" +
"</play:location>" +
"</play:locations>" +
"<play:people/>" +
"</play:item>"));
}
public void testCanOutputSimpleListObjectModelAsXml() throws Exception {
Set<Object> graph = Sets.newHashSet();
Playlist list = new Playlist();
ItemIdentifier item = new ItemIdentifier("http://www.bbc.co.uk/bluepeter");
list.add(item);
ContentQueryResult result = new ContentQueryResult();
result.setContents(ImmutableList.<Description>of(list));
graph.add(result);
new JaxbXmlTranslator().writeTo(request, response, graph, AtlasModelType.CONTENT);
assertThat(response.getResponseAsString(), containsString("<play:item><type>Item</type>" +
"<uri>http://www.bbc.co.uk/bluepeter</uri>" +
"</play:item>"));
}
}
| true | true | public void testCanOutputSimpleItemObjectModelAsXml() throws Exception {
Set<Object> graph = Sets.newHashSet();
Item item = new Item();
item.setTitle("Blue Peter");
item.setUri("http://www.bbc.co.uk/programmes/bluepeter");
item.setAliases(Sets.newHashSet("http://www.bbc.co.uk/p/bluepeter"));
Location location = new Location();
location.setUri("http://www.bbc.co.uk/bluepeter");
location.setEmbedCode("<object><embed></embed></object>");
item.addLocation(location);
DateTime transmitted = new DateTime(1990, 1, 1, 1, 1, 1, 1);
item.addBroadcast(new Broadcast("channel", transmitted, transmitted.plusHours(1)));
ContentQueryResult result = new ContentQueryResult();
result.add(item);
graph.add(result);
new JaxbXmlTranslator().writeTo(request, response, graph, AtlasModelType.CONTENT);
String output = response.getResponseAsString();
assertThat(output, containsString("<play:item>" +
"<uri>http://www.bbc.co.uk/programmes/bluepeter</uri>" +
"<aliases>" +
"<alias>http://www.bbc.co.uk/p/bluepeter</alias>" +
"</aliases>" +
"<clips/>" +
"<play:genres/>" +
"<play:sameAs/>" +
"<play:tags/>" +
"<title>Blue Peter</title>" +
"<play:broadcasts>" +
"<play:broadcast>" +
"<broadcastDuration>3600</broadcastDuration>" +
"<broadcastOn>channel</broadcastOn><transmissionEndTime>1990-01-01T02:01:01.001Z</transmissionEndTime>" +
"<transmissionTime>1990-01-01T01:01:01.001Z</transmissionTime>" +
"</play:broadcast>" +
"</play:broadcasts>" +
"<play:locations>" +
"<play:location>" +
"<available>true</available>" +
"<play:availableCountries/>" +
"<embedCode><object><embed></embed></object></embedCode>" +
"<uri>http://www.bbc.co.uk/bluepeter</uri>" +
"</play:location>" +
"</play:locations>" +
"<play:people/>" +
"</play:item>"));
}
| public void testCanOutputSimpleItemObjectModelAsXml() throws Exception {
Set<Object> graph = Sets.newHashSet();
Item item = new Item();
item.setTitle("Blue Peter");
item.setUri("http://www.bbc.co.uk/programmes/bluepeter");
item.setAliases(Sets.newHashSet("http://www.bbc.co.uk/p/bluepeter"));
Location location = new Location();
location.setUri("http://www.bbc.co.uk/bluepeter");
location.setEmbedCode("<object><embed></embed></object>");
item.addLocation(location);
DateTime transmitted = new DateTime(1990, 1, 1, 1, 1, 1, 1);
item.addBroadcast(new Broadcast("channel", transmitted, transmitted.plusHours(1)));
ContentQueryResult result = new ContentQueryResult();
result.add(item);
graph.add(result);
new JaxbXmlTranslator().writeTo(request, response, graph, AtlasModelType.CONTENT);
String output = response.getResponseAsString();
assertThat(output, containsString("<play:item>" +
"<uri>http://www.bbc.co.uk/programmes/bluepeter</uri>" +
"<aliases>" +
"<alias>http://www.bbc.co.uk/p/bluepeter</alias>" +
"</aliases>" +
"<clips/>" +
"<play:genres/>" +
"<play:sameAs/>" +
"<play:tags/>" +
"<title>Blue Peter</title>" +
"<play:broadcasts>" +
"<play:broadcast>" +
"<broadcastDuration>3600</broadcastDuration>" +
"<broadcastOn>channel</broadcastOn><transmissionEndTime>1990-01-01T02:01:01.001Z</transmissionEndTime>" +
"<transmissionTime>1990-01-01T01:01:01.001Z</transmissionTime>" +
"</play:broadcast>" +
"</play:broadcasts>" +
"<play:countriesOfOrigin/>" +
"<play:locations>" +
"<play:location>" +
"<available>true</available>" +
"<play:availableCountries/>" +
"<embedCode><object><embed></embed></object></embedCode>" +
"<uri>http://www.bbc.co.uk/bluepeter</uri>" +
"</play:location>" +
"</play:locations>" +
"<play:people/>" +
"</play:item>"));
}
|
diff --git a/src/com/yahoo/platform/yui/compressor/JavaScriptCompressor.java b/src/com/yahoo/platform/yui/compressor/JavaScriptCompressor.java
index 43a83fd..d2f77ef 100644
--- a/src/com/yahoo/platform/yui/compressor/JavaScriptCompressor.java
+++ b/src/com/yahoo/platform/yui/compressor/JavaScriptCompressor.java
@@ -1,1326 +1,1326 @@
/*
* YUI Compressor
* http://developer.yahoo.com/yui/compressor/
* Author: Julien Lecomte - http://www.julienlecomte.net/
* Copyright (c) 2011 Yahoo! Inc. All rights reserved.
* The copyrights embodied in the content of this file are licensed
* by Yahoo! Inc. under the BSD (revised) open source license.
*/
package com.yahoo.platform.yui.compressor;
import org.mozilla.javascript.*;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class JavaScriptCompressor {
static final ArrayList ones;
static final ArrayList twos;
static final ArrayList threes;
static final Set builtin = new HashSet();
static final Map literals = new Hashtable();
static final Set reserved = new HashSet();
static {
// This list contains all the 3 characters or less built-in global
// symbols available in a browser. Please add to this list if you
// see anything missing.
builtin.add("NaN");
builtin.add("top");
ones = new ArrayList();
for (char c = 'a'; c <= 'z'; c++)
ones.add(Character.toString(c));
for (char c = 'A'; c <= 'Z'; c++)
ones.add(Character.toString(c));
twos = new ArrayList();
for (int i = 0; i < ones.size(); i++) {
String one = (String) ones.get(i);
for (char c = 'a'; c <= 'z'; c++)
twos.add(one + Character.toString(c));
for (char c = 'A'; c <= 'Z'; c++)
twos.add(one + Character.toString(c));
for (char c = '0'; c <= '9'; c++)
twos.add(one + Character.toString(c));
}
// Remove two-letter JavaScript reserved words and built-in globals...
twos.remove("as");
twos.remove("is");
twos.remove("do");
twos.remove("if");
twos.remove("in");
twos.removeAll(builtin);
threes = new ArrayList();
for (int i = 0; i < twos.size(); i++) {
String two = (String) twos.get(i);
for (char c = 'a'; c <= 'z'; c++)
threes.add(two + Character.toString(c));
for (char c = 'A'; c <= 'Z'; c++)
threes.add(two + Character.toString(c));
for (char c = '0'; c <= '9'; c++)
threes.add(two + Character.toString(c));
}
// Remove three-letter JavaScript reserved words and built-in globals...
threes.remove("for");
threes.remove("int");
threes.remove("new");
threes.remove("try");
threes.remove("use");
threes.remove("var");
threes.removeAll(builtin);
// That's up to ((26+26)*(1+(26+26+10)))*(1+(26+26+10))-8
// (206,380 symbols per scope)
// The following list comes from org/mozilla/javascript/Decompiler.java...
literals.put(new Integer(Token.GET), "get ");
literals.put(new Integer(Token.SET), "set ");
literals.put(new Integer(Token.TRUE), "true");
literals.put(new Integer(Token.FALSE), "false");
literals.put(new Integer(Token.NULL), "null");
literals.put(new Integer(Token.THIS), "this");
literals.put(new Integer(Token.FUNCTION), "function");
literals.put(new Integer(Token.COMMA), ",");
literals.put(new Integer(Token.LC), "{");
literals.put(new Integer(Token.RC), "}");
literals.put(new Integer(Token.LP), "(");
literals.put(new Integer(Token.RP), ")");
literals.put(new Integer(Token.LB), "[");
literals.put(new Integer(Token.RB), "]");
literals.put(new Integer(Token.DOT), ".");
literals.put(new Integer(Token.NEW), "new ");
literals.put(new Integer(Token.DELPROP), "delete ");
literals.put(new Integer(Token.IF), "if");
literals.put(new Integer(Token.ELSE), "else");
literals.put(new Integer(Token.FOR), "for");
literals.put(new Integer(Token.IN), " in ");
literals.put(new Integer(Token.WITH), "with");
literals.put(new Integer(Token.WHILE), "while");
literals.put(new Integer(Token.DO), "do");
literals.put(new Integer(Token.TRY), "try");
literals.put(new Integer(Token.CATCH), "catch");
literals.put(new Integer(Token.FINALLY), "finally");
literals.put(new Integer(Token.THROW), "throw");
literals.put(new Integer(Token.SWITCH), "switch");
literals.put(new Integer(Token.BREAK), "break");
literals.put(new Integer(Token.CONTINUE), "continue");
literals.put(new Integer(Token.CASE), "case");
literals.put(new Integer(Token.DEFAULT), "default");
literals.put(new Integer(Token.RETURN), "return");
literals.put(new Integer(Token.VAR), "var ");
literals.put(new Integer(Token.SEMI), ";");
literals.put(new Integer(Token.ASSIGN), "=");
literals.put(new Integer(Token.ASSIGN_ADD), "+=");
literals.put(new Integer(Token.ASSIGN_SUB), "-=");
literals.put(new Integer(Token.ASSIGN_MUL), "*=");
literals.put(new Integer(Token.ASSIGN_DIV), "/=");
literals.put(new Integer(Token.ASSIGN_MOD), "%=");
literals.put(new Integer(Token.ASSIGN_BITOR), "|=");
literals.put(new Integer(Token.ASSIGN_BITXOR), "^=");
literals.put(new Integer(Token.ASSIGN_BITAND), "&=");
literals.put(new Integer(Token.ASSIGN_LSH), "<<=");
literals.put(new Integer(Token.ASSIGN_RSH), ">>=");
literals.put(new Integer(Token.ASSIGN_URSH), ">>>=");
literals.put(new Integer(Token.HOOK), "?");
literals.put(new Integer(Token.OBJECTLIT), ":");
literals.put(new Integer(Token.COLON), ":");
literals.put(new Integer(Token.OR), "||");
literals.put(new Integer(Token.AND), "&&");
literals.put(new Integer(Token.BITOR), "|");
literals.put(new Integer(Token.BITXOR), "^");
literals.put(new Integer(Token.BITAND), "&");
literals.put(new Integer(Token.SHEQ), "===");
literals.put(new Integer(Token.SHNE), "!==");
literals.put(new Integer(Token.EQ), "==");
literals.put(new Integer(Token.NE), "!=");
literals.put(new Integer(Token.LE), "<=");
literals.put(new Integer(Token.LT), "<");
literals.put(new Integer(Token.GE), ">=");
literals.put(new Integer(Token.GT), ">");
literals.put(new Integer(Token.INSTANCEOF), " instanceof ");
literals.put(new Integer(Token.LSH), "<<");
literals.put(new Integer(Token.RSH), ">>");
literals.put(new Integer(Token.URSH), ">>>");
literals.put(new Integer(Token.TYPEOF), "typeof");
literals.put(new Integer(Token.VOID), "void ");
literals.put(new Integer(Token.CONST), "const ");
literals.put(new Integer(Token.NOT), "!");
literals.put(new Integer(Token.BITNOT), "~");
literals.put(new Integer(Token.POS), "+");
literals.put(new Integer(Token.NEG), "-");
literals.put(new Integer(Token.INC), "++");
literals.put(new Integer(Token.DEC), "--");
literals.put(new Integer(Token.ADD), "+");
literals.put(new Integer(Token.SUB), "-");
literals.put(new Integer(Token.MUL), "*");
literals.put(new Integer(Token.DIV), "/");
literals.put(new Integer(Token.MOD), "%");
literals.put(new Integer(Token.COLONCOLON), "::");
literals.put(new Integer(Token.DOTDOT), "..");
literals.put(new Integer(Token.DOTQUERY), ".(");
literals.put(new Integer(Token.XMLATTR), "@");
literals.put(new Integer(Token.LET), "let ");
literals.put(new Integer(Token.YIELD), "yield ");
// See http://developer.mozilla.org/en/docs/Core_JavaScript_1.5_Reference:Reserved_Words
// JavaScript 1.5 reserved words
reserved.add("break");
reserved.add("case");
reserved.add("catch");
reserved.add("continue");
reserved.add("default");
reserved.add("delete");
reserved.add("do");
reserved.add("else");
reserved.add("finally");
reserved.add("for");
reserved.add("function");
reserved.add("if");
reserved.add("in");
reserved.add("instanceof");
reserved.add("new");
reserved.add("return");
reserved.add("switch");
reserved.add("this");
reserved.add("throw");
reserved.add("try");
reserved.add("typeof");
reserved.add("var");
reserved.add("void");
reserved.add("while");
reserved.add("with");
// Words reserved for future use
reserved.add("abstract");
reserved.add("boolean");
reserved.add("byte");
reserved.add("char");
reserved.add("class");
reserved.add("const");
reserved.add("debugger");
reserved.add("double");
reserved.add("enum");
reserved.add("export");
reserved.add("extends");
reserved.add("final");
reserved.add("float");
reserved.add("goto");
reserved.add("implements");
reserved.add("import");
reserved.add("int");
reserved.add("interface");
reserved.add("long");
reserved.add("native");
reserved.add("package");
reserved.add("private");
reserved.add("protected");
reserved.add("public");
reserved.add("short");
reserved.add("static");
reserved.add("super");
reserved.add("synchronized");
reserved.add("throws");
reserved.add("transient");
reserved.add("volatile");
// These are not reserved, but should be taken into account
// in isValidIdentifier (See jslint source code)
reserved.add("arguments");
reserved.add("eval");
reserved.add("true");
reserved.add("false");
reserved.add("Infinity");
reserved.add("NaN");
reserved.add("null");
reserved.add("undefined");
}
private static int countChar(String haystack, char needle) {
int idx = 0;
int count = 0;
int length = haystack.length();
while (idx < length) {
char c = haystack.charAt(idx++);
if (c == needle) {
count++;
}
}
return count;
}
private static int printSourceString(String source, int offset, StringBuffer sb) {
int length = source.charAt(offset);
++offset;
if ((0x8000 & length) != 0) {
length = ((0x7FFF & length) << 16) | source.charAt(offset);
++offset;
}
if (sb != null) {
String str = source.substring(offset, offset + length);
sb.append(str);
}
return offset + length;
}
private static int printSourceNumber(String source,
int offset, StringBuffer sb) {
double number = 0.0;
char type = source.charAt(offset);
++offset;
if (type == 'S') {
if (sb != null) {
number = source.charAt(offset);
}
++offset;
} else if (type == 'J' || type == 'D') {
if (sb != null) {
long lbits;
lbits = (long) source.charAt(offset) << 48;
lbits |= (long) source.charAt(offset + 1) << 32;
lbits |= (long) source.charAt(offset + 2) << 16;
lbits |= (long) source.charAt(offset + 3);
if (type == 'J') {
number = lbits;
} else {
number = Double.longBitsToDouble(lbits);
}
}
offset += 4;
} else {
// Bad source
throw new RuntimeException();
}
if (sb != null) {
sb.append(ScriptRuntime.numberToString(number, 10));
}
return offset;
}
private static ArrayList parse(Reader in, ErrorReporter reporter)
throws IOException, EvaluatorException {
CompilerEnvirons env = new CompilerEnvirons();
env.setLanguageVersion(Context.VERSION_1_7);
Parser parser = new Parser(env, reporter);
parser.parse(in, null, 1);
String source = parser.getEncodedSource();
int offset = 0;
int length = source.length();
ArrayList tokens = new ArrayList();
StringBuffer sb = new StringBuffer();
while (offset < length) {
int tt = source.charAt(offset++);
switch (tt) {
case Token.CONDCOMMENT:
case Token.KEEPCOMMENT:
case Token.NAME:
case Token.REGEXP:
case Token.STRING:
sb.setLength(0);
offset = printSourceString(source, offset, sb);
tokens.add(new JavaScriptToken(tt, sb.toString()));
break;
case Token.NUMBER:
sb.setLength(0);
offset = printSourceNumber(source, offset, sb);
tokens.add(new JavaScriptToken(tt, sb.toString()));
break;
default:
String literal = (String) literals.get(new Integer(tt));
if (literal != null) {
tokens.add(new JavaScriptToken(tt, literal));
}
break;
}
}
return tokens;
}
private static void processStringLiterals(ArrayList tokens, boolean merge) {
String tv;
int i, length = tokens.size();
JavaScriptToken token, prevToken, nextToken;
if (merge) {
// Concatenate string literals that are being appended wherever
// it is safe to do so. Note that we take care of the case:
// "a" + "b".toUpperCase()
for (i = 0; i < length; i++) {
token = (JavaScriptToken) tokens.get(i);
switch (token.getType()) {
case Token.ADD:
if (i > 0 && i < length) {
prevToken = (JavaScriptToken) tokens.get(i - 1);
nextToken = (JavaScriptToken) tokens.get(i + 1);
if (prevToken.getType() == Token.STRING && nextToken.getType() == Token.STRING &&
(i == length - 1 || ((JavaScriptToken) tokens.get(i + 2)).getType() != Token.DOT)) {
tokens.set(i - 1, new JavaScriptToken(Token.STRING,
prevToken.getValue() + nextToken.getValue()));
tokens.remove(i + 1);
tokens.remove(i);
i = i - 1;
length = length - 2;
break;
}
}
}
}
}
// Second pass...
for (i = 0; i < length; i++) {
token = (JavaScriptToken) tokens.get(i);
if (token.getType() == Token.STRING) {
tv = token.getValue();
// Finally, add the quoting characters and escape the string. We use
// the quoting character that minimizes the amount of escaping to save
// a few additional bytes.
char quotechar;
int singleQuoteCount = countChar(tv, '\'');
int doubleQuoteCount = countChar(tv, '"');
if (doubleQuoteCount <= singleQuoteCount) {
quotechar = '"';
} else {
quotechar = '\'';
}
tv = quotechar + escapeString(tv, quotechar) + quotechar;
// String concatenation transforms the old script scheme:
// '<scr'+'ipt ...><'+'/script>'
// into the following:
// '<script ...></script>'
// which breaks if this code is embedded inside an HTML document.
// Since this is not the right way to do this, let's fix the code by
// transforming all "</script" into "<\/script"
if (tv.indexOf("</script") >= 0) {
tv = tv.replaceAll("<\\/script", "<\\\\/script");
}
tokens.set(i, new JavaScriptToken(Token.STRING, tv));
}
}
}
// Add necessary escaping that was removed in Rhino's tokenizer.
private static String escapeString(String s, char quotechar) {
assert quotechar == '"' || quotechar == '\'';
if (s == null) {
return null;
}
StringBuffer sb = new StringBuffer();
for (int i = 0, L = s.length(); i < L; i++) {
int c = s.charAt(i);
if (c == quotechar) {
sb.append("\\");
}
sb.append((char) c);
}
return sb.toString();
}
/*
* Simple check to see whether a string is a valid identifier name.
* If a string matches this pattern, it means it IS a valid
* identifier name. If a string doesn't match it, it does not
* necessarily mean it is not a valid identifier name.
*/
private static final Pattern SIMPLE_IDENTIFIER_NAME_PATTERN = Pattern.compile("^[a-zA-Z_][a-zA-Z0-9_]*$");
private static boolean isValidIdentifier(String s) {
Matcher m = SIMPLE_IDENTIFIER_NAME_PATTERN.matcher(s);
return (m.matches() && !reserved.contains(s));
}
/*
* Transforms obj["foo"] into obj.foo whenever possible, saving 3 bytes.
*/
private static void optimizeObjectMemberAccess(ArrayList tokens) {
String tv;
int i, length;
JavaScriptToken token;
for (i = 0, length = tokens.size(); i < length; i++) {
if (((JavaScriptToken) tokens.get(i)).getType() == Token.LB &&
i > 0 && i < length - 2 &&
((JavaScriptToken) tokens.get(i - 1)).getType() == Token.NAME &&
((JavaScriptToken) tokens.get(i + 1)).getType() == Token.STRING &&
((JavaScriptToken) tokens.get(i + 2)).getType() == Token.RB) {
token = (JavaScriptToken) tokens.get(i + 1);
tv = token.getValue();
tv = tv.substring(1, tv.length() - 1);
if (isValidIdentifier(tv)) {
tokens.set(i, new JavaScriptToken(Token.DOT, "."));
tokens.set(i + 1, new JavaScriptToken(Token.NAME, tv));
tokens.remove(i + 2);
i = i + 2;
length = length - 1;
}
}
}
}
/*
* Transforms 'foo': ... into foo: ... whenever possible, saving 2 bytes.
*/
private static void optimizeObjLitMemberDecl(ArrayList tokens) {
String tv;
int i, length;
JavaScriptToken token;
for (i = 0, length = tokens.size(); i < length; i++) {
if (((JavaScriptToken) tokens.get(i)).getType() == Token.OBJECTLIT &&
i > 0 && ((JavaScriptToken) tokens.get(i - 1)).getType() == Token.STRING) {
token = (JavaScriptToken) tokens.get(i - 1);
tv = token.getValue();
tv = tv.substring(1, tv.length() - 1);
if (isValidIdentifier(tv)) {
tokens.set(i - 1, new JavaScriptToken(Token.NAME, tv));
}
}
}
}
private ErrorReporter logger;
private boolean munge;
private boolean verbose;
private static final int BUILDING_SYMBOL_TREE = 1;
private static final int CHECKING_SYMBOL_TREE = 2;
private int mode;
private int offset;
private int braceNesting;
private ArrayList tokens;
private Stack scopes = new Stack();
private ScriptOrFnScope globalScope = new ScriptOrFnScope(-1, null);
private Hashtable indexedScopes = new Hashtable();
public JavaScriptCompressor(Reader in, ErrorReporter reporter)
throws IOException, EvaluatorException {
this.logger = reporter;
this.tokens = parse(in, reporter);
}
public void compress(Writer out, int linebreak, boolean munge, boolean verbose,
boolean preserveAllSemiColons, boolean disableOptimizations)
throws IOException {
this.munge = munge;
this.verbose = verbose;
processStringLiterals(this.tokens, !disableOptimizations);
if (!disableOptimizations) {
optimizeObjectMemberAccess(this.tokens);
optimizeObjLitMemberDecl(this.tokens);
}
buildSymbolTree();
// DO NOT TOUCH this.tokens BETWEEN THESE TWO PHASES (BECAUSE OF this.indexedScopes)
mungeSymboltree();
StringBuffer sb = printSymbolTree(linebreak, preserveAllSemiColons);
out.write(sb.toString());
}
private ScriptOrFnScope getCurrentScope() {
return (ScriptOrFnScope) scopes.peek();
}
private void enterScope(ScriptOrFnScope scope) {
scopes.push(scope);
}
private void leaveCurrentScope() {
scopes.pop();
}
private JavaScriptToken consumeToken() {
return (JavaScriptToken) tokens.get(offset++);
}
private JavaScriptToken getToken(int delta) {
return (JavaScriptToken) tokens.get(offset + delta);
}
/*
* Returns the identifier for the specified symbol defined in
* the specified scope or in any scope above it. Returns null
* if this symbol does not have a corresponding identifier.
*/
private JavaScriptIdentifier getIdentifier(String symbol, ScriptOrFnScope scope) {
JavaScriptIdentifier identifier;
while (scope != null) {
identifier = scope.getIdentifier(symbol);
if (identifier != null) {
return identifier;
}
scope = scope.getParentScope();
}
return null;
}
/*
* If either 'eval' or 'with' is used in a local scope, we must make
* sure that all containing local scopes don't get munged. Otherwise,
* the obfuscation would potentially introduce bugs.
*/
private void protectScopeFromObfuscation(ScriptOrFnScope scope) {
assert scope != null;
if (scope == globalScope) {
// The global scope does not get obfuscated,
// so we don't need to worry about it...
return;
}
// Find the highest local scope containing the specified scope.
while (scope.getParentScope() != globalScope) {
scope = scope.getParentScope();
}
assert scope.getParentScope() == globalScope;
scope.preventMunging();
}
private String getDebugString(int max) {
assert max > 0;
StringBuffer result = new StringBuffer();
int start = Math.max(offset - max, 0);
int end = Math.min(offset + max, tokens.size());
for (int i = start; i < end; i++) {
JavaScriptToken token = (JavaScriptToken) tokens.get(i);
if (i == offset - 1) {
result.append(" ---> ");
}
result.append(token.getValue());
if (i == offset - 1) {
result.append(" <--- ");
}
}
return result.toString();
}
private void warn(String message, boolean showDebugString) {
if (verbose) {
if (showDebugString) {
message = message + "\n" + getDebugString(10);
}
logger.warning(message, null, -1, null, -1);
}
}
private void parseFunctionDeclaration() {
String symbol;
JavaScriptToken token;
ScriptOrFnScope currentScope, fnScope;
JavaScriptIdentifier identifier;
currentScope = getCurrentScope();
token = consumeToken();
if (token.getType() == Token.NAME) {
if (mode == BUILDING_SYMBOL_TREE) {
// Get the name of the function and declare it in the current scope.
symbol = token.getValue();
if (currentScope.getIdentifier(symbol) != null) {
warn("The function " + symbol + " has already been declared in the same scope...", true);
}
currentScope.declareIdentifier(symbol);
}
token = consumeToken();
}
assert token.getType() == Token.LP;
if (mode == BUILDING_SYMBOL_TREE) {
fnScope = new ScriptOrFnScope(braceNesting, currentScope);
indexedScopes.put(new Integer(offset), fnScope);
} else {
fnScope = (ScriptOrFnScope) indexedScopes.get(new Integer(offset));
}
// Parse function arguments.
int argpos = 0;
while ((token = consumeToken()).getType() != Token.RP) {
assert token.getType() == Token.NAME ||
token.getType() == Token.COMMA;
if (token.getType() == Token.NAME && mode == BUILDING_SYMBOL_TREE) {
symbol = token.getValue();
identifier = fnScope.declareIdentifier(symbol);
if (symbol.equals("$super") && argpos == 0) {
// Exception for Prototype 1.6...
identifier.preventMunging();
}
argpos++;
}
}
token = consumeToken();
assert token.getType() == Token.LC;
braceNesting++;
token = getToken(0);
if (token.getType() == Token.STRING &&
getToken(1).getType() == Token.SEMI) {
// This is a hint. Hints are empty statements that look like
// "localvar1:nomunge, localvar2:nomunge"; They allow developers
// to prevent specific symbols from getting obfuscated (some heretic
// implementations, such as Prototype 1.6, require specific variable
// names, such as $super for example, in order to work appropriately.
// Note: right now, only "nomunge" is supported in the right hand side
// of a hint. However, in the future, the right hand side may contain
// other values.
consumeToken();
String hints = token.getValue();
// Remove the leading and trailing quotes...
hints = hints.substring(1, hints.length() - 1).trim();
StringTokenizer st1 = new StringTokenizer(hints, ",");
while (st1.hasMoreTokens()) {
String hint = st1.nextToken();
int idx = hint.indexOf(':');
if (idx <= 0 || idx >= hint.length() - 1) {
if (mode == BUILDING_SYMBOL_TREE) {
// No need to report the error twice, hence the test...
warn("Invalid hint syntax: " + hint, true);
}
break;
}
String variableName = hint.substring(0, idx).trim();
String variableType = hint.substring(idx + 1).trim();
if (mode == BUILDING_SYMBOL_TREE) {
fnScope.addHint(variableName, variableType);
} else if (mode == CHECKING_SYMBOL_TREE) {
identifier = fnScope.getIdentifier(variableName);
if (identifier != null) {
if (variableType.equals("nomunge")) {
identifier.preventMunging();
} else {
warn("Unsupported hint value: " + hint, true);
}
} else {
warn("Hint refers to an unknown identifier: " + hint, true);
}
}
}
}
parseScope(fnScope);
}
private void parseCatch() {
String symbol;
JavaScriptToken token;
ScriptOrFnScope currentScope;
JavaScriptIdentifier identifier;
token = getToken(-1);
assert token.getType() == Token.CATCH;
token = consumeToken();
assert token.getType() == Token.LP;
token = consumeToken();
assert token.getType() == Token.NAME;
symbol = token.getValue();
currentScope = getCurrentScope();
if (mode == BUILDING_SYMBOL_TREE) {
// We must declare the exception identifier in the containing function
// scope to avoid errors related to the obfuscation process. No need to
// display a warning if the symbol was already declared here...
currentScope.declareIdentifier(symbol);
} else {
identifier = getIdentifier(symbol, currentScope);
identifier.incrementRefcount();
}
token = consumeToken();
assert token.getType() == Token.RP;
}
private void parseExpression() {
// Parse the expression until we encounter a comma or a semi-colon
// in the same brace nesting, bracket nesting and paren nesting.
// Parse functions if any...
String symbol;
JavaScriptToken token;
ScriptOrFnScope currentScope;
JavaScriptIdentifier identifier;
int expressionBraceNesting = braceNesting;
int bracketNesting = 0;
int parensNesting = 0;
int length = tokens.size();
while (offset < length) {
token = consumeToken();
currentScope = getCurrentScope();
switch (token.getType()) {
case Token.SEMI:
case Token.COMMA:
if (braceNesting == expressionBraceNesting &&
bracketNesting == 0 &&
parensNesting == 0) {
return;
}
break;
case Token.FUNCTION:
parseFunctionDeclaration();
break;
case Token.LC:
braceNesting++;
break;
case Token.RC:
braceNesting--;
assert braceNesting >= expressionBraceNesting;
break;
case Token.LB:
bracketNesting++;
break;
case Token.RB:
bracketNesting--;
break;
case Token.LP:
parensNesting++;
break;
case Token.RP:
parensNesting--;
break;
case Token.CONDCOMMENT:
if (mode == BUILDING_SYMBOL_TREE) {
protectScopeFromObfuscation(currentScope);
warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression!" : ""), true);
}
break;
case Token.NAME:
symbol = token.getValue();
if (mode == BUILDING_SYMBOL_TREE) {
if (symbol.equals("eval")) {
protectScopeFromObfuscation(currentScope);
warn("Using 'eval' is not recommended." + (munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
}
} else if (mode == CHECKING_SYMBOL_TREE) {
if ((offset < 2 ||
(getToken(-2).getType() != Token.DOT &&
getToken(-2).getType() != Token.GET &&
getToken(-2).getType() != Token.SET)) &&
getToken(0).getType() != Token.OBJECTLIT) {
identifier = getIdentifier(symbol, currentScope);
if (identifier == null) {
if (symbol.length() <= 3 && !builtin.contains(symbol)) {
// Here, we found an undeclared and un-namespaced symbol that is
// 3 characters or less in length. Declare it in the global scope.
// We don't need to declare longer symbols since they won't cause
// any conflict with other munged symbols.
globalScope.declareIdentifier(symbol);
// I removed the warning since was only being done when
// for identifiers 3 chars or less, and was just causing
// noise for people who happen to rely on an externally
// declared variable that happen to be that short. We either
// should always warn or never warn -- the fact that we
// declare the short symbols in the global space doesn't
// change anything.
// warn("Found an undeclared symbol: " + symbol, true);
}
} else {
identifier.incrementRefcount();
}
}
}
break;
}
}
}
private void parseScope(ScriptOrFnScope scope) {
String symbol;
JavaScriptToken token;
JavaScriptIdentifier identifier;
int length = tokens.size();
enterScope(scope);
while (offset < length) {
token = consumeToken();
switch (token.getType()) {
case Token.VAR:
if (mode == BUILDING_SYMBOL_TREE && scope.incrementVarCount() > 1) {
warn("Try to use a single 'var' statement per scope.", true);
}
/* FALLSTHROUGH */
case Token.CONST:
// The var keyword is followed by at least one symbol name.
// If several symbols follow, they are comma separated.
for (; ;) {
token = consumeToken();
assert token.getType() == Token.NAME;
if (mode == BUILDING_SYMBOL_TREE) {
symbol = token.getValue();
if (scope.getIdentifier(symbol) == null) {
scope.declareIdentifier(symbol);
} else {
warn("The variable " + symbol + " has already been declared in the same scope...", true);
}
}
token = getToken(0);
assert token.getType() == Token.SEMI ||
token.getType() == Token.ASSIGN ||
token.getType() == Token.COMMA ||
token.getType() == Token.IN;
if (token.getType() == Token.IN) {
break;
} else {
parseExpression();
token = getToken(-1);
if (token.getType() == Token.SEMI) {
break;
}
}
}
break;
case Token.FUNCTION:
parseFunctionDeclaration();
break;
case Token.LC:
braceNesting++;
break;
case Token.RC:
braceNesting--;
assert braceNesting >= scope.getBraceNesting();
if (braceNesting == scope.getBraceNesting()) {
leaveCurrentScope();
return;
}
break;
case Token.WITH:
if (mode == BUILDING_SYMBOL_TREE) {
// Inside a 'with' block, it is impossible to figure out
// statically whether a symbol is a local variable or an
// object member. As a consequence, the only thing we can
// do is turn the obfuscation off for the highest scope
// containing the 'with' block.
protectScopeFromObfuscation(scope);
warn("Using 'with' is not recommended." + (munge ? " Moreover, using 'with' reduces the level of compression!" : ""), true);
}
break;
case Token.CATCH:
parseCatch();
break;
case Token.CONDCOMMENT:
if (mode == BUILDING_SYMBOL_TREE) {
protectScopeFromObfuscation(scope);
warn("Using JScript conditional comments is not recommended." + (munge ? " Moreover, using JScript conditional comments reduces the level of compression." : ""), true);
}
break;
case Token.NAME:
symbol = token.getValue();
if (mode == BUILDING_SYMBOL_TREE) {
if (symbol.equals("eval")) {
protectScopeFromObfuscation(scope);
warn("Using 'eval' is not recommended." + (munge ? " Moreover, using 'eval' reduces the level of compression!" : ""), true);
}
} else if (mode == CHECKING_SYMBOL_TREE) {
if ((offset < 2 || getToken(-2).getType() != Token.DOT) &&
getToken(0).getType() != Token.OBJECTLIT) {
identifier = getIdentifier(symbol, scope);
if (identifier == null) {
if (symbol.length() <= 3 && !builtin.contains(symbol)) {
// Here, we found an undeclared and un-namespaced symbol that is
// 3 characters or less in length. Declare it in the global scope.
// We don't need to declare longer symbols since they won't cause
// any conflict with other munged symbols.
globalScope.declareIdentifier(symbol);
// warn("Found an undeclared symbol: " + symbol, true);
}
} else {
identifier.incrementRefcount();
}
}
}
break;
}
}
}
private void buildSymbolTree() {
offset = 0;
braceNesting = 0;
scopes.clear();
indexedScopes.clear();
indexedScopes.put(new Integer(0), globalScope);
mode = BUILDING_SYMBOL_TREE;
parseScope(globalScope);
}
private void mungeSymboltree() {
if (!munge) {
return;
}
// One problem with obfuscation resides in the use of undeclared
// and un-namespaced global symbols that are 3 characters or less
// in length. Here is an example:
//
// var declaredGlobalVar;
//
// function declaredGlobalFn() {
// var localvar;
// localvar = abc; // abc is an undeclared global symbol
// }
//
// In the example above, there is a slim chance that localvar may be
// munged to 'abc', conflicting with the undeclared global symbol
// abc, creating a potential bug. The following code detects such
// global symbols. This must be done AFTER the entire file has been
// parsed, and BEFORE munging the symbol tree. Note that declaring
// extra symbols in the global scope won't hurt.
//
// Note: Since we go through all the tokens to do this, we also use
// the opportunity to count how many times each identifier is used.
offset = 0;
braceNesting = 0;
scopes.clear();
mode = CHECKING_SYMBOL_TREE;
parseScope(globalScope);
globalScope.munge();
}
private StringBuffer printSymbolTree(int linebreakpos, boolean preserveAllSemiColons)
throws IOException {
offset = 0;
braceNesting = 0;
scopes.clear();
String symbol;
JavaScriptToken token;
JavaScriptToken lastToken = getToken(0);
ScriptOrFnScope currentScope;
JavaScriptIdentifier identifier;
int length = tokens.size();
StringBuffer result = new StringBuffer();
int linestartpos = 0;
enterScope(globalScope);
while (offset < length) {
token = consumeToken();
symbol = token.getValue();
currentScope = getCurrentScope();
switch (token.getType()) {
case Token.GET:
case Token.SET:
lastToken = token;
case Token.NAME:
if (offset >= 2 && getToken(-2).getType() == Token.DOT ||
getToken(0).getType() == Token.OBJECTLIT) {
result.append(symbol);
} else {
identifier = getIdentifier(symbol, currentScope);
if (identifier != null) {
if (identifier.getMungedValue() != null) {
result.append(identifier.getMungedValue());
} else {
result.append(symbol);
}
if (currentScope != globalScope && identifier.getRefcount() == 0) {
warn("The symbol " + symbol + " is declared but is apparently never used.\nThis code can probably be written in a more compact way.", true);
}
} else {
result.append(symbol);
}
}
break;
case Token.REGEXP:
case Token.NUMBER:
case Token.STRING:
result.append(symbol);
break;
case Token.ADD:
case Token.SUB:
result.append((String) literals.get(new Integer(token.getType())));
if (offset < length) {
token = getToken(0);
if (token.getType() == Token.INC ||
token.getType() == Token.DEC ||
token.getType() == Token.ADD ||
token.getType() == Token.DEC) {
// Handle the case x +/- ++/-- y
// We must keep a white space here. Otherwise, x +++ y would be
// interpreted as x ++ + y by the compiler, which is a bug (due
// to the implicit assignment being done on the wrong variable)
result.append(' ');
} else if (token.getType() == Token.POS && getToken(-1).getType() == Token.ADD ||
token.getType() == Token.NEG && getToken(-1).getType() == Token.SUB) {
// Handle the case x + + y and x - - y
result.append(' ');
}
}
break;
case Token.FUNCTION:
- if (lastToken.getType() != Token.GET && lastToken.getType() != Token.SET) {
- result.append("function");
- }
+ if (lastToken.getType() != Token.GET && lastToken.getType() != Token.SET) {
+ result.append("function");
+ }
token = consumeToken();
if (token.getType() == Token.NAME) {
result.append(' ');
symbol = token.getValue();
identifier = getIdentifier(symbol, currentScope);
assert identifier != null;
if (identifier.getMungedValue() != null) {
result.append(identifier.getMungedValue());
} else {
result.append(symbol);
}
if (currentScope != globalScope && identifier.getRefcount() == 0) {
warn("The symbol " + symbol + " is declared but is apparently never used.\nThis code can probably be written in a more compact way.", true);
}
token = consumeToken();
}
assert token.getType() == Token.LP;
result.append('(');
currentScope = (ScriptOrFnScope) indexedScopes.get(new Integer(offset));
enterScope(currentScope);
while ((token = consumeToken()).getType() != Token.RP) {
assert token.getType() == Token.NAME || token.getType() == Token.COMMA;
if (token.getType() == Token.NAME) {
symbol = token.getValue();
identifier = getIdentifier(symbol, currentScope);
assert identifier != null;
if (identifier.getMungedValue() != null) {
result.append(identifier.getMungedValue());
} else {
result.append(symbol);
}
} else if (token.getType() == Token.COMMA) {
result.append(',');
}
}
result.append(')');
token = consumeToken();
assert token.getType() == Token.LC;
result.append('{');
braceNesting++;
token = getToken(0);
if (token.getType() == Token.STRING &&
getToken(1).getType() == Token.SEMI) {
// This is a hint. Skip it!
consumeToken();
consumeToken();
}
break;
case Token.RETURN:
case Token.TYPEOF:
result.append(literals.get(new Integer(token.getType())));
// No space needed after 'return' and 'typeof' when followed
// by '(', '[', '{', a string or a regexp.
if (offset < length) {
token = getToken(0);
if (token.getType() != Token.LP &&
token.getType() != Token.LB &&
token.getType() != Token.LC &&
token.getType() != Token.STRING &&
token.getType() != Token.REGEXP &&
token.getType() != Token.SEMI) {
result.append(' ');
}
}
break;
case Token.CASE:
case Token.THROW:
result.append(literals.get(new Integer(token.getType())));
// White-space needed after 'case' and 'throw' when not followed by a string.
if (offset < length && getToken(0).getType() != Token.STRING) {
result.append(' ');
}
break;
case Token.BREAK:
case Token.CONTINUE:
result.append(literals.get(new Integer(token.getType())));
if (offset < length && getToken(0).getType() != Token.SEMI) {
// If 'break' or 'continue' is not followed by a semi-colon, it must
// be followed by a label, hence the need for a white space.
result.append(' ');
}
break;
case Token.LC:
result.append('{');
braceNesting++;
break;
case Token.RC:
result.append('}');
braceNesting--;
assert braceNesting >= currentScope.getBraceNesting();
if (braceNesting == currentScope.getBraceNesting()) {
leaveCurrentScope();
}
break;
case Token.SEMI:
// No need to output a semi-colon if the next character is a right-curly...
if (preserveAllSemiColons || offset < length && getToken(0).getType() != Token.RC) {
result.append(';');
}
if (linebreakpos >= 0 && result.length() - linestartpos > linebreakpos) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
result.append('\n');
linestartpos = result.length();
}
break;
case Token.CONDCOMMENT:
case Token.KEEPCOMMENT:
if (result.length() > 0 && result.charAt(result.length() - 1) != '\n') {
result.append("\n");
}
result.append("/*");
result.append(symbol);
result.append("*/\n");
break;
default:
String literal = (String) literals.get(new Integer(token.getType()));
if (literal != null) {
result.append(literal);
} else {
warn("This symbol cannot be printed: " + symbol, true);
}
break;
}
}
// Append a semi-colon at the end, even if unnecessary semi-colons are
// supposed to be removed. This is especially useful when concatenating
// several minified files (the absence of an ending semi-colon at the
// end of one file may very likely cause a syntax error)
if (!preserveAllSemiColons &&
result.length() > 0 &&
getToken(-1).getType() != Token.CONDCOMMENT &&
getToken(-1).getType() != Token.KEEPCOMMENT) {
if (result.charAt(result.length() - 1) == '\n') {
result.setCharAt(result.length() - 1, ';');
} else {
result.append(';');
}
}
return result;
}
}
| true | true | private StringBuffer printSymbolTree(int linebreakpos, boolean preserveAllSemiColons)
throws IOException {
offset = 0;
braceNesting = 0;
scopes.clear();
String symbol;
JavaScriptToken token;
JavaScriptToken lastToken = getToken(0);
ScriptOrFnScope currentScope;
JavaScriptIdentifier identifier;
int length = tokens.size();
StringBuffer result = new StringBuffer();
int linestartpos = 0;
enterScope(globalScope);
while (offset < length) {
token = consumeToken();
symbol = token.getValue();
currentScope = getCurrentScope();
switch (token.getType()) {
case Token.GET:
case Token.SET:
lastToken = token;
case Token.NAME:
if (offset >= 2 && getToken(-2).getType() == Token.DOT ||
getToken(0).getType() == Token.OBJECTLIT) {
result.append(symbol);
} else {
identifier = getIdentifier(symbol, currentScope);
if (identifier != null) {
if (identifier.getMungedValue() != null) {
result.append(identifier.getMungedValue());
} else {
result.append(symbol);
}
if (currentScope != globalScope && identifier.getRefcount() == 0) {
warn("The symbol " + symbol + " is declared but is apparently never used.\nThis code can probably be written in a more compact way.", true);
}
} else {
result.append(symbol);
}
}
break;
case Token.REGEXP:
case Token.NUMBER:
case Token.STRING:
result.append(symbol);
break;
case Token.ADD:
case Token.SUB:
result.append((String) literals.get(new Integer(token.getType())));
if (offset < length) {
token = getToken(0);
if (token.getType() == Token.INC ||
token.getType() == Token.DEC ||
token.getType() == Token.ADD ||
token.getType() == Token.DEC) {
// Handle the case x +/- ++/-- y
// We must keep a white space here. Otherwise, x +++ y would be
// interpreted as x ++ + y by the compiler, which is a bug (due
// to the implicit assignment being done on the wrong variable)
result.append(' ');
} else if (token.getType() == Token.POS && getToken(-1).getType() == Token.ADD ||
token.getType() == Token.NEG && getToken(-1).getType() == Token.SUB) {
// Handle the case x + + y and x - - y
result.append(' ');
}
}
break;
case Token.FUNCTION:
if (lastToken.getType() != Token.GET && lastToken.getType() != Token.SET) {
result.append("function");
}
token = consumeToken();
if (token.getType() == Token.NAME) {
result.append(' ');
symbol = token.getValue();
identifier = getIdentifier(symbol, currentScope);
assert identifier != null;
if (identifier.getMungedValue() != null) {
result.append(identifier.getMungedValue());
} else {
result.append(symbol);
}
if (currentScope != globalScope && identifier.getRefcount() == 0) {
warn("The symbol " + symbol + " is declared but is apparently never used.\nThis code can probably be written in a more compact way.", true);
}
token = consumeToken();
}
assert token.getType() == Token.LP;
result.append('(');
currentScope = (ScriptOrFnScope) indexedScopes.get(new Integer(offset));
enterScope(currentScope);
while ((token = consumeToken()).getType() != Token.RP) {
assert token.getType() == Token.NAME || token.getType() == Token.COMMA;
if (token.getType() == Token.NAME) {
symbol = token.getValue();
identifier = getIdentifier(symbol, currentScope);
assert identifier != null;
if (identifier.getMungedValue() != null) {
result.append(identifier.getMungedValue());
} else {
result.append(symbol);
}
} else if (token.getType() == Token.COMMA) {
result.append(',');
}
}
result.append(')');
token = consumeToken();
assert token.getType() == Token.LC;
result.append('{');
braceNesting++;
token = getToken(0);
if (token.getType() == Token.STRING &&
getToken(1).getType() == Token.SEMI) {
// This is a hint. Skip it!
consumeToken();
consumeToken();
}
break;
case Token.RETURN:
case Token.TYPEOF:
result.append(literals.get(new Integer(token.getType())));
// No space needed after 'return' and 'typeof' when followed
// by '(', '[', '{', a string or a regexp.
if (offset < length) {
token = getToken(0);
if (token.getType() != Token.LP &&
token.getType() != Token.LB &&
token.getType() != Token.LC &&
token.getType() != Token.STRING &&
token.getType() != Token.REGEXP &&
token.getType() != Token.SEMI) {
result.append(' ');
}
}
break;
case Token.CASE:
case Token.THROW:
result.append(literals.get(new Integer(token.getType())));
// White-space needed after 'case' and 'throw' when not followed by a string.
if (offset < length && getToken(0).getType() != Token.STRING) {
result.append(' ');
}
break;
case Token.BREAK:
case Token.CONTINUE:
result.append(literals.get(new Integer(token.getType())));
if (offset < length && getToken(0).getType() != Token.SEMI) {
// If 'break' or 'continue' is not followed by a semi-colon, it must
// be followed by a label, hence the need for a white space.
result.append(' ');
}
break;
case Token.LC:
result.append('{');
braceNesting++;
break;
case Token.RC:
result.append('}');
braceNesting--;
assert braceNesting >= currentScope.getBraceNesting();
if (braceNesting == currentScope.getBraceNesting()) {
leaveCurrentScope();
}
break;
case Token.SEMI:
// No need to output a semi-colon if the next character is a right-curly...
if (preserveAllSemiColons || offset < length && getToken(0).getType() != Token.RC) {
result.append(';');
}
if (linebreakpos >= 0 && result.length() - linestartpos > linebreakpos) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
result.append('\n');
linestartpos = result.length();
}
break;
case Token.CONDCOMMENT:
case Token.KEEPCOMMENT:
if (result.length() > 0 && result.charAt(result.length() - 1) != '\n') {
result.append("\n");
}
result.append("/*");
result.append(symbol);
result.append("*/\n");
break;
default:
String literal = (String) literals.get(new Integer(token.getType()));
if (literal != null) {
result.append(literal);
} else {
warn("This symbol cannot be printed: " + symbol, true);
}
break;
}
}
// Append a semi-colon at the end, even if unnecessary semi-colons are
// supposed to be removed. This is especially useful when concatenating
// several minified files (the absence of an ending semi-colon at the
// end of one file may very likely cause a syntax error)
if (!preserveAllSemiColons &&
result.length() > 0 &&
getToken(-1).getType() != Token.CONDCOMMENT &&
getToken(-1).getType() != Token.KEEPCOMMENT) {
if (result.charAt(result.length() - 1) == '\n') {
result.setCharAt(result.length() - 1, ';');
} else {
result.append(';');
}
}
return result;
}
| private StringBuffer printSymbolTree(int linebreakpos, boolean preserveAllSemiColons)
throws IOException {
offset = 0;
braceNesting = 0;
scopes.clear();
String symbol;
JavaScriptToken token;
JavaScriptToken lastToken = getToken(0);
ScriptOrFnScope currentScope;
JavaScriptIdentifier identifier;
int length = tokens.size();
StringBuffer result = new StringBuffer();
int linestartpos = 0;
enterScope(globalScope);
while (offset < length) {
token = consumeToken();
symbol = token.getValue();
currentScope = getCurrentScope();
switch (token.getType()) {
case Token.GET:
case Token.SET:
lastToken = token;
case Token.NAME:
if (offset >= 2 && getToken(-2).getType() == Token.DOT ||
getToken(0).getType() == Token.OBJECTLIT) {
result.append(symbol);
} else {
identifier = getIdentifier(symbol, currentScope);
if (identifier != null) {
if (identifier.getMungedValue() != null) {
result.append(identifier.getMungedValue());
} else {
result.append(symbol);
}
if (currentScope != globalScope && identifier.getRefcount() == 0) {
warn("The symbol " + symbol + " is declared but is apparently never used.\nThis code can probably be written in a more compact way.", true);
}
} else {
result.append(symbol);
}
}
break;
case Token.REGEXP:
case Token.NUMBER:
case Token.STRING:
result.append(symbol);
break;
case Token.ADD:
case Token.SUB:
result.append((String) literals.get(new Integer(token.getType())));
if (offset < length) {
token = getToken(0);
if (token.getType() == Token.INC ||
token.getType() == Token.DEC ||
token.getType() == Token.ADD ||
token.getType() == Token.DEC) {
// Handle the case x +/- ++/-- y
// We must keep a white space here. Otherwise, x +++ y would be
// interpreted as x ++ + y by the compiler, which is a bug (due
// to the implicit assignment being done on the wrong variable)
result.append(' ');
} else if (token.getType() == Token.POS && getToken(-1).getType() == Token.ADD ||
token.getType() == Token.NEG && getToken(-1).getType() == Token.SUB) {
// Handle the case x + + y and x - - y
result.append(' ');
}
}
break;
case Token.FUNCTION:
if (lastToken.getType() != Token.GET && lastToken.getType() != Token.SET) {
result.append("function");
}
token = consumeToken();
if (token.getType() == Token.NAME) {
result.append(' ');
symbol = token.getValue();
identifier = getIdentifier(symbol, currentScope);
assert identifier != null;
if (identifier.getMungedValue() != null) {
result.append(identifier.getMungedValue());
} else {
result.append(symbol);
}
if (currentScope != globalScope && identifier.getRefcount() == 0) {
warn("The symbol " + symbol + " is declared but is apparently never used.\nThis code can probably be written in a more compact way.", true);
}
token = consumeToken();
}
assert token.getType() == Token.LP;
result.append('(');
currentScope = (ScriptOrFnScope) indexedScopes.get(new Integer(offset));
enterScope(currentScope);
while ((token = consumeToken()).getType() != Token.RP) {
assert token.getType() == Token.NAME || token.getType() == Token.COMMA;
if (token.getType() == Token.NAME) {
symbol = token.getValue();
identifier = getIdentifier(symbol, currentScope);
assert identifier != null;
if (identifier.getMungedValue() != null) {
result.append(identifier.getMungedValue());
} else {
result.append(symbol);
}
} else if (token.getType() == Token.COMMA) {
result.append(',');
}
}
result.append(')');
token = consumeToken();
assert token.getType() == Token.LC;
result.append('{');
braceNesting++;
token = getToken(0);
if (token.getType() == Token.STRING &&
getToken(1).getType() == Token.SEMI) {
// This is a hint. Skip it!
consumeToken();
consumeToken();
}
break;
case Token.RETURN:
case Token.TYPEOF:
result.append(literals.get(new Integer(token.getType())));
// No space needed after 'return' and 'typeof' when followed
// by '(', '[', '{', a string or a regexp.
if (offset < length) {
token = getToken(0);
if (token.getType() != Token.LP &&
token.getType() != Token.LB &&
token.getType() != Token.LC &&
token.getType() != Token.STRING &&
token.getType() != Token.REGEXP &&
token.getType() != Token.SEMI) {
result.append(' ');
}
}
break;
case Token.CASE:
case Token.THROW:
result.append(literals.get(new Integer(token.getType())));
// White-space needed after 'case' and 'throw' when not followed by a string.
if (offset < length && getToken(0).getType() != Token.STRING) {
result.append(' ');
}
break;
case Token.BREAK:
case Token.CONTINUE:
result.append(literals.get(new Integer(token.getType())));
if (offset < length && getToken(0).getType() != Token.SEMI) {
// If 'break' or 'continue' is not followed by a semi-colon, it must
// be followed by a label, hence the need for a white space.
result.append(' ');
}
break;
case Token.LC:
result.append('{');
braceNesting++;
break;
case Token.RC:
result.append('}');
braceNesting--;
assert braceNesting >= currentScope.getBraceNesting();
if (braceNesting == currentScope.getBraceNesting()) {
leaveCurrentScope();
}
break;
case Token.SEMI:
// No need to output a semi-colon if the next character is a right-curly...
if (preserveAllSemiColons || offset < length && getToken(0).getType() != Token.RC) {
result.append(';');
}
if (linebreakpos >= 0 && result.length() - linestartpos > linebreakpos) {
// Some source control tools don't like it when files containing lines longer
// than, say 8000 characters, are checked in. The linebreak option is used in
// that case to split long lines after a specific column.
result.append('\n');
linestartpos = result.length();
}
break;
case Token.CONDCOMMENT:
case Token.KEEPCOMMENT:
if (result.length() > 0 && result.charAt(result.length() - 1) != '\n') {
result.append("\n");
}
result.append("/*");
result.append(symbol);
result.append("*/\n");
break;
default:
String literal = (String) literals.get(new Integer(token.getType()));
if (literal != null) {
result.append(literal);
} else {
warn("This symbol cannot be printed: " + symbol, true);
}
break;
}
}
// Append a semi-colon at the end, even if unnecessary semi-colons are
// supposed to be removed. This is especially useful when concatenating
// several minified files (the absence of an ending semi-colon at the
// end of one file may very likely cause a syntax error)
if (!preserveAllSemiColons &&
result.length() > 0 &&
getToken(-1).getType() != Token.CONDCOMMENT &&
getToken(-1).getType() != Token.KEEPCOMMENT) {
if (result.charAt(result.length() - 1) == '\n') {
result.setCharAt(result.length() - 1, ';');
} else {
result.append(';');
}
}
return result;
}
|
diff --git a/src/DVN-web/src/edu/harvard/iq/dvn/core/web/BasicSearchFragment.java b/src/DVN-web/src/edu/harvard/iq/dvn/core/web/BasicSearchFragment.java
index 44aee462..01f9bbce 100644
--- a/src/DVN-web/src/edu/harvard/iq/dvn/core/web/BasicSearchFragment.java
+++ b/src/DVN-web/src/edu/harvard/iq/dvn/core/web/BasicSearchFragment.java
@@ -1,117 +1,118 @@
package edu.harvard.iq.dvn.core.web;
import edu.harvard.iq.dvn.core.index.IndexServiceLocal;
import edu.harvard.iq.dvn.core.index.SearchTerm;
import edu.harvard.iq.dvn.core.study.StudyServiceLocal;
import edu.harvard.iq.dvn.core.study.StudyVersion;
import edu.harvard.iq.dvn.core.study.VariableServiceLocal;
import edu.harvard.iq.dvn.core.web.common.VDCBaseBean;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.ejb.EJB;
import edu.harvard.iq.dvn.core.vdc.VDCCollectionServiceLocal;
import edu.harvard.iq.dvn.core.vdc.VDCServiceLocal;
import javax.faces.bean.ViewScoped;
import javax.inject.Named;
@Named ("BasicSearchFragment")
@ViewScoped
public class BasicSearchFragment extends VDCBaseBean implements java.io.Serializable {
@EJB
IndexServiceLocal indexService;
@EJB
VariableServiceLocal varService;
@EJB
StudyServiceLocal studyService;
@EJB
VDCServiceLocal vdcService;
@EJB
VDCCollectionServiceLocal vdcCollectionService;
private String searchValue = "Search Studies";
private String searchField;
public String search_action() {
searchField = (searchField == null) ? "any" : searchField; // default searchField, in case no dropdown
List searchTerms = new ArrayList();
SearchTerm st = new SearchTerm();
st.setFieldName( searchField );
st.setValue( searchValue );
searchTerms.add(st);
List studies = new ArrayList();
Map variableMap = new HashMap();
Map versionMap = new HashMap();
List displayVersionList = new ArrayList();
if ( searchField.equals("variable") ) {
List variables = indexService.searchVariables(getVDCRequestBean().getCurrentVDC(), st);
varService.determineStudiesFromVariables(variables, studies, variableMap);
} else {
studies = indexService.search(getVDCRequestBean().getCurrentVDC(), searchTerms);
}
if (searchField.equals("any")) {
List<Long> versionIds = indexService.searchVersionUnf(getVDCRequestBean().getCurrentVDC(), searchValue);
Iterator iter = versionIds.iterator();
Long studyId = null;
while (iter.hasNext()) {
Long vId = (Long) iter.next();
StudyVersion sv = null;
try {
sv = studyService.getStudyVersionById(vId);
studyId = sv.getStudy().getId();
List<StudyVersion> svList = (List<StudyVersion>) versionMap.get(studyId);
if (svList == null) {
svList = new ArrayList<StudyVersion>();
}
svList.add(sv);
if (!studies.contains(studyId)) {
displayVersionList.add(studyId);
studies.add(studyId);
}
versionMap.put(studyId, svList);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
StudyListing sl = new StudyListing(StudyListing.SEARCH);
+ sl.setVdcId(getVDCRequestBean().getCurrentVDCId());
sl.setStudyIds(studies);
sl.setSearchTerms(searchTerms);
sl.setVariableMap(variableMap);
sl.setVersionMap(versionMap);
sl.setDisplayStudyVersionsList(displayVersionList);
//getVDCRequestBean().setStudyListing(sl);
String studyListingIndex = StudyListing.addToStudyListingMap(sl, getSessionMap());
return "/StudyListingPage.xhtml?faces-redirect=true&studyListingIndex=" + studyListingIndex + "&vdcId=" + getVDCRequestBean().getCurrentVDCId();
}
public void setSearchField(String searchField) {
this.searchField = searchField;
}
public void setSearchValue(String searchValue) {
this.searchValue = searchValue;
}
public String getSearchField() {
return searchField;
}
public String getSearchValue() {
return searchValue;
}
}
| true | true | public String search_action() {
searchField = (searchField == null) ? "any" : searchField; // default searchField, in case no dropdown
List searchTerms = new ArrayList();
SearchTerm st = new SearchTerm();
st.setFieldName( searchField );
st.setValue( searchValue );
searchTerms.add(st);
List studies = new ArrayList();
Map variableMap = new HashMap();
Map versionMap = new HashMap();
List displayVersionList = new ArrayList();
if ( searchField.equals("variable") ) {
List variables = indexService.searchVariables(getVDCRequestBean().getCurrentVDC(), st);
varService.determineStudiesFromVariables(variables, studies, variableMap);
} else {
studies = indexService.search(getVDCRequestBean().getCurrentVDC(), searchTerms);
}
if (searchField.equals("any")) {
List<Long> versionIds = indexService.searchVersionUnf(getVDCRequestBean().getCurrentVDC(), searchValue);
Iterator iter = versionIds.iterator();
Long studyId = null;
while (iter.hasNext()) {
Long vId = (Long) iter.next();
StudyVersion sv = null;
try {
sv = studyService.getStudyVersionById(vId);
studyId = sv.getStudy().getId();
List<StudyVersion> svList = (List<StudyVersion>) versionMap.get(studyId);
if (svList == null) {
svList = new ArrayList<StudyVersion>();
}
svList.add(sv);
if (!studies.contains(studyId)) {
displayVersionList.add(studyId);
studies.add(studyId);
}
versionMap.put(studyId, svList);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
StudyListing sl = new StudyListing(StudyListing.SEARCH);
sl.setStudyIds(studies);
sl.setSearchTerms(searchTerms);
sl.setVariableMap(variableMap);
sl.setVersionMap(versionMap);
sl.setDisplayStudyVersionsList(displayVersionList);
//getVDCRequestBean().setStudyListing(sl);
String studyListingIndex = StudyListing.addToStudyListingMap(sl, getSessionMap());
return "/StudyListingPage.xhtml?faces-redirect=true&studyListingIndex=" + studyListingIndex + "&vdcId=" + getVDCRequestBean().getCurrentVDCId();
}
| public String search_action() {
searchField = (searchField == null) ? "any" : searchField; // default searchField, in case no dropdown
List searchTerms = new ArrayList();
SearchTerm st = new SearchTerm();
st.setFieldName( searchField );
st.setValue( searchValue );
searchTerms.add(st);
List studies = new ArrayList();
Map variableMap = new HashMap();
Map versionMap = new HashMap();
List displayVersionList = new ArrayList();
if ( searchField.equals("variable") ) {
List variables = indexService.searchVariables(getVDCRequestBean().getCurrentVDC(), st);
varService.determineStudiesFromVariables(variables, studies, variableMap);
} else {
studies = indexService.search(getVDCRequestBean().getCurrentVDC(), searchTerms);
}
if (searchField.equals("any")) {
List<Long> versionIds = indexService.searchVersionUnf(getVDCRequestBean().getCurrentVDC(), searchValue);
Iterator iter = versionIds.iterator();
Long studyId = null;
while (iter.hasNext()) {
Long vId = (Long) iter.next();
StudyVersion sv = null;
try {
sv = studyService.getStudyVersionById(vId);
studyId = sv.getStudy().getId();
List<StudyVersion> svList = (List<StudyVersion>) versionMap.get(studyId);
if (svList == null) {
svList = new ArrayList<StudyVersion>();
}
svList.add(sv);
if (!studies.contains(studyId)) {
displayVersionList.add(studyId);
studies.add(studyId);
}
versionMap.put(studyId, svList);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
}
StudyListing sl = new StudyListing(StudyListing.SEARCH);
sl.setVdcId(getVDCRequestBean().getCurrentVDCId());
sl.setStudyIds(studies);
sl.setSearchTerms(searchTerms);
sl.setVariableMap(variableMap);
sl.setVersionMap(versionMap);
sl.setDisplayStudyVersionsList(displayVersionList);
//getVDCRequestBean().setStudyListing(sl);
String studyListingIndex = StudyListing.addToStudyListingMap(sl, getSessionMap());
return "/StudyListingPage.xhtml?faces-redirect=true&studyListingIndex=" + studyListingIndex + "&vdcId=" + getVDCRequestBean().getCurrentVDCId();
}
|
diff --git a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/EclipseTouchpoint.java b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/EclipseTouchpoint.java
index c79f858d4..0fba62685 100644
--- a/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/EclipseTouchpoint.java
+++ b/bundles/org.eclipse.equinox.p2.touchpoint.eclipse/src/org/eclipse/equinox/internal/p2/touchpoint/eclipse/EclipseTouchpoint.java
@@ -1,200 +1,200 @@
/*******************************************************************************
* Copyright (c) 2007, 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 API and implementation
* Code 9 - ongoing development
******************************************************************************/
package org.eclipse.equinox.internal.p2.touchpoint.eclipse;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.*;
import org.eclipse.core.runtime.*;
import org.eclipse.equinox.internal.p2.core.helpers.LogHelper;
import org.eclipse.equinox.internal.provisional.frameworkadmin.FrameworkAdminRuntimeException;
import org.eclipse.equinox.internal.provisional.p2.core.ProvisionException;
import org.eclipse.equinox.internal.provisional.p2.engine.*;
import org.eclipse.equinox.internal.provisional.p2.metadata.IArtifactKey;
import org.eclipse.equinox.internal.provisional.p2.metadata.IInstallableUnit;
import org.eclipse.equinox.p2.publisher.PublisherInfo;
import org.eclipse.equinox.p2.publisher.eclipse.BundleNestedAdvice;
import org.eclipse.equinox.p2.publisher.eclipse.BundlesAction;
import org.eclipse.osgi.service.resolver.BundleDescription;
import org.eclipse.osgi.util.NLS;
public class EclipseTouchpoint extends Touchpoint {
// TODO: phase id constants should be defined elsewhere.
public static final String INSTALL_PHASE_ID = "install"; //$NON-NLS-1$
public static final String UNINSTALL_PHASE_ID = "uninstall"; //$NON-NLS-1$
public static final String CONFIGURE_PHASE_ID = "configure"; //$NON-NLS-1$
public static final String UNCONFIGURE_PHASE_ID = "unconfigure"; //$NON-NLS-1$
public static final String PROFILE_PROP_LAUNCHER_NAME = "eclipse.touchpoint.launcherName"; //$NON-NLS-1$
public static final String PARM_MANIPULATOR = "manipulator"; //$NON-NLS-1$
public static final String PARM_PLATFORM_CONFIGURATION = "platformConfiguration"; //$NON-NLS-1$
public static final String PARM_SOURCE_BUNDLES = "sourceBundles"; //$NON-NLS-1$
public static final String PARM_IU = "iu"; //$NON-NLS-1$
public static final String PARM_INSTALL_FOLDER = "installFolder"; //$NON-NLS-1$
private static final String NATIVE_TOUCHPOINT_ID = "org.eclipse.equinox.p2.touchpoint.natives"; //$NON-NLS-1$
private static List NATIVE_ACTIONS = Arrays.asList(new String[] {"chmod", "link", "mkdir", "rmdir"}); //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$
private static Map manipulators = new WeakHashMap();
private static Map wrappers = new WeakHashMap();
private static Map sourceManipulators = new WeakHashMap();
private static synchronized LazyManipulator getManipulator(IProfile profile) {
LazyManipulator manipulator = (LazyManipulator) manipulators.get(profile);
if (manipulator == null) {
manipulator = new LazyManipulator(profile);
manipulators.put(profile, manipulator);
}
return manipulator;
}
private static synchronized void saveManipulator(IProfile profile) throws FrameworkAdminRuntimeException, IOException {
LazyManipulator manipulator = (LazyManipulator) manipulators.remove(profile);
if (manipulator != null)
manipulator.save(false);
}
private static synchronized PlatformConfigurationWrapper getPlatformConfigurationWrapper(IProfile profile, LazyManipulator manipulator) {
PlatformConfigurationWrapper wrapper = (PlatformConfigurationWrapper) wrappers.get(profile);
if (wrapper == null) {
File configLocation = Util.getConfigurationFolder(profile);
URI poolURI = Util.getBundlePoolLocation(profile);
wrapper = new PlatformConfigurationWrapper(configLocation, poolURI, manipulator);
wrappers.put(profile, wrapper);
}
return wrapper;
}
private static synchronized void savePlatformConfigurationWrapper(IProfile profile) throws ProvisionException {
PlatformConfigurationWrapper wrapper = (PlatformConfigurationWrapper) wrappers.remove(profile);
if (wrapper != null)
wrapper.save();
}
private static synchronized SourceManipulator getSourceManipulator(IProfile profile) {
SourceManipulator sourceManipulator = (SourceManipulator) sourceManipulators.get(profile);
if (sourceManipulator == null) {
sourceManipulator = new SourceManipulator(profile);
sourceManipulators.put(profile, sourceManipulator);
}
return sourceManipulator;
}
private static synchronized void saveSourceManipulator(IProfile profile) throws IOException {
SourceManipulator sourceManipulator = (SourceManipulator) sourceManipulators.remove(profile);
if (sourceManipulator != null)
sourceManipulator.save();
}
private static synchronized void clearProfileState(IProfile profile) {
manipulators.remove(profile);
wrappers.remove(profile);
sourceManipulators.remove(profile);
}
public IStatus commit(IProfile profile) {
try {
saveManipulator(profile);
} catch (RuntimeException e) {
return Util.createError(Messages.error_saving_manipulator, e);
} catch (IOException e) {
return Util.createError(Messages.error_saving_manipulator, e);
}
try {
savePlatformConfigurationWrapper(profile);
} catch (RuntimeException e) {
return Util.createError(Messages.error_saving_platform_configuration, e);
} catch (ProvisionException pe) {
return Util.createError(Messages.error_saving_platform_configuration, pe);
}
try {
saveSourceManipulator(profile);
} catch (RuntimeException e) {
return Util.createError(Messages.error_saving_source_bundles_list, e);
} catch (IOException e) {
return Util.createError(Messages.error_saving_source_bundles_list, e);
}
return Status.OK_STATUS;
}
public IStatus rollback(IProfile profile) {
clearProfileState(profile);
return Status.OK_STATUS;
}
public String qualifyAction(String actionId) {
String touchpointQualifier = NATIVE_ACTIONS.contains(actionId) ? NATIVE_TOUCHPOINT_ID : Activator.ID;
return touchpointQualifier + "." + actionId; //$NON-NLS-1$
}
public IStatus initializePhase(IProgressMonitor monitor, IProfile profile, String phaseId, Map touchpointParameters) {
touchpointParameters.put(PARM_INSTALL_FOLDER, Util.getInstallFolder(profile));
LazyManipulator manipulator = getManipulator(profile);
touchpointParameters.put(PARM_MANIPULATOR, manipulator);
touchpointParameters.put(PARM_SOURCE_BUNDLES, getSourceManipulator(profile));
touchpointParameters.put(PARM_PLATFORM_CONFIGURATION, getPlatformConfigurationWrapper(profile, manipulator));
return null;
}
public IStatus initializeOperand(IProfile profile, Operand operand, Map parameters) {
IInstallableUnit iu = (IInstallableUnit) parameters.get(PARM_IU);
if (iu != null && Boolean.valueOf(iu.getProperty(IInstallableUnit.PROP_PARTIAL_IU)).booleanValue()) {
IInstallableUnit preparedIU = prepareIU(iu, profile);
if (preparedIU == null)
return Util.createError(NLS.bind(Messages.failed_prepareIU, iu));
parameters.put(PARM_IU, preparedIU);
}
return Status.OK_STATUS;
}
private IInstallableUnit prepareIU(IInstallableUnit iu, IProfile profile) {
Class c = null;
try {
- c = Class.forName("org.eclipse.equinox.spi.p2.publisher.PublisherHelper"); //$NON-NLS-1$
+ c = Class.forName("org.eclipse.equinox.p2.publisher.eclipse.BundlesAction"); //$NON-NLS-1$
if (c != null)
c = Class.forName("org.eclipse.osgi.service.resolver.PlatformAdmin"); //$NON-NLS-1$
} catch (ClassNotFoundException e) {
throw new IllegalStateException(NLS.bind(Messages.generator_not_available, e.getMessage()));
}
if (c != null) {
IArtifactKey[] artifacts = iu.getArtifacts();
if (artifacts == null || artifacts.length == 0)
return iu;
IArtifactKey artifactKey = artifacts[0];
if (artifactKey == null)
return iu;
File bundleFile = Util.getArtifactFile(artifactKey, profile);
if (bundleFile == null) {
LogHelper.log(Util.createError(NLS.bind(Messages.artifact_file_not_found, artifactKey.toString())));
return null;
}
return createBundleIU(artifactKey, bundleFile);
}
// should not occur
throw new IllegalStateException(Messages.unexpected_prepareiu_error);
}
private IInstallableUnit createBundleIU(IArtifactKey artifactKey, File bundleFile) {
BundleDescription bundleDescription = BundlesAction.createBundleDescription(bundleFile);
PublisherInfo info = new PublisherInfo();
info.addAdvice(new BundleNestedAdvice());
return BundlesAction.createBundleIU(bundleDescription, (Map) bundleDescription.getUserObject(), bundleFile.isDirectory(), artifactKey, info);
}
}
| true | true | private IInstallableUnit prepareIU(IInstallableUnit iu, IProfile profile) {
Class c = null;
try {
c = Class.forName("org.eclipse.equinox.spi.p2.publisher.PublisherHelper"); //$NON-NLS-1$
if (c != null)
c = Class.forName("org.eclipse.osgi.service.resolver.PlatformAdmin"); //$NON-NLS-1$
} catch (ClassNotFoundException e) {
throw new IllegalStateException(NLS.bind(Messages.generator_not_available, e.getMessage()));
}
if (c != null) {
IArtifactKey[] artifacts = iu.getArtifacts();
if (artifacts == null || artifacts.length == 0)
return iu;
IArtifactKey artifactKey = artifacts[0];
if (artifactKey == null)
return iu;
File bundleFile = Util.getArtifactFile(artifactKey, profile);
if (bundleFile == null) {
LogHelper.log(Util.createError(NLS.bind(Messages.artifact_file_not_found, artifactKey.toString())));
return null;
}
return createBundleIU(artifactKey, bundleFile);
}
// should not occur
throw new IllegalStateException(Messages.unexpected_prepareiu_error);
}
| private IInstallableUnit prepareIU(IInstallableUnit iu, IProfile profile) {
Class c = null;
try {
c = Class.forName("org.eclipse.equinox.p2.publisher.eclipse.BundlesAction"); //$NON-NLS-1$
if (c != null)
c = Class.forName("org.eclipse.osgi.service.resolver.PlatformAdmin"); //$NON-NLS-1$
} catch (ClassNotFoundException e) {
throw new IllegalStateException(NLS.bind(Messages.generator_not_available, e.getMessage()));
}
if (c != null) {
IArtifactKey[] artifacts = iu.getArtifacts();
if (artifacts == null || artifacts.length == 0)
return iu;
IArtifactKey artifactKey = artifacts[0];
if (artifactKey == null)
return iu;
File bundleFile = Util.getArtifactFile(artifactKey, profile);
if (bundleFile == null) {
LogHelper.log(Util.createError(NLS.bind(Messages.artifact_file_not_found, artifactKey.toString())));
return null;
}
return createBundleIU(artifactKey, bundleFile);
}
// should not occur
throw new IllegalStateException(Messages.unexpected_prepareiu_error);
}
|
diff --git a/src/main/java/com/metaweb/gridworks/clustering/binning/BinningClusterer.java b/src/main/java/com/metaweb/gridworks/clustering/binning/BinningClusterer.java
index b83ca760..adb36009 100644
--- a/src/main/java/com/metaweb/gridworks/clustering/binning/BinningClusterer.java
+++ b/src/main/java/com/metaweb/gridworks/clustering/binning/BinningClusterer.java
@@ -1,151 +1,151 @@
package com.metaweb.gridworks.clustering.binning;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.TreeMap;
import java.util.Map.Entry;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONWriter;
import com.metaweb.gridworks.browsing.Engine;
import com.metaweb.gridworks.browsing.FilteredRows;
import com.metaweb.gridworks.browsing.RowVisitor;
import com.metaweb.gridworks.clustering.Clusterer;
import com.metaweb.gridworks.model.Cell;
import com.metaweb.gridworks.model.Project;
import com.metaweb.gridworks.model.Row;
public class BinningClusterer extends Clusterer {
private Keyer _keyer;
static protected Map<String, Keyer> _keyers = new HashMap<String, Keyer>();
List<Map<String,Integer>> _clusters;
static {
_keyers.put("fingerprint", new FingerprintKeyer());
_keyers.put("ngram-fingerprint", new NGramFingerprintKeyer());
_keyers.put("metaphone", new MetaphoneKeyer());
_keyers.put("double-metaphone", new DoubleMetaphoneKeyer());
_keyers.put("soundex", new SoundexKeyer());
}
class BinningRowVisitor implements RowVisitor {
Keyer _keyer;
Object[] _params;
JSONObject _config;
Map<String,Map<String,Integer>> _map = new HashMap<String,Map<String,Integer>>();
public BinningRowVisitor(Keyer k, JSONObject o) {
_keyer = k;
_config = o;
if (k instanceof NGramFingerprintKeyer) {
try {
int size = _config.getJSONObject("params").getInt("ngram-size");
_params = new Object[1];
_params[0] = size;
} catch (JSONException e) {
//Gridworks.warn("No params specified, using default");
}
}
}
public boolean visit(Project project, int rowIndex, Row row, boolean contextual) {
- Cell cell = row.cells.get(_colindex);
+ Cell cell = row.getCell(_colindex);
if (cell != null && cell.value != null) {
String v = cell.value.toString();
String s = (v instanceof String) ? ((String) v) : v.toString();
String key = _keyer.key(s,_params);
if (_map.containsKey(key)) {
Map<String,Integer> m = _map.get(key);
if (m.containsKey(v)) {
m.put(v, m.get(v) + 1);
} else {
m.put(v,1);
}
} else {
Map<String,Integer> m = new TreeMap<String,Integer>();
m.put(v,0);
_map.put(key, m);
}
}
return false;
}
public Map<String,Map<String,Integer>> getMap() {
return _map;
}
}
public class SizeComparator implements Comparator<Map<String,Integer>> {
public int compare(Map<String,Integer> o1, Map<String,Integer> o2) {
int s1 = o1.size();
int s2 = o2.size();
if (o1 == o2) {
int total1 = 0;
for (int i : o1.values()) {
total1 += i;
}
int total2 = 0;
for (int i : o2.values()) {
total2 += i;
}
return total2 - total1;
} else {
return s2 - s1;
}
}
}
public class EntriesComparator implements Comparator<Entry<String,Integer>> {
public int compare(Entry<String,Integer> o1, Entry<String,Integer> o2) {
return o2.getValue() - o1.getValue();
}
}
public void initializeFromJSON(Project project, JSONObject o) throws Exception {
super.initializeFromJSON(project, o);
_keyer = _keyers.get(o.getString("function").toLowerCase());
}
public void computeClusters(Engine engine) {
BinningRowVisitor visitor = new BinningRowVisitor(_keyer,_config);
FilteredRows filteredRows = engine.getAllFilteredRows(true);
filteredRows.accept(_project, visitor);
Map<String,Map<String,Integer>> map = visitor.getMap();
_clusters = new ArrayList<Map<String,Integer>>(map.values());
Collections.sort(_clusters, new SizeComparator());
}
public void write(JSONWriter writer, Properties options) throws JSONException {
EntriesComparator c = new EntriesComparator();
writer.array();
for (Map<String,Integer> m : _clusters) {
if (m.size() > 1) {
writer.array();
List<Entry<String,Integer>> entries = new ArrayList<Entry<String,Integer>>(m.entrySet());
Collections.sort(entries,c);
for (Entry<String,Integer> e : entries) {
writer.object();
writer.key("v"); writer.value(e.getKey());
writer.key("c"); writer.value(e.getValue());
writer.endObject();
}
writer.endArray();
}
}
writer.endArray();
}
}
| true | true | public boolean visit(Project project, int rowIndex, Row row, boolean contextual) {
Cell cell = row.cells.get(_colindex);
if (cell != null && cell.value != null) {
String v = cell.value.toString();
String s = (v instanceof String) ? ((String) v) : v.toString();
String key = _keyer.key(s,_params);
if (_map.containsKey(key)) {
Map<String,Integer> m = _map.get(key);
if (m.containsKey(v)) {
m.put(v, m.get(v) + 1);
} else {
m.put(v,1);
}
} else {
Map<String,Integer> m = new TreeMap<String,Integer>();
m.put(v,0);
_map.put(key, m);
}
}
return false;
}
| public boolean visit(Project project, int rowIndex, Row row, boolean contextual) {
Cell cell = row.getCell(_colindex);
if (cell != null && cell.value != null) {
String v = cell.value.toString();
String s = (v instanceof String) ? ((String) v) : v.toString();
String key = _keyer.key(s,_params);
if (_map.containsKey(key)) {
Map<String,Integer> m = _map.get(key);
if (m.containsKey(v)) {
m.put(v, m.get(v) + 1);
} else {
m.put(v,1);
}
} else {
Map<String,Integer> m = new TreeMap<String,Integer>();
m.put(v,0);
_map.put(key, m);
}
}
return false;
}
|
diff --git a/src/app/client/RetailStoreClientImplDriver3.java b/src/app/client/RetailStoreClientImplDriver3.java
index f2cb715..a9c3151 100644
--- a/src/app/client/RetailStoreClientImplDriver3.java
+++ b/src/app/client/RetailStoreClientImplDriver3.java
@@ -1,32 +1,32 @@
package app.client;
import java.io.IOException;
import app.orb.RetailStorePackage.InsufficientQuantity;
import app.orb.RetailStorePackage.NoSuchItem;
public class RetailStoreClientImplDriver3 extends RetailStoreClientImpl {
public RetailStoreClientImplDriver3(String customerID)
throws IOException {
super(customerID, null);
}
public void run() {
try {
for (int i = 0; i != 60; i++) {
- System.out.println("Attempting to purhcase 2 of 1000");
+ System.out.println("Attempting to purchase 1 of 1000");
purchaseItem(1000, 1); // should succeed
Thread.sleep(1000);
}
} catch (NoSuchItem e) {
System.err.println(getCustomerID() + ": The requested item does not exist!");
} catch (InsufficientQuantity e) {
System.err.println(getCustomerID() + ": There is not enough stock to fulfill your order!");
} catch (Exception e) {
System.err.println("Purchase exception: " + e.toString());
e.printStackTrace();
}
shutdown();
}
}
| true | true | public void run() {
try {
for (int i = 0; i != 60; i++) {
System.out.println("Attempting to purhcase 2 of 1000");
purchaseItem(1000, 1); // should succeed
Thread.sleep(1000);
}
} catch (NoSuchItem e) {
System.err.println(getCustomerID() + ": The requested item does not exist!");
} catch (InsufficientQuantity e) {
System.err.println(getCustomerID() + ": There is not enough stock to fulfill your order!");
} catch (Exception e) {
System.err.println("Purchase exception: " + e.toString());
e.printStackTrace();
}
shutdown();
}
| public void run() {
try {
for (int i = 0; i != 60; i++) {
System.out.println("Attempting to purchase 1 of 1000");
purchaseItem(1000, 1); // should succeed
Thread.sleep(1000);
}
} catch (NoSuchItem e) {
System.err.println(getCustomerID() + ": The requested item does not exist!");
} catch (InsufficientQuantity e) {
System.err.println(getCustomerID() + ": There is not enough stock to fulfill your order!");
} catch (Exception e) {
System.err.println("Purchase exception: " + e.toString());
e.printStackTrace();
}
shutdown();
}
|
diff --git a/plugins/org.eclipse.acceleo.parser/src/org/eclipse/acceleo/internal/parser/compiler/AcceleoParserUtils.java b/plugins/org.eclipse.acceleo.parser/src/org/eclipse/acceleo/internal/parser/compiler/AcceleoParserUtils.java
index 02d4c5af..47014013 100644
--- a/plugins/org.eclipse.acceleo.parser/src/org/eclipse/acceleo/internal/parser/compiler/AcceleoParserUtils.java
+++ b/plugins/org.eclipse.acceleo.parser/src/org/eclipse/acceleo/internal/parser/compiler/AcceleoParserUtils.java
@@ -1,294 +1,294 @@
/*******************************************************************************
* Copyright (c) 2008, 2012 Obeo.
* 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:
* Obeo - initial API and implementation
*******************************************************************************/
package org.eclipse.acceleo.internal.parser.compiler;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.security.CodeSource;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.eclipse.acceleo.common.IAcceleoConstants;
import org.eclipse.acceleo.internal.parser.cst.utils.Sequence;
import org.eclipse.acceleo.model.mtl.MtlPackage;
import org.eclipse.acceleo.model.mtl.resource.EMtlBinaryResourceFactoryImpl;
import org.eclipse.acceleo.model.mtl.resource.EMtlResourceFactoryImpl;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.URIConverter;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.ecore.xmi.impl.EcoreResourceFactoryImpl;
import org.eclipse.ocl.ecore.EcoreEnvironment;
import org.eclipse.ocl.ecore.EcoreEnvironmentFactory;
import org.eclipse.ocl.expressions.ExpressionsPackage;
/**
* Utility class used during the compilation.
*
* @author <a href="mailto:[email protected]">Stephane Begaudeau</a>
* @since 3.2
*/
public final class AcceleoParserUtils {
/**
* The constructor.
*/
private AcceleoParserUtils() {
// Hides the constructor.
}
/**
* Gets all the possible sequences to search when we use the given file in other files : '[import myGen',
* '[import org::eclipse::myGen', 'extends myGen', 'extends org::eclipse::myGen'...
*
* @param acceleoProject
* is the project
* @param file
* is the MTL file
* @return all the possible sequences to search for the given file
*/
public static List<Sequence> getImportSequencesToSearch(AcceleoProject acceleoProject, File file) {
List<Sequence> result = new ArrayList<Sequence>();
String simpleModuleName = file.getName();
if (simpleModuleName.endsWith(IAcceleoConstants.MTL_FILE_EXTENSION)) {
simpleModuleName = simpleModuleName.substring(0, simpleModuleName.length()
- (IAcceleoConstants.MTL_FILE_EXTENSION.length() + 1));
}
String[] tokens = new String[] {IAcceleoConstants.DEFAULT_BEGIN, IAcceleoConstants.IMPORT,
simpleModuleName, };
result.add(new Sequence(tokens));
tokens = new String[] {IAcceleoConstants.EXTENDS, simpleModuleName, };
result.add(new Sequence(tokens));
String fullModuleName = acceleoProject.getModuleQualifiedName(file);
tokens = new String[] {IAcceleoConstants.DEFAULT_BEGIN, IAcceleoConstants.IMPORT, fullModuleName, };
result.add(new Sequence(tokens));
tokens = new String[] {IAcceleoConstants.EXTENDS, fullModuleName, };
result.add(new Sequence(tokens));
return result;
}
/**
* Returns the set of uri of the emtls contained in the jar with the given URI.
*
* @param jar
* The URI of the jar file.
* @return The set of uri of the emtls contained in the jar with the given URI.
*/
public static Set<URI> getAllModules(URI jar) {
Set<URI> modulesURIs = new LinkedHashSet<URI>();
try {
String jarPath = jar.toString();
String osName = System.getProperty("os.name"); //$NON-NLS-1$
final String file = "file:"; //$NON-NLS-1$
- if (osName.indexOf("win") >= 0) { //$NON-NLS-1$
+ if (osName.indexOf("win") >= 0 || osName.indexOf("Win") >= 0) { //$NON-NLS-1$ //$NON-NLS-2$
// Windows
if (jarPath.startsWith("file:\\") || jarPath.startsWith("file:/")) { //$NON-NLS-1$ //$NON-NLS-2$
jarPath = jarPath.substring(6);
}
} else if (osName.indexOf("Mac") >= 0) { //$NON-NLS-1$
// Mac
if (jarPath.startsWith(file)) {
jarPath = jarPath.substring(5);
}
} else if (osName.indexOf("nux") >= 0 || osName.indexOf("nix") >= 0) { //$NON-NLS-1$ //$NON-NLS-2$
// Unix / Linux
if (jarPath.startsWith(file)) {
jarPath = jarPath.substring(5);
}
} else {
// Unix / Linux
if (jarPath.startsWith(file)) {
jarPath = jarPath.substring(5);
}
}
JarFile jarFile = new JarFile(jarPath);
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry nextElement = entries.nextElement();
String name = nextElement.getName();
if (!nextElement.isDirectory() && name.endsWith(IAcceleoConstants.EMTL_FILE_EXTENSION)) {
URI jarFileURI = URI.createFileURI(jarPath);
URI entryURI = URI.createURI(name);
URI uri = URI.createURI("jar:" + jarFileURI.toString() + "!/" + entryURI.toString()); //$NON-NLS-1$//$NON-NLS-2$
modulesURIs.add(uri);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return modulesURIs;
}
/**
* Returns the module name (a::b::c::d) of the resources at the given URI.
*
* @param moduleURI
* The URI of an emtl file.
* @return The module name (a::b::c::d) of the resources at the given URI.
*/
public static String getModuleName(URI moduleURI) {
String modulePath = moduleURI.toString();
if (modulePath.startsWith("jar:file:")) { //$NON-NLS-1$
int indexOf = modulePath.indexOf(".jar!/"); //$NON-NLS-1$
if (indexOf != -1) {
String moduleName = modulePath.substring(indexOf + ".jar!/".length()); //$NON-NLS-1$
if (moduleName.endsWith(IAcceleoConstants.EMTL_FILE_EXTENSION)) {
moduleName = moduleName.substring(0, moduleName.length()
- (IAcceleoConstants.EMTL_FILE_EXTENSION.length() + 1));
moduleName = moduleName.replace("/", IAcceleoConstants.NAMESPACE_SEPARATOR); //$NON-NLS-1$
return moduleName;
}
}
}
return null;
}
/**
* Delete the given directory.
*
* @param directory
* The directory.
* @return <code>true</code> if the directory has been deleted along with its content, <code>false</code>
* otherwise.
*/
public static boolean removeDirectory(File directory) {
boolean result = false;
if (!directory.exists()) {
result = true;
}
String[] list = directory.list();
// Some JVMs return null for File.list() when the
// directory is empty.
if (list != null) {
for (int i = 0; i < list.length; i++) {
File entry = new File(directory, list[i]);
// System.out.println("\tremoving entry " + entry);
if (entry.isDirectory()) {
if (!removeDirectory(entry)) {
result = false;
}
} else {
if (!entry.delete()) {
result = false;
}
}
}
}
result = directory.delete();
return result;
}
/**
* Register the necessary resource factories.
*
* @param resourceSet
* The resource set.
*/
public static void registerResourceFactories(ResourceSet resourceSet) {
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put("ecore", //$NON-NLS-1$
new EcoreResourceFactoryImpl());
resourceSet.getResourceFactoryRegistry().getContentTypeToFactoryMap().put(
IAcceleoConstants.BINARY_CONTENT_TYPE, new EMtlBinaryResourceFactoryImpl());
resourceSet.getResourceFactoryRegistry().getContentTypeToFactoryMap().put(
IAcceleoConstants.XMI_CONTENT_TYPE, new EMtlResourceFactoryImpl());
Resource.Factory.Registry.INSTANCE.getExtensionToFactoryMap().put("ecore", //$NON-NLS-1$
new EcoreResourceFactoryImpl());
Resource.Factory.Registry.INSTANCE.getContentTypeToFactoryMap().put(
IAcceleoConstants.BINARY_CONTENT_TYPE, new EMtlBinaryResourceFactoryImpl());
Resource.Factory.Registry.INSTANCE.getContentTypeToFactoryMap().put(
IAcceleoConstants.XMI_CONTENT_TYPE, new EMtlResourceFactoryImpl());
}
/**
* This will update the resource set's package registry with all usual EPackages.
*
* @param resourceSet
* The resource set.
*/
public static void registerPackages(ResourceSet resourceSet) {
EPackage.Registry.INSTANCE.put(EcorePackage.eINSTANCE.getNsURI(), EcorePackage.eINSTANCE);
EPackage.Registry.INSTANCE.put(org.eclipse.ocl.ecore.EcorePackage.eINSTANCE.getNsURI(),
org.eclipse.ocl.ecore.EcorePackage.eINSTANCE);
EPackage.Registry.INSTANCE.put(ExpressionsPackage.eINSTANCE.getNsURI(), ExpressionsPackage.eINSTANCE);
EPackage.Registry.INSTANCE.put(MtlPackage.eINSTANCE.getNsURI(), MtlPackage.eINSTANCE);
EPackage.Registry.INSTANCE.put("http://www.eclipse.org/ocl/1.1.0/oclstdlib.ecore", //$NON-NLS-1$
getOCLStdLibPackage());
}
/**
* Returns the package containing the OCL standard library.
*
* @return The package containing the OCL standard library.
*/
private static EPackage getOCLStdLibPackage() {
EcoreEnvironmentFactory factory = new EcoreEnvironmentFactory();
EcoreEnvironment environment = (EcoreEnvironment)factory.createEnvironment();
EPackage oclStdLibPackage = (EPackage)EcoreUtil.getRootContainer(environment.getOCLStandardLibrary()
.getBag());
environment.dispose();
return oclStdLibPackage;
}
/**
* Register the libraries.
*
* @param resourceSet
* The resource set.
*/
public static void registerLibraries(ResourceSet resourceSet) {
CodeSource acceleoModel = MtlPackage.class.getProtectionDomain().getCodeSource();
if (acceleoModel != null) {
String libraryLocation = acceleoModel.getLocation().toString();
if (libraryLocation.endsWith(".jar")) { //$NON-NLS-1$
libraryLocation = "jar:" + libraryLocation + '!'; //$NON-NLS-1$
} else if (libraryLocation.startsWith("file:/") && libraryLocation.endsWith("bin/")) { //$NON-NLS-1$ //$NON-NLS-2$
libraryLocation = libraryLocation.substring(6, libraryLocation.length() - 4);
}
String std = libraryLocation + "model/mtlstdlib.ecore"; //$NON-NLS-1$
String nonstd = libraryLocation + "model/mtlnonstdlib.ecore"; //$NON-NLS-1$
URL stdlib = MtlPackage.class.getResource("/model/mtlstdlib.ecore"); //$NON-NLS-1$
URL resource = MtlPackage.class.getResource("/model/mtlnonstdlib.ecore"); //$NON-NLS-1$
if (stdlib != null && resource != null) {
URIConverter.URI_MAP
.put(URI.createURI("http://www.eclipse.org/acceleo/mtl/3.0/mtlstdlib.ecore"), URI.createURI(stdlib.toString())); //$NON-NLS-1$
URIConverter.URI_MAP
.put(URI.createURI("http://www.eclipse.org/acceleo/mtl/3.0/mtlnonstdlib.ecore"), URI.createURI(resource.toString())); //$NON-NLS-1$
} else {
URIConverter.URI_MAP
.put(URI.createURI("http://www.eclipse.org/acceleo/mtl/3.0/mtlstdlib.ecore"), URI.createFileURI(std)); //$NON-NLS-1$
URIConverter.URI_MAP
.put(URI.createURI("http://www.eclipse.org/acceleo/mtl/3.0/mtlnonstdlib.ecore"), URI.createFileURI(nonstd)); //$NON-NLS-1$
}
} else {
System.err.println("Coudln't retrieve location of plugin 'org.eclipse.acceleo.model'."); //$NON-NLS-1$
}
}
}
| true | true | public static Set<URI> getAllModules(URI jar) {
Set<URI> modulesURIs = new LinkedHashSet<URI>();
try {
String jarPath = jar.toString();
String osName = System.getProperty("os.name"); //$NON-NLS-1$
final String file = "file:"; //$NON-NLS-1$
if (osName.indexOf("win") >= 0) { //$NON-NLS-1$
// Windows
if (jarPath.startsWith("file:\\") || jarPath.startsWith("file:/")) { //$NON-NLS-1$ //$NON-NLS-2$
jarPath = jarPath.substring(6);
}
} else if (osName.indexOf("Mac") >= 0) { //$NON-NLS-1$
// Mac
if (jarPath.startsWith(file)) {
jarPath = jarPath.substring(5);
}
} else if (osName.indexOf("nux") >= 0 || osName.indexOf("nix") >= 0) { //$NON-NLS-1$ //$NON-NLS-2$
// Unix / Linux
if (jarPath.startsWith(file)) {
jarPath = jarPath.substring(5);
}
} else {
// Unix / Linux
if (jarPath.startsWith(file)) {
jarPath = jarPath.substring(5);
}
}
JarFile jarFile = new JarFile(jarPath);
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry nextElement = entries.nextElement();
String name = nextElement.getName();
if (!nextElement.isDirectory() && name.endsWith(IAcceleoConstants.EMTL_FILE_EXTENSION)) {
URI jarFileURI = URI.createFileURI(jarPath);
URI entryURI = URI.createURI(name);
URI uri = URI.createURI("jar:" + jarFileURI.toString() + "!/" + entryURI.toString()); //$NON-NLS-1$//$NON-NLS-2$
modulesURIs.add(uri);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return modulesURIs;
}
| public static Set<URI> getAllModules(URI jar) {
Set<URI> modulesURIs = new LinkedHashSet<URI>();
try {
String jarPath = jar.toString();
String osName = System.getProperty("os.name"); //$NON-NLS-1$
final String file = "file:"; //$NON-NLS-1$
if (osName.indexOf("win") >= 0 || osName.indexOf("Win") >= 0) { //$NON-NLS-1$ //$NON-NLS-2$
// Windows
if (jarPath.startsWith("file:\\") || jarPath.startsWith("file:/")) { //$NON-NLS-1$ //$NON-NLS-2$
jarPath = jarPath.substring(6);
}
} else if (osName.indexOf("Mac") >= 0) { //$NON-NLS-1$
// Mac
if (jarPath.startsWith(file)) {
jarPath = jarPath.substring(5);
}
} else if (osName.indexOf("nux") >= 0 || osName.indexOf("nix") >= 0) { //$NON-NLS-1$ //$NON-NLS-2$
// Unix / Linux
if (jarPath.startsWith(file)) {
jarPath = jarPath.substring(5);
}
} else {
// Unix / Linux
if (jarPath.startsWith(file)) {
jarPath = jarPath.substring(5);
}
}
JarFile jarFile = new JarFile(jarPath);
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry nextElement = entries.nextElement();
String name = nextElement.getName();
if (!nextElement.isDirectory() && name.endsWith(IAcceleoConstants.EMTL_FILE_EXTENSION)) {
URI jarFileURI = URI.createFileURI(jarPath);
URI entryURI = URI.createURI(name);
URI uri = URI.createURI("jar:" + jarFileURI.toString() + "!/" + entryURI.toString()); //$NON-NLS-1$//$NON-NLS-2$
modulesURIs.add(uri);
}
}
} catch (IOException e) {
e.printStackTrace();
}
return modulesURIs;
}
|
diff --git a/ImportPlugin/src/org/gephi/io/importer/plugin/database/EdgeListDatabaseImpl.java b/ImportPlugin/src/org/gephi/io/importer/plugin/database/EdgeListDatabaseImpl.java
index df75131be..5ce6bc4b7 100644
--- a/ImportPlugin/src/org/gephi/io/importer/plugin/database/EdgeListDatabaseImpl.java
+++ b/ImportPlugin/src/org/gephi/io/importer/plugin/database/EdgeListDatabaseImpl.java
@@ -1,115 +1,117 @@
/*
Copyright 2008-2010 Gephi
Authors : Mathieu Bastian <[email protected]>
Website : http://www.gephi.org
This file is part of Gephi.
DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
Copyright 2011 Gephi Consortium. All rights reserved.
The contents of this file are subject to the terms of either the GNU
General Public License Version 3 only ("GPL") or the Common
Development and Distribution License("CDDL") (collectively, the
"License"). You may not use this file except in compliance with the
License. You can obtain a copy of the License at
http://gephi.org/about/legal/license-notice/
or /cddl-1.0.txt and /gpl-3.0.txt. See the License for the
specific language governing permissions and limitations under the
License. When distributing the software, include this License Header
Notice in each file and include the License files at
/cddl-1.0.txt and /gpl-3.0.txt. If applicable, add the following below the
License Header, with the fields enclosed by brackets [] replaced by
your own identifying information:
"Portions Copyrighted [year] [name of copyright owner]"
If you wish your version of this file to be governed by only the CDDL
or only the GPL Version 3, indicate your decision by adding
"[Contributor] elects to include this software in this distribution
under the [CDDL or GPL Version 3] license." If you do not indicate a
single choice of license, a recipient has the option to distribute
your version of this file under either the CDDL, the GPL Version 3 or
to extend the choice of license to its licensees as provided above.
However, if you add GPL Version 3 code and therefore, elected the GPL
Version 3 license, then the option applies only if the new code is
made subject to such option by the copyright holder.
Contributor(s):
Portions Copyrighted 2011 Gephi Consortium.
*/
package org.gephi.io.importer.plugin.database;
import org.gephi.io.importer.api.AbstractDatabase;
import org.gephi.io.importer.api.PropertiesAssociations.EdgeProperties;
import org.gephi.io.importer.api.PropertiesAssociations.NodeProperties;
/**
*
* @author Mathieu Bastian
*/
public class EdgeListDatabaseImpl extends AbstractDatabase {
private String nodeQuery;
private String edgeQuery;
private String nodeAttributesQuery;
private String edgeAttributesQuery;
public EdgeListDatabaseImpl() {
//Default node associations
properties.addNodePropertyAssociation(NodeProperties.ID, "id");
properties.addNodePropertyAssociation(NodeProperties.LABEL, "label");
properties.addNodePropertyAssociation(NodeProperties.X, "x");
properties.addNodePropertyAssociation(NodeProperties.Y, "y");
properties.addNodePropertyAssociation(NodeProperties.SIZE, "size");
+ properties.addNodePropertyAssociation(NodeProperties.COLOR, "color");
properties.addNodePropertyAssociation(NodeProperties.START, "start");
properties.addNodePropertyAssociation(NodeProperties.END, "end");
properties.addNodePropertyAssociation(NodeProperties.START, "start_open");
properties.addNodePropertyAssociation(NodeProperties.END_OPEN, "end_open");
//Default edge associations
properties.addEdgePropertyAssociation(EdgeProperties.ID, "id");
properties.addEdgePropertyAssociation(EdgeProperties.SOURCE, "source");
properties.addEdgePropertyAssociation(EdgeProperties.TARGET, "target");
properties.addEdgePropertyAssociation(EdgeProperties.LABEL, "label");
properties.addEdgePropertyAssociation(EdgeProperties.WEIGHT, "weight");
+ properties.addNodePropertyAssociation(NodeProperties.COLOR, "color");
properties.addEdgePropertyAssociation(EdgeProperties.START, "start");
properties.addEdgePropertyAssociation(EdgeProperties.END, "end");
properties.addEdgePropertyAssociation(EdgeProperties.START, "start_open");
properties.addEdgePropertyAssociation(EdgeProperties.END_OPEN, "end_open");
}
public String getEdgeAttributesQuery() {
return edgeAttributesQuery;
}
public void setEdgeAttributesQuery(String edgeAttributesQuery) {
this.edgeAttributesQuery = edgeAttributesQuery;
}
public String getEdgeQuery() {
return edgeQuery;
}
public void setEdgeQuery(String edgeQuery) {
this.edgeQuery = edgeQuery;
}
public String getNodeAttributesQuery() {
return nodeAttributesQuery;
}
public void setNodeAttributesQuery(String nodeAttributesQuery) {
this.nodeAttributesQuery = nodeAttributesQuery;
}
public String getNodeQuery() {
return nodeQuery;
}
public void setNodeQuery(String nodeQuery) {
this.nodeQuery = nodeQuery;
}
}
| false | true | public EdgeListDatabaseImpl() {
//Default node associations
properties.addNodePropertyAssociation(NodeProperties.ID, "id");
properties.addNodePropertyAssociation(NodeProperties.LABEL, "label");
properties.addNodePropertyAssociation(NodeProperties.X, "x");
properties.addNodePropertyAssociation(NodeProperties.Y, "y");
properties.addNodePropertyAssociation(NodeProperties.SIZE, "size");
properties.addNodePropertyAssociation(NodeProperties.START, "start");
properties.addNodePropertyAssociation(NodeProperties.END, "end");
properties.addNodePropertyAssociation(NodeProperties.START, "start_open");
properties.addNodePropertyAssociation(NodeProperties.END_OPEN, "end_open");
//Default edge associations
properties.addEdgePropertyAssociation(EdgeProperties.ID, "id");
properties.addEdgePropertyAssociation(EdgeProperties.SOURCE, "source");
properties.addEdgePropertyAssociation(EdgeProperties.TARGET, "target");
properties.addEdgePropertyAssociation(EdgeProperties.LABEL, "label");
properties.addEdgePropertyAssociation(EdgeProperties.WEIGHT, "weight");
properties.addEdgePropertyAssociation(EdgeProperties.START, "start");
properties.addEdgePropertyAssociation(EdgeProperties.END, "end");
properties.addEdgePropertyAssociation(EdgeProperties.START, "start_open");
properties.addEdgePropertyAssociation(EdgeProperties.END_OPEN, "end_open");
}
| public EdgeListDatabaseImpl() {
//Default node associations
properties.addNodePropertyAssociation(NodeProperties.ID, "id");
properties.addNodePropertyAssociation(NodeProperties.LABEL, "label");
properties.addNodePropertyAssociation(NodeProperties.X, "x");
properties.addNodePropertyAssociation(NodeProperties.Y, "y");
properties.addNodePropertyAssociation(NodeProperties.SIZE, "size");
properties.addNodePropertyAssociation(NodeProperties.COLOR, "color");
properties.addNodePropertyAssociation(NodeProperties.START, "start");
properties.addNodePropertyAssociation(NodeProperties.END, "end");
properties.addNodePropertyAssociation(NodeProperties.START, "start_open");
properties.addNodePropertyAssociation(NodeProperties.END_OPEN, "end_open");
//Default edge associations
properties.addEdgePropertyAssociation(EdgeProperties.ID, "id");
properties.addEdgePropertyAssociation(EdgeProperties.SOURCE, "source");
properties.addEdgePropertyAssociation(EdgeProperties.TARGET, "target");
properties.addEdgePropertyAssociation(EdgeProperties.LABEL, "label");
properties.addEdgePropertyAssociation(EdgeProperties.WEIGHT, "weight");
properties.addNodePropertyAssociation(NodeProperties.COLOR, "color");
properties.addEdgePropertyAssociation(EdgeProperties.START, "start");
properties.addEdgePropertyAssociation(EdgeProperties.END, "end");
properties.addEdgePropertyAssociation(EdgeProperties.START, "start_open");
properties.addEdgePropertyAssociation(EdgeProperties.END_OPEN, "end_open");
}
|
diff --git a/svnkit/src/org/tmatesoft/svn/core/internal/wc/SVNFileUtil.java b/svnkit/src/org/tmatesoft/svn/core/internal/wc/SVNFileUtil.java
index e020789c3..0a289c698 100644
--- a/svnkit/src/org/tmatesoft/svn/core/internal/wc/SVNFileUtil.java
+++ b/svnkit/src/org/tmatesoft/svn/core/internal/wc/SVNFileUtil.java
@@ -1,1464 +1,1464 @@
/*
* ====================================================================
* Copyright (c) 2004-2007 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.wc;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.io.Reader;
import java.io.Writer;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.CharsetDecoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Properties;
import java.util.StringTokenizer;
import org.tmatesoft.svn.core.SVNErrorCode;
import org.tmatesoft.svn.core.SVNErrorMessage;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.internal.util.SVNFormatUtil;
import org.tmatesoft.svn.core.internal.util.SVNPathUtil;
import org.tmatesoft.svn.core.internal.util.jna.SVNJNAUtil;
import org.tmatesoft.svn.core.internal.wc.admin.SVNTranslator;
import org.tmatesoft.svn.core.wc.ISVNEventHandler;
import org.tmatesoft.svn.core.wc.ISVNOptions;
import org.tmatesoft.svn.util.SVNDebugLog;
/**
* @version 1.1.1
* @author TMate Software Ltd., Peter Skoog
*/
public class SVNFileUtil {
private static final String ID_COMMAND;
private static final String LN_COMMAND;
public static final String LS_COMMAND;
private static final String CHMOD_COMMAND;
private static final String ATTRIB_COMMAND;
private static final String ENV_COMMAND;
public final static boolean isWindows;
public final static boolean isOS2;
public final static boolean isOSX;
public final static boolean isBSD;
public static boolean isLinux;
public final static boolean isOpenVMS;
public static final int STREAM_CHUNK_SIZE = 16384;
public final static OutputStream DUMMY_OUT = new OutputStream() {
public void write(int b) throws IOException {
}
};
public final static InputStream DUMMY_IN = new InputStream() {
public int read() throws IOException {
return -1;
}
};
private static String nativeEOLMarker;
private static String ourGroupID;
private static String ourUserID;
private static File ourAppDataPath;
private static String ourAdminDirectoryName;
private static File ourSystemAppDataPath;
private static volatile boolean ourIsSleepForTimeStamp = true;
public static final String BINARY_MIME_TYPE = "application/octet-stream";
static {
String osName = System.getProperty("os.name");
boolean windows = osName != null && osName.toLowerCase().indexOf("windows") >= 0;
if (!windows && osName != null) {
windows = osName.toLowerCase().indexOf("os/2") >= 0;
isOS2 = windows;
} else {
isOS2 = false;
}
isWindows = windows;
isOSX = !isWindows && osName != null && osName.toLowerCase().indexOf("mac") >= 0;
isLinux = !isWindows && osName != null && osName.toLowerCase().indexOf("linux") >= 0;
isBSD = !isWindows && !isLinux && osName != null && osName.toLowerCase().indexOf("bsd") >= 0;
isOpenVMS = osName != null && !isWindows && !isOSX && osName.toLowerCase().indexOf("openvms") >= 0;
if (isOpenVMS) {
setAdminDirectoryName("_svn");
}
String prefix = "svnkit.program.";
Properties props = new Properties();
InputStream is = SVNFileUtil.class.getResourceAsStream("/svnkit.runtime.properties");
if (is != null) {
try {
props.load(is);
} catch (IOException e) {
} finally {
SVNFileUtil.closeFile(is);
}
}
ID_COMMAND = props.getProperty(prefix + "id", "id");
LN_COMMAND = props.getProperty(prefix + "ln", "ln");
LS_COMMAND = props.getProperty(prefix + "ls", "ls");
CHMOD_COMMAND = props.getProperty(prefix + "chmod", "chmod");
ATTRIB_COMMAND = props.getProperty(prefix + "attrib", "attrib");
ENV_COMMAND = props.getProperty(prefix + "env", "env");
}
public static File getParentFile(File file) {
String path = file.getAbsolutePath();
path = path.replace(File.separatorChar, '/');
path = SVNPathUtil.canonicalizePath(path);
int up = 0;
while (path.endsWith("/..")) {
path = SVNPathUtil.removeTail(path);
up++;
}
for(int i = 0; i < up; i++) {
path = SVNPathUtil.removeTail(path);
}
path = path.replace('/', File.separatorChar);
file = new File(path);
return file.getParentFile();
}
public static String readFile(File file) throws SVNException {
InputStream is = null;
try {
is = openFileForReading(file);
return readFile(is);
} catch (IOException ioe) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Can not read from file ''{0}'': {1}", new Object[] {file, ioe.getLocalizedMessage()});
SVNErrorManager.error(err);
} finally {
closeFile(is);
}
return null;
}
public static String readFile(InputStream input) throws IOException {
byte[] buf = new byte[STREAM_CHUNK_SIZE];
StringBuffer result = new StringBuffer();
int r = -1;
while ((r = input.read(buf)) != -1) {
result.append(new String(buf, 0, r, "UTF-8"));
}
return result.toString();
}
public static String getBasePath(File file) {
File base = file.getParentFile();
while (base != null) {
if (base.isDirectory()) {
File adminDir = new File(base, getAdminDirectoryName());
if (adminDir.exists() && adminDir.isDirectory()) {
break;
}
}
base = base.getParentFile();
}
String path = file.getAbsolutePath();
if (base != null) {
path = path.substring(base.getAbsolutePath().length());
}
path = path.replace(File.separatorChar, '/');
if (path.startsWith("/")) {
path = path.substring(1);
}
return path;
}
public static void createEmptyFile(File file) throws SVNException {
boolean created;
if (file != null && file.getParentFile() != null && !file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
try {
created = file != null ? file.createNewFile() : false;
} catch (IOException e) {
created = false;
}
if (!created) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot create new file ''{0}''", file);
SVNErrorManager.error(err);
}
}
/**
* An internal method for ASCII bytes to write only!
*
* @param file
* @param contents
* @throws SVNException
*/
public static void createFile(File file, String contents, String charSet) throws SVNException {
createEmptyFile(file);
if (contents == null || contents.length() == 0) {
return;
}
OutputStream os = null;
try {
os = SVNFileUtil.openFileForWriting(file);
if (charSet != null) {
os.write(contents.getBytes(charSet));
} else {
os.write(contents.getBytes());
}
} catch (IOException ioe) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Can not write to file ''{0}'': {1}", new Object[] {file, ioe.getLocalizedMessage()});
SVNErrorManager.error(err, ioe);
} catch (SVNException svne) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Can not write to file ''{0}''", file);
SVNErrorManager.error(err, svne);
} finally {
SVNFileUtil.closeFile(os);
}
}
public static void writeVersionFile(File file, int version) throws SVNException {
if (version < 0) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.INCORRECT_PARAMS,
"Version {0} is not non-negative", new Integer(version));
SVNErrorManager.error(err);
}
String contents = version + "\n";
File tmpFile = SVNFileUtil.createUniqueFile(file.getParentFile(), file.getName(), ".tmp");
OutputStream os = null;
try {
os = SVNFileUtil.openFileForWriting(tmpFile);
os.write(contents.getBytes("US-ASCII"));
} catch (IOException e) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e.getLocalizedMessage());
SVNErrorManager.error(err, e);
} finally {
SVNFileUtil.closeFile(os);
}
if (isWindows) {
setReadonly(file, false);
}
SVNFileUtil.rename(tmpFile, file);
setReadonly(file, true);
}
public static File createUniqueFile(File parent, String name, String suffix) throws SVNException {
File file = new File(parent, name + suffix);
for (int i = 1; i < 99999; i++) {
if (SVNFileType.getType(file) == SVNFileType.NONE) {
return file;
}
file = new File(parent, name + "." + i + suffix);
}
if (SVNFileType.getType(file) == SVNFileType.NONE) {
return file;
}
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_UNIQUE_NAMES_EXHAUSTED, "Unable to make name for ''{0}''", new File(parent, name));
SVNErrorManager.error(err);
return null;
}
public static void rename(File src, File dst) throws SVNException {
if (SVNFileType.getType(src) == SVNFileType.NONE) {
deleteFile(dst);
return;
}
if (dst.isDirectory()) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot rename file ''{0}'' to ''{1}''; file ''{1}'' is a directory", new Object[] {src, dst});
SVNErrorManager.error(err);
}
boolean renamed = false;
if (!isWindows) {
renamed = src.renameTo(dst);
} else {
if (SVNJNAUtil.moveFile(src, dst)) {
renamed = true;
} else {
boolean wasRO = dst.exists() && !dst.canWrite();
setReadonly(src, false);
setReadonly(dst, false);
// use special loop on windows.
for (int i = 0; i < 10; i++) {
dst.delete();
if (src.renameTo(dst)) {
if (wasRO && !isOpenVMS) {
dst.setReadOnly();
}
return;
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
}
}
if (!renamed) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot rename file ''{0}'' to ''{1}''", new Object[] {src, dst});
SVNErrorManager.error(err);
}
}
public static boolean setReadonly(File file, boolean readonly) {
if (!file.exists()) {
return false;
}
if (isOpenVMS) {
// Never set readOnly for OpenVMS
return true;
}
if (readonly) {
return file.setReadOnly();
}
if (isWindows) {
if (SVNJNAUtil.setWritable(file)) {
return true;
}
} else if (isLinux || isOSX || isBSD) {
if (SVNJNAUtil.setWritable(file)) {
return true;
}
}
if (file.canWrite()) {
return true;
}
try {
if (file.length() < 1024 * 100) {
// faster way for small files.
File tmp = createUniqueFile(file.getParentFile(), file.getName(), ".ro");
copyFile(file, tmp, false);
copyFile(tmp, file, false);
deleteFile(tmp);
} else {
if (isWindows) {
Process p = Runtime.getRuntime().exec(ATTRIB_COMMAND + " -R \"" + file.getAbsolutePath() + "\"");
p.waitFor();
} else {
execCommand(new String[] {
CHMOD_COMMAND, "ugo+w", file.getAbsolutePath()
});
}
}
} catch (Throwable th) {
SVNDebugLog.getDefaultLog().info(th);
return false;
}
return true;
}
public static void setExecutable(File file, boolean executable) {
if (isWindows || isOpenVMS ||
file == null || !file.exists() || SVNFileType.getType(file) == SVNFileType.SYMLINK) {
return;
}
if (SVNJNAUtil.setExecutable(file, executable)) {
return;
}
try {
if (file.canWrite()) {
execCommand(new String[] {
CHMOD_COMMAND, executable ? "ugo+x" : "ugo-x", file.getAbsolutePath()
});
}
} catch (Throwable th) {
SVNDebugLog.getDefaultLog().info(th);
}
}
public static File resolveSymlinkToFile(File file) {
File targetFile = file;
while (SVNFileType.getType(targetFile) == SVNFileType.SYMLINK) {
String symlinkName = getSymlinkName(targetFile);
if (symlinkName == null) {
return null;
}
if (symlinkName.startsWith("/")) {
targetFile = new File(symlinkName);
} else {
targetFile = new File(targetFile.getParentFile(), symlinkName);
}
}
if (targetFile == null || !targetFile.isFile()) {
return null;
}
return targetFile;
}
public static void copy(File src, File dst, boolean safe, boolean copyAdminDirectories) throws SVNException {
SVNFileType srcType = SVNFileType.getType(src);
if (srcType == SVNFileType.FILE) {
copyFile(src, dst, safe);
} else if (srcType == SVNFileType.DIRECTORY) {
copyDirectory(src, dst, copyAdminDirectories, null);
} else if (srcType == SVNFileType.SYMLINK) {
String name = SVNFileUtil.getSymlinkName(src);
if (name != null) {
SVNFileUtil.createSymlink(dst, name);
}
}
}
public static void copyFile(File src, File dst, boolean safe) throws SVNException {
if (src == null || dst == null) {
return;
}
if (src.equals(dst)) {
return;
}
if (!src.exists()) {
dst.delete();
return;
}
File tmpDst = dst;
if (SVNFileType.getType(dst) != SVNFileType.NONE) {
if (safe) {
tmpDst = createUniqueFile(dst.getParentFile(), ".copy", ".tmp");
} else {
dst.delete();
}
}
boolean executable = isExecutable(src);
dst.getParentFile().mkdirs();
FileChannel srcChannel = null;
FileChannel dstChannel = null;
FileInputStream is = null;
FileOutputStream os = null;
SVNErrorMessage error = null;
try {
is = createFileInputStream(src);
srcChannel = is.getChannel();
- os = createFileOutputStream(dst, false);
+ os = createFileOutputStream(tmpDst, false);
dstChannel = os.getChannel();
long totalSize = srcChannel.size();
long toCopy = totalSize;
while (toCopy > 0) {
toCopy -= dstChannel.transferFrom(srcChannel, totalSize - toCopy, toCopy);
}
} catch (IOException e) {
error = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot copy file ''{0}'' to ''{1}'': {2}", new Object[] {
src, dst, e.getLocalizedMessage()
});
} finally {
if (srcChannel != null) {
try {
srcChannel.close();
} catch (IOException e) {
//
}
}
if (dstChannel != null) {
try {
dstChannel.close();
} catch (IOException e) {
//
}
}
SVNFileUtil.closeFile(is);
SVNFileUtil.closeFile(os);
}
if (error != null) {
error = null;
InputStream sis = null;
OutputStream dos = null;
try {
sis = SVNFileUtil.openFileForReading(src);
dos = SVNFileUtil.openFileForWriting(dst);
SVNTranslator.copy(sis, dos);
} catch (IOException e) {
error = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot copy file ''{0}'' to ''{1}'': {2}", new Object[] {
src, dst, e.getLocalizedMessage()
});
} finally {
SVNFileUtil.closeFile(dos);
SVNFileUtil.closeFile(sis);
}
}
if (error != null) {
SVNErrorManager.error(error);
}
if (safe && tmpDst != dst) {
rename(tmpDst, dst);
}
if (executable) {
setExecutable(dst, true);
}
dst.setLastModified(src.lastModified());
}
public static boolean createSymlink(File link, File linkName) throws SVNException {
if (isWindows || isOpenVMS) {
return false;
}
if (SVNFileType.getType(link) != SVNFileType.NONE) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot create symbolic link ''{0}''; file already exists", link);
SVNErrorManager.error(err);
}
String fileContents = "";
try {
fileContents = readSingleLine(linkName);
} catch (IOException e) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e.getLocalizedMessage());
SVNErrorManager.error(err, e);
}
if (fileContents.startsWith("link ")) {
fileContents = fileContents.substring("link".length()).trim();
return createSymlink(link, fileContents);
}
//create file using internal representation
createFile(link, fileContents, "UTF-8");
return true;
}
public static boolean createSymlink(File link, String linkName) {
if (SVNJNAUtil.createSymlink(link, linkName)) {
return true;
}
try {
execCommand(new String[] {
LN_COMMAND, "-s", linkName, link.getAbsolutePath()
});
} catch (Throwable th) {
SVNDebugLog.getDefaultLog().info(th);
}
return SVNFileType.getType(link) == SVNFileType.SYMLINK;
}
public static boolean detranslateSymlink(File src, File linkFile) throws SVNException {
if (isWindows || isOpenVMS) {
return false;
}
if (SVNFileType.getType(src) != SVNFileType.SYMLINK) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot detranslate symbolic link ''{0}''; file does not exist or not a symbolic link", src);
SVNErrorManager.error(err);
}
String linkPath = getSymlinkName(src);
OutputStream os = openFileForWriting(linkFile);
try {
os.write("link ".getBytes("UTF-8"));
os.write(linkPath.getBytes("UTF-8"));
} catch (IOException e) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e.getLocalizedMessage());
SVNErrorManager.error(err, e);
} finally {
SVNFileUtil.closeFile(os);
}
return true;
}
public static String getSymlinkName(File link) {
if (isWindows || isOpenVMS || link == null) {
return null;
}
String ls = null;
ls = SVNJNAUtil.getLinkTarget(link);
if (ls != null) {
return ls;
}
try {
ls = execCommand(new String[] {
LS_COMMAND, "-ld", link.getAbsolutePath()
});
} catch (Throwable th) {
SVNDebugLog.getDefaultLog().info(th);
}
if (ls == null || ls.lastIndexOf(" -> ") < 0) {
return null;
}
String[] attributes = ls.split("\\s+");
return attributes[attributes.length - 1];
}
public static String computeChecksum(String line) {
if (line == null) {
return null;
}
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
return null;
}
if (digest == null) {
return null;
}
digest.update(line.getBytes());
return toHexDigest(digest);
}
public static String computeChecksum(File file) throws SVNException {
if (file == null || file.isDirectory() || !file.exists()) {
return null;
}
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "MD5 implementation not found: {0}", e.getLocalizedMessage());
SVNErrorManager.error(err, e);
return null;
}
InputStream is = openFileForReading(file);
byte[] buffer = new byte[1024 * 16];
try {
while (true) {
int l = is.read(buffer);
if (l <= 0) {
break;
}
digest.update(buffer, 0, l);
}
} catch (IOException e) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e.getLocalizedMessage());
SVNErrorManager.error(err, e);
} finally {
closeFile(is);
}
return toHexDigest(digest);
}
public static boolean compareFiles(File f1, File f2, MessageDigest digest) throws SVNException {
if (f1 == null || f2 == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.INCORRECT_PARAMS, "NULL paths are supported in compareFiles method");
SVNErrorManager.error(err);
return false;
}
if (f1.equals(f2)) {
return true;
}
boolean equals = true;
if (f1.length() != f2.length()) {
if (digest == null) {
return false;
}
equals = false;
}
InputStream is1 = openFileForReading(f1);
InputStream is2 = openFileForReading(f2);
try {
while (true) {
int b1 = is1.read();
int b2 = is2.read();
if (b1 != b2) {
if (digest == null) {
return false;
}
equals = false;
}
if (b1 < 0) {
break;
}
if (digest != null) {
digest.update((byte) (b1 & 0xFF));
}
}
} catch (IOException e) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, e.getLocalizedMessage());
SVNErrorManager.error(err, e);
} finally {
closeFile(is1);
closeFile(is2);
}
return equals;
}
public static void setHidden(File file, boolean hidden) {
if (isWindows && SVNJNAUtil.setHidden(file)) {
return;
}
if (!isWindows || file == null || !file.exists() || file.isHidden()) {
return;
}
try {
Runtime.getRuntime().exec("attrib " + (hidden ? "+" : "-") + "H \"" + file.getAbsolutePath() + "\"");
} catch (Throwable th) {
SVNDebugLog.getDefaultLog().info(th);
}
}
public static void deleteAll(File dir, ISVNEventHandler cancelBaton) throws SVNException {
deleteAll(dir, true, cancelBaton);
}
public static void deleteAll(File dir, boolean deleteDirs) {
try {
deleteAll(dir, deleteDirs, null);
} catch (SVNException e) {
// should never happen as cancell handler is null.
}
}
public static void deleteAll(File dir, boolean deleteDirs, ISVNEventHandler cancelBaton) throws SVNException {
if (dir == null) {
return;
}
SVNFileType fileType = SVNFileType.getType(dir);
File[] children = fileType == SVNFileType.DIRECTORY ? SVNFileListUtil.listFiles(dir) : null;
if (children != null) {
if (cancelBaton != null) {
cancelBaton.checkCancelled();
}
for (int i = 0; i < children.length; i++) {
File child = children[i];
deleteAll(child, deleteDirs, cancelBaton);
}
if (cancelBaton != null) {
cancelBaton.checkCancelled();
}
}
if (fileType == SVNFileType.DIRECTORY && !deleteDirs) {
return;
}
deleteFile(dir);
}
public static boolean deleteFile(File file) throws SVNException {
if (file == null) {
return true;
}
if (!isWindows || file.isDirectory() || !file.exists()) {
return file.delete();
}
for (int i = 0; i < 10; i++) {
if (file.delete() && !file.exists()) {
return true;
}
if (!file.exists()) {
return true;
}
setReadonly(file, false);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
}
}
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot delete file ''{0}''", file);
SVNErrorManager.error(err);
return false;
}
private static String readSingleLine(File file) throws IOException {
if (!file.isFile() || !file.canRead()) {
throw new IOException("can't open file '" + file.getAbsolutePath() + "'");
}
BufferedReader reader = null;
String line = null;
InputStream is = null;
try {
is = createFileInputStream(file);
reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
line = reader.readLine();
} finally {
closeFile(is);
}
return line;
}
public static String toHexDigest(MessageDigest digest) {
if (digest == null) {
return null;
}
byte[] result = digest.digest();
String hexDigest = "";
for (int i = 0; i < result.length; i++) {
hexDigest += SVNFormatUtil.getHexNumberFromByte(result[i]);
}
return hexDigest;
}
public static String toHexDigest(byte[] digest) {
if (digest == null) {
return null;
}
String hexDigest = "";
for (int i = 0; i < digest.length; i++) {
hexDigest += SVNFormatUtil.getHexNumberFromByte(digest[i]);
}
return hexDigest;
}
public static byte[] fromHexDigest(String hexDigest) {
if (hexDigest == null || hexDigest.length() == 0) {
return null;
}
String hexMD5Digest = hexDigest.toLowerCase();
int digestLength = hexMD5Digest.length() / 2;
if (digestLength == 0 || 2 * digestLength != hexMD5Digest.length()) {
return null;
}
byte[] digest = new byte[digestLength];
for (int i = 0; i < hexMD5Digest.length() / 2; i++) {
if (!isHex(hexMD5Digest.charAt(2 * i)) || !isHex(hexMD5Digest.charAt(2 * i + 1))) {
return null;
}
int hi = Character.digit(hexMD5Digest.charAt(2 * i), 16) << 4;
int lo = Character.digit(hexMD5Digest.charAt(2 * i + 1), 16);
Integer ib = new Integer(hi | lo);
byte b = ib.byteValue();
digest[i] = b;
}
return digest;
}
private static boolean isHex(char ch) {
return Character.isDigit(ch) || (Character.toUpperCase(ch) >= 'A' && Character.toUpperCase(ch) <= 'F');
}
public static String getNativeEOLMarker(ISVNOptions options) {
if (nativeEOLMarker == null) {
nativeEOLMarker = new String(options.getNativeEOL());
}
return nativeEOLMarker;
}
public static long roundTimeStamp(long tstamp) {
return (tstamp / 1000) * 1000;
}
public static void sleepForTimestamp() {
if (!ourIsSleepForTimeStamp) {
return;
}
long time = System.currentTimeMillis();
time = 1100 - (time - (time / 1000) * 1000);
try {
Thread.sleep(time);
} catch (InterruptedException e) {
//
}
}
public static void setSleepForTimestamp(boolean sleep) {
ourIsSleepForTimeStamp = sleep;
}
public static String readLineFromStream(InputStream is, StringBuffer buffer, CharsetDecoder decoder) throws IOException {
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int r = -1;
while ((r = is.read()) != '\n') {
if (r == -1) {
String out = decode(decoder, byteBuffer.toByteArray());
buffer.append(out);
return null;
}
byteBuffer.write(r);
}
String out = decode(decoder, byteBuffer.toByteArray());
buffer.append(out);
return out;
}
private static String decode(CharsetDecoder decoder, byte[] in) {
ByteBuffer inBuf = ByteBuffer.wrap(in);
CharBuffer outBuf = CharBuffer.allocate(inBuf.capacity()*Math.round(decoder.maxCharsPerByte() + 0.5f));
decoder.decode(inBuf, outBuf, true);
decoder.flush(outBuf);
decoder.reset();
return outBuf.flip().toString();
}
public static String detectMimeType(InputStream is) throws IOException {
byte[] buffer = new byte[1024];
int read = 0;
read = is.read(buffer);
int binaryCount = 0;
for (int i = 0; i < read; i++) {
byte b = buffer[i];
if (b == 0) {
return BINARY_MIME_TYPE;
}
if (b < 0x07 || (b > 0x0d && b < 0x20) || b > 0x7F) {
binaryCount++;
}
}
if (read > 0 && binaryCount * 1000 / read > 850) {
return BINARY_MIME_TYPE;
}
return null;
}
public static String detectMimeType(File file) {
if (file == null || !file.exists()) {
return null;
}
InputStream is = null;
try {
is = openFileForReading(file);
return detectMimeType(is);
} catch (IOException e) {
return null;
} catch (SVNException e) {
return null;
} finally {
closeFile(is);
}
}
public static boolean isExecutable(File file) {
if (isWindows || isOpenVMS) {
return false;
}
Boolean executable = SVNJNAUtil.isExecutable(file);
if (executable != null) {
return executable.booleanValue();
}
String[] commandLine = new String[] {
LS_COMMAND, "-ln", file.getAbsolutePath()
};
String line = null;
try {
if (file.canRead()) {
line = execCommand(commandLine);
}
} catch (Throwable th) {
SVNDebugLog.getDefaultLog().info(th);
}
if (line == null || line.indexOf(' ') < 0) {
return false;
}
int index = 0;
String mod = null;
String fuid = null;
String fgid = null;
for (StringTokenizer tokens = new StringTokenizer(line, " \t"); tokens.hasMoreTokens();) {
String token = tokens.nextToken();
if (index == 0) {
mod = token;
} else if (index == 2) {
fuid = token;
} else if (index == 3) {
fgid = token;
} else if (index > 3) {
break;
}
index++;
}
if (mod == null) {
return false;
}
if (getCurrentUser().equals(fuid)) {
return mod.toLowerCase().indexOf('x') >= 0 && mod.toLowerCase().indexOf('x') < 4;
} else if (getCurrentGroup().equals(fgid)) {
return mod.toLowerCase().indexOf('x', 4) >= 4 && mod.toLowerCase().indexOf('x', 4) < 7;
} else {
return mod.toLowerCase().indexOf('x', 7) >= 7;
}
}
public static void copyDirectory(File srcDir, File dstDir, boolean copyAdminDir, ISVNEventHandler cancel) throws SVNException {
if (!dstDir.exists()) {
dstDir.mkdirs();
dstDir.setLastModified(srcDir.lastModified());
}
File[] files = SVNFileListUtil.listFiles(srcDir);
for (int i = 0; files != null && i < files.length; i++) {
File file = files[i];
if (file.getName().equals("..") || file.getName().equals(".") || file.equals(dstDir)) {
continue;
}
if (cancel != null) {
cancel.checkCancelled();
}
if (!copyAdminDir && file.getName().equals(getAdminDirectoryName())) {
continue;
}
SVNFileType fileType = SVNFileType.getType(file);
File dst = new File(dstDir, file.getName());
if (fileType == SVNFileType.FILE) {
boolean executable = isExecutable(file);
copyFile(file, dst, false);
if (executable) {
setExecutable(dst, executable);
}
} else if (fileType == SVNFileType.DIRECTORY) {
copyDirectory(file, dst, copyAdminDir, cancel);
if (file.isHidden() || getAdminDirectoryName().equals(file.getName())) {
setHidden(dst, true);
}
} else if (fileType == SVNFileType.SYMLINK) {
String name = getSymlinkName(file);
createSymlink(dst, name);
}
}
}
public static OutputStream openFileForWriting(File file) throws SVNException {
return openFileForWriting(file, false);
}
public static OutputStream openFileForWriting(File file, boolean append) throws SVNException {
if (file == null) {
return null;
}
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
if (file.isFile() && !file.canWrite()) {
// force writable.
if (append) {
setReadonly(file, false);
} else {
deleteFile(file);
}
}
try {
return new BufferedOutputStream(createFileOutputStream(file, append));
} catch (IOException e) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot write to ''{0}'': {1}", new Object[] {
file, e.getLocalizedMessage()
});
SVNErrorManager.error(err, e);
}
return null;
}
public static FileOutputStream createFileOutputStream(File file, boolean append) throws IOException {
int retryCount = SVNFileUtil.isWindows ? 11 : 1;
FileOutputStream os = null;
for (int i = 0; i < retryCount; i++) {
try {
os = new FileOutputStream(file, append);
break;
} catch (IOException e) {
if (i + 1 >= retryCount) {
throw e;
}
SVNFileUtil.closeFile(os);
if (file.exists() && file.isFile() && file.canWrite()) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
}
continue;
}
throw e;
}
}
return os;
}
public static RandomAccessFile openRAFileForWriting(File file, boolean append) throws SVNException {
if (file == null) {
return null;
}
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
RandomAccessFile raFile = null;
try {
raFile = new RandomAccessFile(file, "rw");
if (append) {
raFile.seek(raFile.length());
}
} catch (FileNotFoundException e) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Can not write to file ''{0}'': {1}", new Object[] {
file, e.getLocalizedMessage()
});
SVNErrorManager.error(err, e);
} catch (IOException ioe) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Can not set position pointer in file ''{0}'': {1}", new Object[] {
file, ioe.getLocalizedMessage()
});
SVNErrorManager.error(err, ioe);
}
return raFile;
}
public static InputStream openFileForReading(File file) throws SVNException {
if (file == null) {
return null;
}
if (!file.isFile() || !file.canRead()) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot read from ''{0}'': path refers to directory or read access is denied", file);
SVNErrorManager.error(err);
}
if (!file.exists()) {
return DUMMY_IN;
}
try {
return new BufferedInputStream(createFileInputStream(file));
} catch (IOException e) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot read from ''{0}'': {1}", new Object[] {
file, e.getLocalizedMessage()
});
SVNErrorManager.error(err, e);
}
return null;
}
public static FileInputStream createFileInputStream(File file) throws IOException {
int retryCount = SVNFileUtil.isWindows ? 11 : 1;
FileInputStream is = null;
for (int i = 0; i < retryCount; i++) {
try {
is = new FileInputStream(file);
break;
} catch (IOException e) {
if (i + 1 >= retryCount) {
throw e;
}
SVNFileUtil.closeFile(is);
if (file.exists() && file.isFile() && file.canRead()) {
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
}
continue;
}
throw e;
}
}
return is;
}
public static RandomAccessFile openRAFileForReading(File file) throws SVNException {
if (file == null) {
return null;
}
if (!file.isFile() || !file.canRead()) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot read from ''{0}'': path refers to a directory or read access is denied", file);
SVNErrorManager.error(err);
}
if (!file.exists()) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "File ''{0}'' does not exist", file);
SVNErrorManager.error(err);
}
try {
return new RandomAccessFile(file, "r");
} catch (FileNotFoundException e) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot read from ''{0}'': {1}", new Object[] {
file, e.getLocalizedMessage()
});
SVNErrorManager.error(err);
}
return null;
}
public static void closeFile(InputStream is) {
if (is == null) {
return;
}
try {
is.close();
} catch (IOException e) {
//
}
}
public static void closeFile(ISVNInputFile inFile) {
if (inFile == null) {
return;
}
try {
inFile.close();
} catch (IOException e) {
//
}
}
public static void closeFile(OutputStream os) {
if (os == null) {
return;
}
try {
os.close();
} catch (IOException e) {
//
}
}
public static void closeFile(RandomAccessFile raf) {
if (raf == null) {
return;
}
try {
raf.close();
} catch (IOException e) {
//
}
}
public static String execCommand(String[] commandLine) {
return execCommand(commandLine, false);
}
public static String execCommand(String[] commandLine, boolean waitAfterRead) {
return execCommand(commandLine, null, waitAfterRead);
}
public static String execCommand(String[] commandLine, String[] env, boolean waitAfterRead) {
InputStream is = null;
StringBuffer result = new StringBuffer();
try {
Process process = Runtime.getRuntime().exec(commandLine, env);
is = process.getInputStream();
if (!waitAfterRead) {
int rc = process.waitFor();
if (rc != 0) {
return null;
}
}
int r;
while ((r = is.read()) >= 0) {
result.append((char) (r & 0xFF));
}
if (waitAfterRead) {
int rc = process.waitFor();
if (rc != 0) {
return null;
}
}
return result.toString().trim();
} catch (IOException e) {
SVNDebugLog.getDefaultLog().info(e);
} catch (InterruptedException e) {
SVNDebugLog.getDefaultLog().info(e);
} finally {
closeFile(is);
}
return null;
}
private static String getCurrentUser() {
if (isWindows || isOpenVMS) {
return System.getProperty("user.name");
}
if (ourUserID == null) {
ourUserID = execCommand(new String[] {
ID_COMMAND, "-u"
});
if (ourUserID == null) {
ourUserID = "0";
}
}
return ourUserID;
}
private static String getCurrentGroup() {
if (isWindows || isOpenVMS) {
return System.getProperty("user.name");
}
if (ourGroupID == null) {
ourGroupID = execCommand(new String[] {
ID_COMMAND, "-g"
});
if (ourGroupID == null) {
ourGroupID = "0";
}
}
return ourGroupID;
}
public static void closeFile(Writer os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
//
}
}
}
public static void closeFile(Reader is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
//
}
}
}
public static String getAdminDirectoryName() {
if (ourAdminDirectoryName == null) {
String defaultAdminDir = ".svn";
if (getEnvironmentVariable("SVN_ASP_DOT_NET_HACK") != null) {
defaultAdminDir = "_svn";
}
ourAdminDirectoryName = System.getProperty("svnkit.admindir", System.getProperty("javasvn.admindir", defaultAdminDir));
if (ourAdminDirectoryName == null || "".equals(ourAdminDirectoryName.trim())) {
ourAdminDirectoryName = defaultAdminDir;
}
}
return ourAdminDirectoryName;
}
public static void setAdminDirectoryName(String name) {
ourAdminDirectoryName = name;
}
public static File getApplicationDataPath() {
if (ourAppDataPath != null) {
return ourAppDataPath;
}
String envAppData = getEnvironmentVariable("APPDATA");
if (envAppData == null) {
ourAppDataPath = new File(new File(System.getProperty("user.home")), "Application Data");
} else {
ourAppDataPath = new File(envAppData);
}
return ourAppDataPath;
}
public static File getSystemApplicationDataPath() {
if (ourSystemAppDataPath != null) {
return ourSystemAppDataPath;
}
String envAppData = getEnvironmentVariable("ALLUSERSPROFILE");
if (envAppData == null) {
ourSystemAppDataPath = new File(new File("C:/Documents and Settings/All Users"), "Application Data");
} else {
ourSystemAppDataPath = new File(envAppData, "Application Data");
}
return ourSystemAppDataPath;
}
public static String getEnvironmentVariable(String name) {
try {
// pre-Java 1.5 this throws an Error. On Java 1.5 it
// returns the environment variable
Method getenv = System.class.getMethod("getenv", new Class[] {String.class});
if (getenv != null) {
Object value = getenv.invoke(null, new Object[] {name});
if (value instanceof String) {
return (String) value;
}
}
} catch (Throwable e) {
try {
// This means we are on 1.4. Get all variables into
// a Properties object and get the variable from that
return getEnvironment().getProperty(name);
} catch (Throwable e1) {
SVNDebugLog.getDefaultLog().info(e);
SVNDebugLog.getDefaultLog().info(e1);
return null;
}
}
return null;
}
private static String ourTestEditor = null;
private static String ourTestMergeTool = null;
private static String ourTestFunction = null;
public static void setTestEnvironment(String editor, String mergeTool, String function) {
ourTestEditor = editor;
ourTestMergeTool = mergeTool;
ourTestFunction = function;
}
public static String[] getTestEnvironment() {
return new String[] {ourTestEditor, ourTestMergeTool, ourTestFunction};
}
private static Properties getEnvironment() throws Throwable {
Process p = null;
Properties envVars = new Properties();
Runtime r = Runtime.getRuntime();
if (isWindows) {
if (System.getProperty("os.name").toLowerCase().indexOf("windows 9") >= 0) {
p = r.exec("command.com /c set");
} else {
p = r.exec("cmd.exe /c set");
}
} else {
p = r.exec(ENV_COMMAND); // if OpenVMS ENV_COMMAND could be "mcr
// gnu:[bin]env"
}
if (p != null) {
BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
int idx = line.indexOf('=');
if (idx >= 0) {
String key = line.substring(0, idx);
String value = line.substring(idx + 1);
envVars.setProperty(key, value);
}
}
}
return envVars;
}
public static File createTempDirectory(String name) throws SVNException {
File tmpFile = null;
try {
tmpFile = File.createTempFile("svnkit" + name, ".tmp");
} catch (IOException e) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot create temporary directory: {0}", e.getLocalizedMessage());
SVNErrorManager.error(err, e);
}
if (tmpFile.exists()) {
tmpFile.delete();
}
tmpFile.mkdirs();
return tmpFile;
}
public static File createTempFile(String prefix, String suffix) throws SVNException {
File tmpFile = null;
try {
if (prefix.length() < 3) {
prefix = "svn" + prefix;
}
tmpFile = File.createTempFile(prefix, suffix);
} catch (IOException e) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot create temporary file: {0}", e.getLocalizedMessage());
SVNErrorManager.error(err, e);
}
return tmpFile;
}
public static File getSystemConfigurationDirectory() {
if (isWindows) {
return new File(getSystemApplicationDataPath(), "Subversion");
} else if (isOpenVMS) {
return new File("/sys$config", "subversion").getAbsoluteFile();
}
return new File("/etc/subversion");
}
}
| true | true | public static void copyFile(File src, File dst, boolean safe) throws SVNException {
if (src == null || dst == null) {
return;
}
if (src.equals(dst)) {
return;
}
if (!src.exists()) {
dst.delete();
return;
}
File tmpDst = dst;
if (SVNFileType.getType(dst) != SVNFileType.NONE) {
if (safe) {
tmpDst = createUniqueFile(dst.getParentFile(), ".copy", ".tmp");
} else {
dst.delete();
}
}
boolean executable = isExecutable(src);
dst.getParentFile().mkdirs();
FileChannel srcChannel = null;
FileChannel dstChannel = null;
FileInputStream is = null;
FileOutputStream os = null;
SVNErrorMessage error = null;
try {
is = createFileInputStream(src);
srcChannel = is.getChannel();
os = createFileOutputStream(dst, false);
dstChannel = os.getChannel();
long totalSize = srcChannel.size();
long toCopy = totalSize;
while (toCopy > 0) {
toCopy -= dstChannel.transferFrom(srcChannel, totalSize - toCopy, toCopy);
}
} catch (IOException e) {
error = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot copy file ''{0}'' to ''{1}'': {2}", new Object[] {
src, dst, e.getLocalizedMessage()
});
} finally {
if (srcChannel != null) {
try {
srcChannel.close();
} catch (IOException e) {
//
}
}
if (dstChannel != null) {
try {
dstChannel.close();
} catch (IOException e) {
//
}
}
SVNFileUtil.closeFile(is);
SVNFileUtil.closeFile(os);
}
if (error != null) {
error = null;
InputStream sis = null;
OutputStream dos = null;
try {
sis = SVNFileUtil.openFileForReading(src);
dos = SVNFileUtil.openFileForWriting(dst);
SVNTranslator.copy(sis, dos);
} catch (IOException e) {
error = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot copy file ''{0}'' to ''{1}'': {2}", new Object[] {
src, dst, e.getLocalizedMessage()
});
} finally {
SVNFileUtil.closeFile(dos);
SVNFileUtil.closeFile(sis);
}
}
if (error != null) {
SVNErrorManager.error(error);
}
if (safe && tmpDst != dst) {
rename(tmpDst, dst);
}
if (executable) {
setExecutable(dst, true);
}
dst.setLastModified(src.lastModified());
}
| public static void copyFile(File src, File dst, boolean safe) throws SVNException {
if (src == null || dst == null) {
return;
}
if (src.equals(dst)) {
return;
}
if (!src.exists()) {
dst.delete();
return;
}
File tmpDst = dst;
if (SVNFileType.getType(dst) != SVNFileType.NONE) {
if (safe) {
tmpDst = createUniqueFile(dst.getParentFile(), ".copy", ".tmp");
} else {
dst.delete();
}
}
boolean executable = isExecutable(src);
dst.getParentFile().mkdirs();
FileChannel srcChannel = null;
FileChannel dstChannel = null;
FileInputStream is = null;
FileOutputStream os = null;
SVNErrorMessage error = null;
try {
is = createFileInputStream(src);
srcChannel = is.getChannel();
os = createFileOutputStream(tmpDst, false);
dstChannel = os.getChannel();
long totalSize = srcChannel.size();
long toCopy = totalSize;
while (toCopy > 0) {
toCopy -= dstChannel.transferFrom(srcChannel, totalSize - toCopy, toCopy);
}
} catch (IOException e) {
error = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot copy file ''{0}'' to ''{1}'': {2}", new Object[] {
src, dst, e.getLocalizedMessage()
});
} finally {
if (srcChannel != null) {
try {
srcChannel.close();
} catch (IOException e) {
//
}
}
if (dstChannel != null) {
try {
dstChannel.close();
} catch (IOException e) {
//
}
}
SVNFileUtil.closeFile(is);
SVNFileUtil.closeFile(os);
}
if (error != null) {
error = null;
InputStream sis = null;
OutputStream dos = null;
try {
sis = SVNFileUtil.openFileForReading(src);
dos = SVNFileUtil.openFileForWriting(dst);
SVNTranslator.copy(sis, dos);
} catch (IOException e) {
error = SVNErrorMessage.create(SVNErrorCode.IO_ERROR, "Cannot copy file ''{0}'' to ''{1}'': {2}", new Object[] {
src, dst, e.getLocalizedMessage()
});
} finally {
SVNFileUtil.closeFile(dos);
SVNFileUtil.closeFile(sis);
}
}
if (error != null) {
SVNErrorManager.error(error);
}
if (safe && tmpDst != dst) {
rename(tmpDst, dst);
}
if (executable) {
setExecutable(dst, true);
}
dst.setLastModified(src.lastModified());
}
|
diff --git a/com.mountainminds.eclemma.core/src/com/mountainminds/eclemma/internal/core/instr/InstrMarker.java b/com.mountainminds.eclemma.core/src/com/mountainminds/eclemma/internal/core/instr/InstrMarker.java
index c2cfff6..dca6aad 100644
--- a/com.mountainminds.eclemma.core/src/com/mountainminds/eclemma/internal/core/instr/InstrMarker.java
+++ b/com.mountainminds.eclemma.core/src/com/mountainminds/eclemma/internal/core/instr/InstrMarker.java
@@ -1,74 +1,76 @@
/*******************************************************************************
* Copyright (c) 2006 Mountainminds GmbH & Co. KG
* This software is provided under the terms of the Eclipse Public License v1.0
* See http://www.eclipse.org/legal/epl-v10.html.
*
* $Id: $
******************************************************************************/
package com.mountainminds.eclemma.internal.core.instr;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.Date;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
/**
* Static utilities to mark instrumented output folders. The mark created as a
* special file in the output directory, which will be deleted during a clean
* build.
*
* @author Marc R. Hoffmann
* @version $Revision: $
*/
public class InstrMarker {
private static final String MARKERFILE = ".emma_instrumented"; //$NON-NLS-1$
/**
* Sets a mark on the given output folder.
*
* @param path
* workspace relative path of the output folder
* @throws CoreException
* Thrown when creating the marker file fails
*/
public static void mark(IPath path) throws CoreException {
IFolder folder = getFolder(path);
if (folder != null) {
IFile marker = folder.getFile(MARKERFILE);
- marker.create(getMarkerContent(), true, null);
- marker.setDerived(true);
+ if (!marker.exists()) {
+ marker.create(getMarkerContent(), true, null);
+ marker.setDerived(true);
+ }
}
}
/**
* Checks whether the given output folder has an instrumentation mark.
*
* @param path
* workspace relative path of the output folder
* @return <code>true</true> if the mark exists
*/
public static boolean isMarked(IPath path) {
IFolder folder = getFolder(path);
return folder == null ? false : folder.getFile(MARKERFILE).exists();
}
private static IFolder getFolder(IPath path) {
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IResource res = root.findMember(path);
return res instanceof IFolder ? (IFolder) res : null;
}
private static InputStream getMarkerContent() {
String text = "Class files instrumented at " + new Date(); //$NON-NLS-1$
return new ByteArrayInputStream(text.getBytes());
}
}
| true | true | public static void mark(IPath path) throws CoreException {
IFolder folder = getFolder(path);
if (folder != null) {
IFile marker = folder.getFile(MARKERFILE);
marker.create(getMarkerContent(), true, null);
marker.setDerived(true);
}
}
| public static void mark(IPath path) throws CoreException {
IFolder folder = getFolder(path);
if (folder != null) {
IFile marker = folder.getFile(MARKERFILE);
if (!marker.exists()) {
marker.create(getMarkerContent(), true, null);
marker.setDerived(true);
}
}
}
|
diff --git a/src/org/eclipse/jface/viewers/WrappedViewerLabelProvider.java b/src/org/eclipse/jface/viewers/WrappedViewerLabelProvider.java
index 46faa884..bc00609b 100644
--- a/src/org/eclipse/jface/viewers/WrappedViewerLabelProvider.java
+++ b/src/org/eclipse/jface/viewers/WrappedViewerLabelProvider.java
@@ -1,205 +1,205 @@
/*******************************************************************************
* Copyright (c) 2006, 2007 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
*******************************************************************************/
package org.eclipse.jface.viewers;
import org.eclipse.core.runtime.Assert;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
/**
* The WrappedViewerLabelProvider is a label provider that allows
* {@link ILabelProvider}, {@link IColorProvider} and {@link IFontProvider} to
* be mapped to a ColumnLabelProvider.
*
* @since 3.3
*
*/
class WrappedViewerLabelProvider extends ColumnLabelProvider {
private static ILabelProvider defaultLabelProvider = new LabelProvider();
private ILabelProvider labelProvider = defaultLabelProvider;
private IColorProvider colorProvider;
private IFontProvider fontProvider;
private IViewerLabelProvider viewerLabelProvider;
private ITreePathLabelProvider treePathLabelProvider;
/**
* Create a new instance of the receiver based on labelProvider.
*
* @param labelProvider
*/
public WrappedViewerLabelProvider(IBaseLabelProvider labelProvider) {
super();
setProviders(labelProvider);
}
/**
* Set the any providers for the receiver that can be adapted from provider.
*
* @param provider
* {@link Object}
*/
public void setProviders(Object provider) {
if (provider instanceof ITreePathLabelProvider)
treePathLabelProvider = ((ITreePathLabelProvider) provider);
if (provider instanceof IViewerLabelProvider)
viewerLabelProvider = ((IViewerLabelProvider) provider);
if (provider instanceof ILabelProvider)
labelProvider = ((ILabelProvider) provider);
if (provider instanceof IColorProvider)
colorProvider = (IColorProvider) provider;
if (provider instanceof IFontProvider)
fontProvider = (IFontProvider) provider;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.IFontProvider#getFont(java.lang.Object)
*/
public Font getFont(Object element) {
if (fontProvider == null) {
return null;
}
return fontProvider.getFont(element);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.IColorProvider#getBackground(java.lang.Object)
*/
public Color getBackground(Object element) {
if (colorProvider == null) {
return null;
}
return colorProvider.getBackground(element);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object)
*/
public String getText(Object element) {
return getLabelProvider().getText(element);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object)
*/
public Image getImage(Object element) {
return getLabelProvider().getImage(element);
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.viewers.IColorProvider#getForeground(java.lang.Object)
*/
public Color getForeground(Object element) {
if (colorProvider == null) {
return null;
}
return colorProvider.getForeground(element);
}
/**
* Get the label provider
*
* @return {@link ILabelProvider}
*/
ILabelProvider getLabelProvider() {
return labelProvider;
}
/**
* Get the color provider
*
* @return {@link IColorProvider}
*/
IColorProvider getColorProvider() {
return colorProvider;
}
/**
* Get the font provider
*
* @return {@link IFontProvider}.
*/
IFontProvider getFontProvider() {
return fontProvider;
}
public void update(ViewerCell cell) {
if(viewerLabelProvider == null && treePathLabelProvider == null){
super.update(cell);
return;
}
ViewerLabel label = new ViewerLabel(cell.getText(), cell.getImage());
- if (viewerLabelProvider != null) {
- viewerLabelProvider.updateLabel(label, cell.getElement());
- } else if (treePathLabelProvider != null) {
+ if (treePathLabelProvider != null) {
TreePath treePath = cell.getViewerRow().getTreePath();
Assert.isNotNull(treePath);
treePathLabelProvider.updateLabel(label, treePath);
- }
+ } else if (viewerLabelProvider != null) {
+ viewerLabelProvider.updateLabel(label, cell.getElement());
+ }
if (!label.hasNewForeground() && colorProvider != null)
label.setForeground(getForeground(cell.getElement()));
if (!label.hasNewBackground() && colorProvider != null)
label.setBackground(getBackground(cell.getElement()));
if (!label.hasNewFont() && fontProvider != null)
label.setFont(getFont(cell.getElement()));
applyViewerLabel(cell, label);
}
private void applyViewerLabel(ViewerCell cell, ViewerLabel label) {
if (label.hasNewText()) {
cell.setText(label.getText());
}
if (label.hasNewImage()) {
cell.setImage(label.getImage());
}
if (colorProvider!= null || label.hasNewBackground()) {
cell.setBackground(label.getBackground());
}
if (colorProvider!= null || label.hasNewForeground()) {
cell.setForeground(label.getForeground());
}
if (fontProvider!= null || label.hasNewFont()) {
cell.setFont(label.getFont());
}
}
}
| false | true | public void update(ViewerCell cell) {
if(viewerLabelProvider == null && treePathLabelProvider == null){
super.update(cell);
return;
}
ViewerLabel label = new ViewerLabel(cell.getText(), cell.getImage());
if (viewerLabelProvider != null) {
viewerLabelProvider.updateLabel(label, cell.getElement());
} else if (treePathLabelProvider != null) {
TreePath treePath = cell.getViewerRow().getTreePath();
Assert.isNotNull(treePath);
treePathLabelProvider.updateLabel(label, treePath);
}
if (!label.hasNewForeground() && colorProvider != null)
label.setForeground(getForeground(cell.getElement()));
if (!label.hasNewBackground() && colorProvider != null)
label.setBackground(getBackground(cell.getElement()));
if (!label.hasNewFont() && fontProvider != null)
label.setFont(getFont(cell.getElement()));
applyViewerLabel(cell, label);
}
| public void update(ViewerCell cell) {
if(viewerLabelProvider == null && treePathLabelProvider == null){
super.update(cell);
return;
}
ViewerLabel label = new ViewerLabel(cell.getText(), cell.getImage());
if (treePathLabelProvider != null) {
TreePath treePath = cell.getViewerRow().getTreePath();
Assert.isNotNull(treePath);
treePathLabelProvider.updateLabel(label, treePath);
} else if (viewerLabelProvider != null) {
viewerLabelProvider.updateLabel(label, cell.getElement());
}
if (!label.hasNewForeground() && colorProvider != null)
label.setForeground(getForeground(cell.getElement()));
if (!label.hasNewBackground() && colorProvider != null)
label.setBackground(getBackground(cell.getElement()));
if (!label.hasNewFont() && fontProvider != null)
label.setFont(getFont(cell.getElement()));
applyViewerLabel(cell, label);
}
|
diff --git a/AdvancedMap3D/src/main/java/com/nutiteq/utils/WkbRead.java b/AdvancedMap3D/src/main/java/com/nutiteq/utils/WkbRead.java
index b2f3dd7..afee077 100644
--- a/AdvancedMap3D/src/main/java/com/nutiteq/utils/WkbRead.java
+++ b/AdvancedMap3D/src/main/java/com/nutiteq/utils/WkbRead.java
@@ -1,224 +1,224 @@
package com.nutiteq.utils;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import com.nutiteq.components.MapPos;
import com.nutiteq.geometry.Geometry;
import com.nutiteq.geometry.Line;
import com.nutiteq.geometry.Point;
import com.nutiteq.geometry.Polygon;
import com.nutiteq.log.Log;
import com.nutiteq.style.LineStyle;
import com.nutiteq.style.PointStyle;
import com.nutiteq.style.PolygonStyle;
public class WkbRead {
/// Big Endian
private static int wkbXDR = 0;
/// Little Endian
private static int wkbNDR = 1;
// geometry types
private static final int wkbPoint = 1;
private static final int wkbLineString = 2;
private static final int wkbPolygon = 3;
private static final int wkbMultiPoint = 4;
private static final int wkbMultiLineString = 5;
private static final int wkbMultiPolygon = 6;
private static final int wkbGeometryCollection = 7;
public static Geometry[] readWkb(ByteArrayInputStream is, Object userData){
int endinanByte = is.read();
ByteOrder endian;
if(endinanByte == 0){
endian = java.nio.ByteOrder.BIG_ENDIAN;
}else{
endian = java.nio.ByteOrder.LITTLE_ENDIAN;
}
int type = readInt(is,endian);
int geometryType = type & 0xff;
boolean hasZ = ((type & 0x80000000) != 0);
int dimensions = 2;
if (hasZ){
dimensions = 3;
}
boolean hasSRID = ((type & 0x20000000) != 0);
int srid = 0;
if (hasSRID){
- srid = is.read(); // read SRID
+ srid = readInt(is,endian); // read SRID
Log.debug("SRID ignored in WKB: "+srid);
}
Geometry[] result = null;
switch (geometryType) {
case wkbPoint :
result = readPoint(is,dimensions,endian,userData);
break;
case wkbLineString :
result = readLineString(is, dimensions, endian, userData);
break;
case wkbPolygon :
result = readPolygon(is, dimensions, endian, userData);
break;
case wkbMultiPoint :
result = readMultiPoint(is, dimensions, endian, userData);
break;
case wkbMultiLineString :
result = readMultiLineString(is, dimensions, endian, userData);
break;
case wkbMultiPolygon :
result = readMultiPolygon(is, dimensions, endian, userData);
break;
case wkbGeometryCollection :
result = readGeometryCollection(is, dimensions, endian, userData);
break;
default:
Log.error("Unknown geometryType "+geometryType);
}
return result;
}
private static int readInt(ByteArrayInputStream is, ByteOrder byteOrder) {
byte buffer[] = new byte[4];
try {
is.read(buffer);
} catch (IOException e) {
e.printStackTrace();
}
return ByteBuffer.wrap(buffer).order(byteOrder).getInt();
}
private static Geometry[] readGeometryCollection(ByteArrayInputStream is, int dimensions, ByteOrder endian, Object userData) {
int numGeoms = readInt(is, endian);
List<Geometry> geomList = new ArrayList<Geometry>();
for(int i = 0; i<numGeoms;i++){
Geometry[] geometry = readWkb(is, userData);
for(int j = 0; j<geometry.length; j++) {
geomList.add(geometry[j]);
}
}
Geometry[] geoms = new Geometry[geomList.size()];
geomList.toArray(geoms);
return geoms;
}
private static Geometry[] readMultiPolygon(ByteArrayInputStream is, int dimensions, ByteOrder endian, Object userData) {
int numPolygons = readInt(is, endian);
List<Geometry> polyList = new ArrayList<Geometry>();
for(int i = 0; i<numPolygons;i++){
Geometry[] geometry = readWkb(is, userData);
if (geometry == null)
continue;
for(int j = 0; j < geometry.length; j++) {
if(!(geometry[j] instanceof Polygon)){
Log.error("MultiPolygon must have only Polygon elements");
} else {
polyList.add(geometry[j]);
}
}
}
Geometry[] polygons = new Geometry[polyList.size()];
polyList.toArray(polygons);
return polygons;
}
private static Geometry[] readMultiLineString(ByteArrayInputStream is, int dimensions, ByteOrder endian, Object userData) {
int numLines = readInt(is, endian);
List<Geometry> lineList = new ArrayList<Geometry>();
for(int i = 0; i<numLines;i++){
Geometry[] geometry = readWkb(is, userData);
if (geometry == null)
continue;
for(int j = 0; j < geometry.length; j++) {
if(!(geometry[j] instanceof Line)){
Log.error("MultiLineString must have only Line elements");
} else {
lineList.add(geometry[j]);
}
}
}
Geometry[] lines = new Geometry[lineList.size()];
lineList.toArray(lines);
return lines;
}
private static Geometry[] readMultiPoint(ByteArrayInputStream is, int dimensions, ByteOrder endian, Object userData) {
Log.error("Not implemented readMultiPoint WKB reader");
return null;
}
private static Geometry[] readPolygon(ByteArrayInputStream is, int dimensions, ByteOrder endian, Object userData) {
int numRings = readInt(is, endian);
if(numRings < 1)
return new Geometry[0];
int size = readInt(is, endian);
List<MapPos> outerRing = readCoordinateList(is, dimensions, size, endian);
List<List<MapPos>> innerRings = null;
if(numRings > 1){
innerRings = new LinkedList<List<MapPos>>();
for (int i = 1; i < numRings; i++){
int innerSize = is.read();
List<MapPos> innerRing = readCoordinateList(is, dimensions, innerSize, endian);
innerRings.add(innerRing);
}
}
return new Geometry[]{new Polygon(outerRing, innerRings, null, (PolygonStyle) null, userData)};
}
private static Geometry[] readLineString(ByteArrayInputStream is, int dimensions, ByteOrder endian, Object userData) {
int size = readInt(is,endian);
return new Geometry[]{new Line(readCoordinateList(is, dimensions, size, endian), null, (LineStyle) null, userData)};
}
private static Geometry[] readPoint(ByteArrayInputStream is, int dimensions, ByteOrder endian, Object userData) {
return new Geometry[]{new Point(readCoordinate(is,dimensions,endian), null, (PointStyle) null, userData)};
}
private static List<MapPos> readCoordinateList(ByteArrayInputStream is, int dimensions, int size, ByteOrder endian) {
if(size == 0)
return null;
List<MapPos> mapPoses = new ArrayList<MapPos>();
for (int i = 0; i < size; i++) {
mapPoses.add(readCoordinate(is,dimensions,endian));
}
return mapPoses;
}
private static MapPos readCoordinate(ByteArrayInputStream is, int dimensions, ByteOrder endian) {
double x = 0;
double y = 0;
double z = 0;
byte buffer[] = new byte[8];
try {
is.read(buffer);
x = ByteBuffer.wrap(buffer).order(endian).getDouble();
is.read(buffer);
y = ByteBuffer.wrap(buffer).order(endian).getDouble();
if (dimensions == 3) {
is.read(buffer);
z = ByteBuffer.wrap(buffer).order(endian).getDouble();
}
} catch (IOException e) {
Log.error("read coordinate error "+e.getMessage());
}
return new MapPos(x,y,z);
}
}
| true | true | public static Geometry[] readWkb(ByteArrayInputStream is, Object userData){
int endinanByte = is.read();
ByteOrder endian;
if(endinanByte == 0){
endian = java.nio.ByteOrder.BIG_ENDIAN;
}else{
endian = java.nio.ByteOrder.LITTLE_ENDIAN;
}
int type = readInt(is,endian);
int geometryType = type & 0xff;
boolean hasZ = ((type & 0x80000000) != 0);
int dimensions = 2;
if (hasZ){
dimensions = 3;
}
boolean hasSRID = ((type & 0x20000000) != 0);
int srid = 0;
if (hasSRID){
srid = is.read(); // read SRID
Log.debug("SRID ignored in WKB: "+srid);
}
Geometry[] result = null;
switch (geometryType) {
case wkbPoint :
result = readPoint(is,dimensions,endian,userData);
break;
case wkbLineString :
result = readLineString(is, dimensions, endian, userData);
break;
case wkbPolygon :
result = readPolygon(is, dimensions, endian, userData);
break;
case wkbMultiPoint :
result = readMultiPoint(is, dimensions, endian, userData);
break;
case wkbMultiLineString :
result = readMultiLineString(is, dimensions, endian, userData);
break;
case wkbMultiPolygon :
result = readMultiPolygon(is, dimensions, endian, userData);
break;
case wkbGeometryCollection :
result = readGeometryCollection(is, dimensions, endian, userData);
break;
default:
Log.error("Unknown geometryType "+geometryType);
}
return result;
}
| public static Geometry[] readWkb(ByteArrayInputStream is, Object userData){
int endinanByte = is.read();
ByteOrder endian;
if(endinanByte == 0){
endian = java.nio.ByteOrder.BIG_ENDIAN;
}else{
endian = java.nio.ByteOrder.LITTLE_ENDIAN;
}
int type = readInt(is,endian);
int geometryType = type & 0xff;
boolean hasZ = ((type & 0x80000000) != 0);
int dimensions = 2;
if (hasZ){
dimensions = 3;
}
boolean hasSRID = ((type & 0x20000000) != 0);
int srid = 0;
if (hasSRID){
srid = readInt(is,endian); // read SRID
Log.debug("SRID ignored in WKB: "+srid);
}
Geometry[] result = null;
switch (geometryType) {
case wkbPoint :
result = readPoint(is,dimensions,endian,userData);
break;
case wkbLineString :
result = readLineString(is, dimensions, endian, userData);
break;
case wkbPolygon :
result = readPolygon(is, dimensions, endian, userData);
break;
case wkbMultiPoint :
result = readMultiPoint(is, dimensions, endian, userData);
break;
case wkbMultiLineString :
result = readMultiLineString(is, dimensions, endian, userData);
break;
case wkbMultiPolygon :
result = readMultiPolygon(is, dimensions, endian, userData);
break;
case wkbGeometryCollection :
result = readGeometryCollection(is, dimensions, endian, userData);
break;
default:
Log.error("Unknown geometryType "+geometryType);
}
return result;
}
|
diff --git a/ModeratorGui/src/me/heldplayer/ModeratorGui/ReviewCommand.java b/ModeratorGui/src/me/heldplayer/ModeratorGui/ReviewCommand.java
index b0ab3ef..257f2e6 100644
--- a/ModeratorGui/src/me/heldplayer/ModeratorGui/ReviewCommand.java
+++ b/ModeratorGui/src/me/heldplayer/ModeratorGui/ReviewCommand.java
@@ -1,213 +1,213 @@
package me.heldplayer.ModeratorGui;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import me.heldplayer.ModeratorGui.tables.*;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
public class ReviewCommand implements CommandExecutor {
private final ModeratorGui main;
private final SimpleDateFormat dateFormat;
public ReviewCommand(ModeratorGui plugin) {
main = plugin;
dateFormat = new SimpleDateFormat("MM-dd-yyyy");
}
@Override
public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) {
if (args.length <= 0) {
int rowCount = main.getDatabase().find(Lists.class).findRowCount();
String[] results = new String[13];
results[0] = ChatColor.GRAY + "Types: " + ChatColor.YELLOW + "Issue " + ChatColor.DARK_RED + "Ban " + ChatColor.DARK_GREEN + "Unban " + ChatColor.GREEN + "Promote " + ChatColor.RED + "Demote";
results[1] = ChatColor.GRAY + "Current date: " + dateFormat.format(Long.valueOf(System.currentTimeMillis()));
results[2] = ChatColor.GRAY + "" + ChatColor.ITALIC + "All dates are MM-dd-yyyy";
int sideI = 3;
for (int i = rowCount; i > (rowCount <= 10 ? 0 : rowCount - 10); i--) {
Lists list = main.getDatabase().find(Lists.class).where().eq("id", i).findUnique();
if (list == null) {
continue;
}
int id = list.getReportId();
ReportType type = ReportType.getType(list.getType());
switch (type) {
case ISSUE:
Issues issue = main.getDatabase().find(Issues.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.YELLOW + "[X] " + ChatColor.AQUA + issue.getReported() + ChatColor.YELLOW + ", by " + ChatColor.AQUA + issue.getReporter() + ChatColor.YELLOW + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(issue.getTimestamp())) + ChatColor.YELLOW + ": " + issue.getIssue();
break;
case BAN:
Bans ban = main.getDatabase().find(Bans.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.DARK_RED + "[X] " + ChatColor.AQUA + ban.getBanned() + ChatColor.DARK_RED + ", by " + ChatColor.AQUA + ban.getBanner() + ChatColor.DARK_RED + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(ban.getTimestamp())) + ChatColor.DARK_RED + ": " + ban.getReason();
break;
case UNBAN:
Unbans unban = main.getDatabase().find(Unbans.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.DARK_GREEN + "[X] " + ChatColor.AQUA + unban.getUnbanned() + ChatColor.DARK_GREEN + ", by " + ChatColor.AQUA + unban.getUnbanner() + ChatColor.DARK_GREEN + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(unban.getTimestamp())) + ChatColor.DARK_GREEN + ": " + unban.getReason();
break;
case PROMOTE:
Promotions promote = main.getDatabase().find(Promotions.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.GREEN + "[X] " + ChatColor.AQUA + promote.getPromoted() + ChatColor.GREEN + ", by " + ChatColor.AQUA + promote.getPromoter() + ChatColor.GREEN + ", " + ChatColor.AQUA + promote.getPrevRank() + ChatColor.GREEN + " => " + ChatColor.AQUA + promote.getNewRank() + ChatColor.GREEN + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(promote.getTimestamp())) + ChatColor.GREEN + ": " + promote.getReason();
break;
case DEMOTE:
Demotions demote = main.getDatabase().find(Demotions.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.RED + "[X] " + ChatColor.AQUA + demote.getDemoted() + ChatColor.RED + ", by " + ChatColor.AQUA + demote.getDemoter() + ChatColor.RED + ", " + ChatColor.AQUA + demote.getPrevRank() + ChatColor.RED + " => " + ChatColor.AQUA + demote.getNewRank() + ChatColor.RED + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(demote.getTimestamp())) + ChatColor.RED + ": " + demote.getReason();
break;
default:
results[sideI] = ChatColor.DARK_GRAY + "Unspecified action happened";
break;
}
sideI++;
}
for (String result : results) {
if (result != null)
sender.sendMessage(result);
}
return true;
}
pagination: {
if(args.length == 1){
int page = 0;
try {
- page = Integer.parseInt(args[0]);
+ page = Integer.parseInt(args[0]) - 1;
} catch(NumberFormatException ex){
break pagination;
}
int rowCount = main.getDatabase().find(Lists.class).findRowCount();
String[] results = new String[13];
results[0] = ChatColor.GRAY + "Types: " + ChatColor.YELLOW + "Issue " + ChatColor.DARK_RED + "Ban " + ChatColor.DARK_GREEN + "Unban " + ChatColor.GREEN + "Promote " + ChatColor.RED + "Demote";
results[1] = ChatColor.GRAY + "Current date: " + dateFormat.format(Long.valueOf(System.currentTimeMillis()));
results[2] = ChatColor.GRAY + "" + ChatColor.ITALIC + "All dates are MM-dd-yyyy";
int sideI = 3;
- for (int i = rowCount - page * 10; i > (rowCount <= 10 ? 0 : rowCount - 10); i--) {
+ for (int i = rowCount - page * 10; i > (rowCount - page * 10 <= 10 ? 0 : rowCount - page * 10 - 10); i--) {
Lists list = main.getDatabase().find(Lists.class).where().eq("id", i).findUnique();
if (list == null) {
continue;
}
int id = list.getReportId();
ReportType type = ReportType.getType(list.getType());
switch (type) {
case ISSUE:
Issues issue = main.getDatabase().find(Issues.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.YELLOW + "[X] " + ChatColor.AQUA + issue.getReported() + ChatColor.YELLOW + ", by " + ChatColor.AQUA + issue.getReporter() + ChatColor.YELLOW + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(issue.getTimestamp())) + ChatColor.YELLOW + ": " + issue.getIssue();
break;
case BAN:
Bans ban = main.getDatabase().find(Bans.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.DARK_RED + "[X] " + ChatColor.AQUA + ban.getBanned() + ChatColor.DARK_RED + ", by " + ChatColor.AQUA + ban.getBanner() + ChatColor.DARK_RED + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(ban.getTimestamp())) + ChatColor.DARK_RED + ": " + ban.getReason();
break;
case UNBAN:
Unbans unban = main.getDatabase().find(Unbans.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.DARK_GREEN + "[X] " + ChatColor.AQUA + unban.getUnbanned() + ChatColor.DARK_GREEN + ", by " + ChatColor.AQUA + unban.getUnbanner() + ChatColor.DARK_GREEN + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(unban.getTimestamp())) + ChatColor.DARK_GREEN + ": " + unban.getReason();
break;
case PROMOTE:
Promotions promote = main.getDatabase().find(Promotions.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.GREEN + "[X] " + ChatColor.AQUA + promote.getPromoted() + ChatColor.GREEN + ", by " + ChatColor.AQUA + promote.getPromoter() + ChatColor.GREEN + ", " + ChatColor.AQUA + promote.getPrevRank() + ChatColor.GREEN + " => " + ChatColor.AQUA + promote.getNewRank() + ChatColor.GREEN + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(promote.getTimestamp())) + ChatColor.GREEN + ": " + promote.getReason();
break;
case DEMOTE:
Demotions demote = main.getDatabase().find(Demotions.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.RED + "[X] " + ChatColor.AQUA + demote.getDemoted() + ChatColor.RED + ", by " + ChatColor.AQUA + demote.getDemoter() + ChatColor.RED + ", " + ChatColor.AQUA + demote.getPrevRank() + ChatColor.RED + " => " + ChatColor.AQUA + demote.getNewRank() + ChatColor.RED + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(demote.getTimestamp())) + ChatColor.RED + ": " + demote.getReason();
break;
default:
results[sideI] = ChatColor.DARK_GRAY + "Unspecified action happened";
break;
}
sideI++;
}
for (String result : results) {
if (result != null)
sender.sendMessage(result);
}
return true;
}
}
if(args[1].equalsIgnoreCase("") && args.length > 1){
}
return false;
}
private List<String> getPlayerMatches(String name) {
OfflinePlayer[] players = main.getServer().getOfflinePlayers();
List<String> matched = new ArrayList<String>();
for (OfflinePlayer player : players) {
if (player.getName().equalsIgnoreCase(name)) {
matched.clear();
matched.add(player.getName());
return matched;
}
if (player.getName().length() < name.length()) {
continue;
}
if (player.getName().substring(0, name.length()).equalsIgnoreCase(name)) {
matched.add(player.getName());
}
}
return matched;
}
private List<String> getRankMatches(String rank) {
List<String> ranks = main.ranks;
List<String> matched = new ArrayList<String>();
for (String matchedRank : ranks) {
if (matchedRank.equalsIgnoreCase(rank)) {
matched.clear();
matched.add(matchedRank);
return matched;
}
if (matchedRank.length() < rank.length()) {
continue;
}
if (matchedRank.substring(0, rank.length()).equalsIgnoreCase(rank)) {
matched.add(matchedRank);
}
}
return matched;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) {
if (args.length <= 0) {
int rowCount = main.getDatabase().find(Lists.class).findRowCount();
String[] results = new String[13];
results[0] = ChatColor.GRAY + "Types: " + ChatColor.YELLOW + "Issue " + ChatColor.DARK_RED + "Ban " + ChatColor.DARK_GREEN + "Unban " + ChatColor.GREEN + "Promote " + ChatColor.RED + "Demote";
results[1] = ChatColor.GRAY + "Current date: " + dateFormat.format(Long.valueOf(System.currentTimeMillis()));
results[2] = ChatColor.GRAY + "" + ChatColor.ITALIC + "All dates are MM-dd-yyyy";
int sideI = 3;
for (int i = rowCount; i > (rowCount <= 10 ? 0 : rowCount - 10); i--) {
Lists list = main.getDatabase().find(Lists.class).where().eq("id", i).findUnique();
if (list == null) {
continue;
}
int id = list.getReportId();
ReportType type = ReportType.getType(list.getType());
switch (type) {
case ISSUE:
Issues issue = main.getDatabase().find(Issues.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.YELLOW + "[X] " + ChatColor.AQUA + issue.getReported() + ChatColor.YELLOW + ", by " + ChatColor.AQUA + issue.getReporter() + ChatColor.YELLOW + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(issue.getTimestamp())) + ChatColor.YELLOW + ": " + issue.getIssue();
break;
case BAN:
Bans ban = main.getDatabase().find(Bans.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.DARK_RED + "[X] " + ChatColor.AQUA + ban.getBanned() + ChatColor.DARK_RED + ", by " + ChatColor.AQUA + ban.getBanner() + ChatColor.DARK_RED + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(ban.getTimestamp())) + ChatColor.DARK_RED + ": " + ban.getReason();
break;
case UNBAN:
Unbans unban = main.getDatabase().find(Unbans.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.DARK_GREEN + "[X] " + ChatColor.AQUA + unban.getUnbanned() + ChatColor.DARK_GREEN + ", by " + ChatColor.AQUA + unban.getUnbanner() + ChatColor.DARK_GREEN + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(unban.getTimestamp())) + ChatColor.DARK_GREEN + ": " + unban.getReason();
break;
case PROMOTE:
Promotions promote = main.getDatabase().find(Promotions.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.GREEN + "[X] " + ChatColor.AQUA + promote.getPromoted() + ChatColor.GREEN + ", by " + ChatColor.AQUA + promote.getPromoter() + ChatColor.GREEN + ", " + ChatColor.AQUA + promote.getPrevRank() + ChatColor.GREEN + " => " + ChatColor.AQUA + promote.getNewRank() + ChatColor.GREEN + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(promote.getTimestamp())) + ChatColor.GREEN + ": " + promote.getReason();
break;
case DEMOTE:
Demotions demote = main.getDatabase().find(Demotions.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.RED + "[X] " + ChatColor.AQUA + demote.getDemoted() + ChatColor.RED + ", by " + ChatColor.AQUA + demote.getDemoter() + ChatColor.RED + ", " + ChatColor.AQUA + demote.getPrevRank() + ChatColor.RED + " => " + ChatColor.AQUA + demote.getNewRank() + ChatColor.RED + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(demote.getTimestamp())) + ChatColor.RED + ": " + demote.getReason();
break;
default:
results[sideI] = ChatColor.DARK_GRAY + "Unspecified action happened";
break;
}
sideI++;
}
for (String result : results) {
if (result != null)
sender.sendMessage(result);
}
return true;
}
pagination: {
if(args.length == 1){
int page = 0;
try {
page = Integer.parseInt(args[0]);
} catch(NumberFormatException ex){
break pagination;
}
int rowCount = main.getDatabase().find(Lists.class).findRowCount();
String[] results = new String[13];
results[0] = ChatColor.GRAY + "Types: " + ChatColor.YELLOW + "Issue " + ChatColor.DARK_RED + "Ban " + ChatColor.DARK_GREEN + "Unban " + ChatColor.GREEN + "Promote " + ChatColor.RED + "Demote";
results[1] = ChatColor.GRAY + "Current date: " + dateFormat.format(Long.valueOf(System.currentTimeMillis()));
results[2] = ChatColor.GRAY + "" + ChatColor.ITALIC + "All dates are MM-dd-yyyy";
int sideI = 3;
for (int i = rowCount - page * 10; i > (rowCount <= 10 ? 0 : rowCount - 10); i--) {
Lists list = main.getDatabase().find(Lists.class).where().eq("id", i).findUnique();
if (list == null) {
continue;
}
int id = list.getReportId();
ReportType type = ReportType.getType(list.getType());
switch (type) {
case ISSUE:
Issues issue = main.getDatabase().find(Issues.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.YELLOW + "[X] " + ChatColor.AQUA + issue.getReported() + ChatColor.YELLOW + ", by " + ChatColor.AQUA + issue.getReporter() + ChatColor.YELLOW + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(issue.getTimestamp())) + ChatColor.YELLOW + ": " + issue.getIssue();
break;
case BAN:
Bans ban = main.getDatabase().find(Bans.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.DARK_RED + "[X] " + ChatColor.AQUA + ban.getBanned() + ChatColor.DARK_RED + ", by " + ChatColor.AQUA + ban.getBanner() + ChatColor.DARK_RED + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(ban.getTimestamp())) + ChatColor.DARK_RED + ": " + ban.getReason();
break;
case UNBAN:
Unbans unban = main.getDatabase().find(Unbans.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.DARK_GREEN + "[X] " + ChatColor.AQUA + unban.getUnbanned() + ChatColor.DARK_GREEN + ", by " + ChatColor.AQUA + unban.getUnbanner() + ChatColor.DARK_GREEN + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(unban.getTimestamp())) + ChatColor.DARK_GREEN + ": " + unban.getReason();
break;
case PROMOTE:
Promotions promote = main.getDatabase().find(Promotions.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.GREEN + "[X] " + ChatColor.AQUA + promote.getPromoted() + ChatColor.GREEN + ", by " + ChatColor.AQUA + promote.getPromoter() + ChatColor.GREEN + ", " + ChatColor.AQUA + promote.getPrevRank() + ChatColor.GREEN + " => " + ChatColor.AQUA + promote.getNewRank() + ChatColor.GREEN + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(promote.getTimestamp())) + ChatColor.GREEN + ": " + promote.getReason();
break;
case DEMOTE:
Demotions demote = main.getDatabase().find(Demotions.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.RED + "[X] " + ChatColor.AQUA + demote.getDemoted() + ChatColor.RED + ", by " + ChatColor.AQUA + demote.getDemoter() + ChatColor.RED + ", " + ChatColor.AQUA + demote.getPrevRank() + ChatColor.RED + " => " + ChatColor.AQUA + demote.getNewRank() + ChatColor.RED + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(demote.getTimestamp())) + ChatColor.RED + ": " + demote.getReason();
break;
default:
results[sideI] = ChatColor.DARK_GRAY + "Unspecified action happened";
break;
}
sideI++;
}
for (String result : results) {
if (result != null)
sender.sendMessage(result);
}
return true;
}
}
if(args[1].equalsIgnoreCase("") && args.length > 1){
}
return false;
}
| public boolean onCommand(CommandSender sender, Command command, String alias, String[] args) {
if (args.length <= 0) {
int rowCount = main.getDatabase().find(Lists.class).findRowCount();
String[] results = new String[13];
results[0] = ChatColor.GRAY + "Types: " + ChatColor.YELLOW + "Issue " + ChatColor.DARK_RED + "Ban " + ChatColor.DARK_GREEN + "Unban " + ChatColor.GREEN + "Promote " + ChatColor.RED + "Demote";
results[1] = ChatColor.GRAY + "Current date: " + dateFormat.format(Long.valueOf(System.currentTimeMillis()));
results[2] = ChatColor.GRAY + "" + ChatColor.ITALIC + "All dates are MM-dd-yyyy";
int sideI = 3;
for (int i = rowCount; i > (rowCount <= 10 ? 0 : rowCount - 10); i--) {
Lists list = main.getDatabase().find(Lists.class).where().eq("id", i).findUnique();
if (list == null) {
continue;
}
int id = list.getReportId();
ReportType type = ReportType.getType(list.getType());
switch (type) {
case ISSUE:
Issues issue = main.getDatabase().find(Issues.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.YELLOW + "[X] " + ChatColor.AQUA + issue.getReported() + ChatColor.YELLOW + ", by " + ChatColor.AQUA + issue.getReporter() + ChatColor.YELLOW + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(issue.getTimestamp())) + ChatColor.YELLOW + ": " + issue.getIssue();
break;
case BAN:
Bans ban = main.getDatabase().find(Bans.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.DARK_RED + "[X] " + ChatColor.AQUA + ban.getBanned() + ChatColor.DARK_RED + ", by " + ChatColor.AQUA + ban.getBanner() + ChatColor.DARK_RED + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(ban.getTimestamp())) + ChatColor.DARK_RED + ": " + ban.getReason();
break;
case UNBAN:
Unbans unban = main.getDatabase().find(Unbans.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.DARK_GREEN + "[X] " + ChatColor.AQUA + unban.getUnbanned() + ChatColor.DARK_GREEN + ", by " + ChatColor.AQUA + unban.getUnbanner() + ChatColor.DARK_GREEN + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(unban.getTimestamp())) + ChatColor.DARK_GREEN + ": " + unban.getReason();
break;
case PROMOTE:
Promotions promote = main.getDatabase().find(Promotions.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.GREEN + "[X] " + ChatColor.AQUA + promote.getPromoted() + ChatColor.GREEN + ", by " + ChatColor.AQUA + promote.getPromoter() + ChatColor.GREEN + ", " + ChatColor.AQUA + promote.getPrevRank() + ChatColor.GREEN + " => " + ChatColor.AQUA + promote.getNewRank() + ChatColor.GREEN + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(promote.getTimestamp())) + ChatColor.GREEN + ": " + promote.getReason();
break;
case DEMOTE:
Demotions demote = main.getDatabase().find(Demotions.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.RED + "[X] " + ChatColor.AQUA + demote.getDemoted() + ChatColor.RED + ", by " + ChatColor.AQUA + demote.getDemoter() + ChatColor.RED + ", " + ChatColor.AQUA + demote.getPrevRank() + ChatColor.RED + " => " + ChatColor.AQUA + demote.getNewRank() + ChatColor.RED + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(demote.getTimestamp())) + ChatColor.RED + ": " + demote.getReason();
break;
default:
results[sideI] = ChatColor.DARK_GRAY + "Unspecified action happened";
break;
}
sideI++;
}
for (String result : results) {
if (result != null)
sender.sendMessage(result);
}
return true;
}
pagination: {
if(args.length == 1){
int page = 0;
try {
page = Integer.parseInt(args[0]) - 1;
} catch(NumberFormatException ex){
break pagination;
}
int rowCount = main.getDatabase().find(Lists.class).findRowCount();
String[] results = new String[13];
results[0] = ChatColor.GRAY + "Types: " + ChatColor.YELLOW + "Issue " + ChatColor.DARK_RED + "Ban " + ChatColor.DARK_GREEN + "Unban " + ChatColor.GREEN + "Promote " + ChatColor.RED + "Demote";
results[1] = ChatColor.GRAY + "Current date: " + dateFormat.format(Long.valueOf(System.currentTimeMillis()));
results[2] = ChatColor.GRAY + "" + ChatColor.ITALIC + "All dates are MM-dd-yyyy";
int sideI = 3;
for (int i = rowCount - page * 10; i > (rowCount - page * 10 <= 10 ? 0 : rowCount - page * 10 - 10); i--) {
Lists list = main.getDatabase().find(Lists.class).where().eq("id", i).findUnique();
if (list == null) {
continue;
}
int id = list.getReportId();
ReportType type = ReportType.getType(list.getType());
switch (type) {
case ISSUE:
Issues issue = main.getDatabase().find(Issues.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.YELLOW + "[X] " + ChatColor.AQUA + issue.getReported() + ChatColor.YELLOW + ", by " + ChatColor.AQUA + issue.getReporter() + ChatColor.YELLOW + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(issue.getTimestamp())) + ChatColor.YELLOW + ": " + issue.getIssue();
break;
case BAN:
Bans ban = main.getDatabase().find(Bans.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.DARK_RED + "[X] " + ChatColor.AQUA + ban.getBanned() + ChatColor.DARK_RED + ", by " + ChatColor.AQUA + ban.getBanner() + ChatColor.DARK_RED + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(ban.getTimestamp())) + ChatColor.DARK_RED + ": " + ban.getReason();
break;
case UNBAN:
Unbans unban = main.getDatabase().find(Unbans.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.DARK_GREEN + "[X] " + ChatColor.AQUA + unban.getUnbanned() + ChatColor.DARK_GREEN + ", by " + ChatColor.AQUA + unban.getUnbanner() + ChatColor.DARK_GREEN + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(unban.getTimestamp())) + ChatColor.DARK_GREEN + ": " + unban.getReason();
break;
case PROMOTE:
Promotions promote = main.getDatabase().find(Promotions.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.GREEN + "[X] " + ChatColor.AQUA + promote.getPromoted() + ChatColor.GREEN + ", by " + ChatColor.AQUA + promote.getPromoter() + ChatColor.GREEN + ", " + ChatColor.AQUA + promote.getPrevRank() + ChatColor.GREEN + " => " + ChatColor.AQUA + promote.getNewRank() + ChatColor.GREEN + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(promote.getTimestamp())) + ChatColor.GREEN + ": " + promote.getReason();
break;
case DEMOTE:
Demotions demote = main.getDatabase().find(Demotions.class).where().eq("id", id).findUnique();
results[sideI] = ChatColor.RED + "[X] " + ChatColor.AQUA + demote.getDemoted() + ChatColor.RED + ", by " + ChatColor.AQUA + demote.getDemoter() + ChatColor.RED + ", " + ChatColor.AQUA + demote.getPrevRank() + ChatColor.RED + " => " + ChatColor.AQUA + demote.getNewRank() + ChatColor.RED + " on " + ChatColor.AQUA + dateFormat.format(Long.valueOf(demote.getTimestamp())) + ChatColor.RED + ": " + demote.getReason();
break;
default:
results[sideI] = ChatColor.DARK_GRAY + "Unspecified action happened";
break;
}
sideI++;
}
for (String result : results) {
if (result != null)
sender.sendMessage(result);
}
return true;
}
}
if(args[1].equalsIgnoreCase("") && args.length > 1){
}
return false;
}
|
diff --git a/src/main/java/net/catharos/lib/mysql/QueryBuilder.java b/src/main/java/net/catharos/lib/mysql/QueryBuilder.java
index 1847b2d..b618194 100644
--- a/src/main/java/net/catharos/lib/mysql/QueryBuilder.java
+++ b/src/main/java/net/catharos/lib/mysql/QueryBuilder.java
@@ -1,113 +1,113 @@
package net.catharos.lib.mysql;
import net.catharos.lib.util.ArrayUtil;
import net.catharos.lib.util.StringUtil;
import org.apache.commons.lang.Validate;
public class QueryBuilder {
/** The table prefix used in queries */
private String prefix;
public QueryBuilder() {
this("");
}
public QueryBuilder( String prefix ) {
setPrefix(prefix);
}
public String selectAll(String table) {
StringBuilder str = new StringBuilder("SELECT ");
str.append(" * FROM ").append(getTableName(table));
return str.toString();
}
public String selectAllWhere(String table, String where) {
return this.selectWhere(table, "*", where);
}
public String selectWhere(String table, String what, String where) {
StringBuilder str = new StringBuilder("SELECT ");
str.append(what).append(" FROM ").append(getTableName(table));
str.append(" WHERE ").append(where);
return str.toString();
}
/** Generates a SQL update string */
- public String update(String table, Object[] keys, Object[] values) {
+ public String update(String table, String[] keys, Object[] values) {
Validate.notEmpty(keys);
Validate.notEmpty(values);
- Validate.isTrue(keys.length > values.length);
+ Validate.isTrue(keys.length >= values.length);
StringBuilder str = new StringBuilder("UPDATE ");
str.append(getTableName(table)).append(" SET ");
if(values.length == 1) {
str.append(StringUtil.getMySQLString(values[0]));
} else {
for(int i = 0; i < keys.length; i++) {
- Object key = keys[i];
+ String key = keys[i];
Object val = values.length < i ? values[i] : null;
str.append(key).append("=").append(StringUtil.getMySQLString(val));
}
}
return str.toString();
}
/** Generates a SQL insert string */
public String insert(String table, Object... values) {
Validate.notEmpty(values);
StringBuilder str = new StringBuilder("INSERT INTO ");
str.append(getTableName(table)).append(" VALUES(");
String[] val = new String[values.length];
for(int i = 0; i < val.length; i++) {
val[i] = StringUtil.getMySQLString(values[i]);
}
return str.append(ArrayUtil.implode(val, ", ")).append(")").toString();
}
public String createIfNotExists(String table, String[] lines, String suffix) {
return createIfNotExists(table, lines, suffix, true);
}
public String createIfNotExists(String table, String[] lines, String suffix, boolean primary) {
StringBuilder str = new StringBuilder("CREATE TABLE IF NOT EXISTS ");
str.append(getTableName(table)).append(" (");
for(int s = 0; s < lines.length; s++) {
String[] split = lines[s].split(" ", 2);
split[0] = replaceMagic(StringUtil.getMySQLString(split[0]));
str.append(ArrayUtil.implode(split));
if(s == 0 && primary) str.append(" NOT NULL PRIMARY KEY");
str.append(", ");
}
return str.append(replaceMagic(suffix)).append(")").toString();
}
/** Returns the table name including the set prefix */
public final String getTableName( String table ) {
return prefix + table;
}
/** Sets the table prefix used in queries */
protected final void setPrefix( String prefix ) {
this.prefix = prefix;
}
protected final String replaceMagic( String msg ) {
return msg.replace("'", "`");
}
}
| false | true | public String update(String table, Object[] keys, Object[] values) {
Validate.notEmpty(keys);
Validate.notEmpty(values);
Validate.isTrue(keys.length > values.length);
StringBuilder str = new StringBuilder("UPDATE ");
str.append(getTableName(table)).append(" SET ");
if(values.length == 1) {
str.append(StringUtil.getMySQLString(values[0]));
} else {
for(int i = 0; i < keys.length; i++) {
Object key = keys[i];
Object val = values.length < i ? values[i] : null;
str.append(key).append("=").append(StringUtil.getMySQLString(val));
}
}
return str.toString();
}
| public String update(String table, String[] keys, Object[] values) {
Validate.notEmpty(keys);
Validate.notEmpty(values);
Validate.isTrue(keys.length >= values.length);
StringBuilder str = new StringBuilder("UPDATE ");
str.append(getTableName(table)).append(" SET ");
if(values.length == 1) {
str.append(StringUtil.getMySQLString(values[0]));
} else {
for(int i = 0; i < keys.length; i++) {
String key = keys[i];
Object val = values.length < i ? values[i] : null;
str.append(key).append("=").append(StringUtil.getMySQLString(val));
}
}
return str.toString();
}
|
diff --git a/TestScript.java b/TestScript.java
index 726439d..e91bd91 100644
--- a/TestScript.java
+++ b/TestScript.java
@@ -1,90 +1,91 @@
package com.redhat.qe.auto.testng;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
import com.redhat.qe.tools.compare.CollectionSorter;
public abstract class TestScript {
protected static boolean initialized = false;
protected static Logger log = Logger.getLogger(TestScript.class.getName());
protected static final String defaultAutomationPropertiesFile=System.getenv("HOME")+"/automation.properties";
protected static final String defaultLogPropertiesFile=System.getProperty("user.home")+ "/log.properties";
public TestScript() {
if (initialized) return; //only need to run this stuff once per jvm
String propFile ="";
//load log properties
try{
Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());
propFile = System.getProperty("log.propertiesfile", defaultLogPropertiesFile);
if (! new File(propFile).exists()) {
log.fine("No log.propertiesfile specified, nor found in HOME dir, trying to use default in project.");
propFile = "log.properties";
}
else{
log.info("Found log properties file: "+propFile);
}
LogManager.getLogManager().readConfiguration(new FileInputStream(propFile));
log.fine("Loaded logger configuration from log.propertiesfile: "+propFile);
} catch(Exception e){
e.printStackTrace();
log.log(Level.SEVERE, "Could not load log properties from "+propFile, e);
}
//load automation properties
try{
propFile = (System.getProperty("automation.propertiesfile"));
if(propFile == null || propFile.length() == 0){
log.info("System property automation.propertiesfile is not set. Defaulting to "+ defaultAutomationPropertiesFile);
propFile = defaultAutomationPropertiesFile;
}
Properties p = new Properties();
p.load(new FileInputStream(propFile));
for (Object key: p.keySet()){
System.setProperty((String)key, p.getProperty((String)(key)));
}
log.fine("Loaded automation properties from automation.propertiesfile: "+propFile);
// default automation.dir to user.dir
if(System.getProperty("automation.dir") == null){
System.setProperty("automation.dir", System.getProperty("user.dir"));
}
} catch(Exception e){
e.printStackTrace();
log.log(Level.SEVERE, "Could not load automation properties from "+propFile, e);
}
// echo all the system properties
Set<String> keySet = System.getProperties().stringPropertyNames();
List<String> keyList = CollectionSorter.asSortedList(keySet);
for (Object key: keyList){
String value = System.getProperty((String) key);
- if (key.toString().toLowerCase().contains("password"))
+ if (key.toString().toLowerCase().contains("password") ||
+ key.toString().toLowerCase().contains("passphrase"))
value = "********";
log.finer("Property("+key+")= "+ value);
}
initialized = true;
}
}
| true | true | public TestScript() {
if (initialized) return; //only need to run this stuff once per jvm
String propFile ="";
//load log properties
try{
Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());
propFile = System.getProperty("log.propertiesfile", defaultLogPropertiesFile);
if (! new File(propFile).exists()) {
log.fine("No log.propertiesfile specified, nor found in HOME dir, trying to use default in project.");
propFile = "log.properties";
}
else{
log.info("Found log properties file: "+propFile);
}
LogManager.getLogManager().readConfiguration(new FileInputStream(propFile));
log.fine("Loaded logger configuration from log.propertiesfile: "+propFile);
} catch(Exception e){
e.printStackTrace();
log.log(Level.SEVERE, "Could not load log properties from "+propFile, e);
}
//load automation properties
try{
propFile = (System.getProperty("automation.propertiesfile"));
if(propFile == null || propFile.length() == 0){
log.info("System property automation.propertiesfile is not set. Defaulting to "+ defaultAutomationPropertiesFile);
propFile = defaultAutomationPropertiesFile;
}
Properties p = new Properties();
p.load(new FileInputStream(propFile));
for (Object key: p.keySet()){
System.setProperty((String)key, p.getProperty((String)(key)));
}
log.fine("Loaded automation properties from automation.propertiesfile: "+propFile);
// default automation.dir to user.dir
if(System.getProperty("automation.dir") == null){
System.setProperty("automation.dir", System.getProperty("user.dir"));
}
} catch(Exception e){
e.printStackTrace();
log.log(Level.SEVERE, "Could not load automation properties from "+propFile, e);
}
// echo all the system properties
Set<String> keySet = System.getProperties().stringPropertyNames();
List<String> keyList = CollectionSorter.asSortedList(keySet);
for (Object key: keyList){
String value = System.getProperty((String) key);
if (key.toString().toLowerCase().contains("password"))
value = "********";
log.finer("Property("+key+")= "+ value);
}
initialized = true;
}
| public TestScript() {
if (initialized) return; //only need to run this stuff once per jvm
String propFile ="";
//load log properties
try{
Thread.currentThread().setContextClassLoader(ClassLoader.getSystemClassLoader());
propFile = System.getProperty("log.propertiesfile", defaultLogPropertiesFile);
if (! new File(propFile).exists()) {
log.fine("No log.propertiesfile specified, nor found in HOME dir, trying to use default in project.");
propFile = "log.properties";
}
else{
log.info("Found log properties file: "+propFile);
}
LogManager.getLogManager().readConfiguration(new FileInputStream(propFile));
log.fine("Loaded logger configuration from log.propertiesfile: "+propFile);
} catch(Exception e){
e.printStackTrace();
log.log(Level.SEVERE, "Could not load log properties from "+propFile, e);
}
//load automation properties
try{
propFile = (System.getProperty("automation.propertiesfile"));
if(propFile == null || propFile.length() == 0){
log.info("System property automation.propertiesfile is not set. Defaulting to "+ defaultAutomationPropertiesFile);
propFile = defaultAutomationPropertiesFile;
}
Properties p = new Properties();
p.load(new FileInputStream(propFile));
for (Object key: p.keySet()){
System.setProperty((String)key, p.getProperty((String)(key)));
}
log.fine("Loaded automation properties from automation.propertiesfile: "+propFile);
// default automation.dir to user.dir
if(System.getProperty("automation.dir") == null){
System.setProperty("automation.dir", System.getProperty("user.dir"));
}
} catch(Exception e){
e.printStackTrace();
log.log(Level.SEVERE, "Could not load automation properties from "+propFile, e);
}
// echo all the system properties
Set<String> keySet = System.getProperties().stringPropertyNames();
List<String> keyList = CollectionSorter.asSortedList(keySet);
for (Object key: keyList){
String value = System.getProperty((String) key);
if (key.toString().toLowerCase().contains("password") ||
key.toString().toLowerCase().contains("passphrase"))
value = "********";
log.finer("Property("+key+")= "+ value);
}
initialized = true;
}
|
diff --git a/srcj/com/sun/electric/tool/io/input/LTSpiceOut.java b/srcj/com/sun/electric/tool/io/input/LTSpiceOut.java
index 7cbb52b6a..6676812c0 100644
--- a/srcj/com/sun/electric/tool/io/input/LTSpiceOut.java
+++ b/srcj/com/sun/electric/tool/io/input/LTSpiceOut.java
@@ -1,319 +1,319 @@
/* -*- tab-width: 4 -*-
*
* Electric(tm) VLSI Design System
*
* File: LTSpiceOut.java
* Input/output tool: reader for LTSpice output (.raw)
* Written by Steven M. Rubin, Sun Microsystems.
*
* Copyright (c) 2009 Sun Microsystems and Static Free Software
*
* Electric(tm) 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.
*
* Electric(tm) 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 Electric(tm); see the file COPYING. If not, write to
* the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
* Boston, Mass 02111-1307, USA.
*/
package com.sun.electric.tool.io.input;
import com.sun.electric.database.hierarchy.Cell;
import com.sun.electric.database.text.TextUtils;
import com.sun.electric.tool.simulation.AnalogAnalysis;
import com.sun.electric.tool.simulation.AnalogSignal;
import com.sun.electric.tool.simulation.Stimuli;
import com.sun.electric.tool.simulation.Waveform;
import com.sun.electric.tool.simulation.WaveformImpl;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
/**
* Class for reading and displaying waveforms from LTSpice Raw output.
* These are contained in .raw files.
*/
public class LTSpiceOut extends Simulate
{
private static final boolean DEBUG = false;
private boolean complexValues;
/**
* Class for handling swept signals.
*/
private static class SweepAnalysisLT extends AnalogAnalysis
{
double [][] commonTime; // sweep, signal
List<List<double[]>> theSweeps = new ArrayList<List<double[]>>(); // sweep, event, signal
private SweepAnalysisLT(Stimuli sd, AnalogAnalysis.AnalysisType type)
{
super(sd, type, false);
}
protected Waveform[] loadWaveforms(AnalogSignal signal)
{
int sigIndex = signal.getIndexInAnalysis();
Waveform[] waveforms = new Waveform[commonTime.length];
for (int sweep = 0; sweep < waveforms.length; sweep++)
{
double[] times = commonTime[sweep];
List<double[]> theSweep = theSweeps.get(sweep);
Waveform waveform = new WaveformImpl(times, theSweep.get(sigIndex));
waveforms[sweep] = waveform;
}
return waveforms;
}
}
LTSpiceOut() {}
/**
* Method to read an LTSpice output file.
*/
protected Stimuli readSimulationOutput(URL fileURL, Cell cell)
throws IOException
{
// open the file
if (openBinaryInput(fileURL)) return null;
// show progress reading .raw file
startProgressDialog("LTSpice output", fileURL.getFile());
// read the actual signal data from the .raw file
Stimuli sd = readRawLTSpiceFile(cell);
// stop progress dialog, close the file
stopProgressDialog();
closeInput();
// return the simulation data
return sd;
}
private Stimuli readRawLTSpiceFile(Cell cell)
throws IOException
{
complexValues = false;
boolean realValues = false;
int signalCount = -1;
String[] signalNames = null;
int rowCount = -1;
AnalogAnalysis.AnalysisType aType = AnalogAnalysis.ANALYSIS_TRANS;
for(;;)
{
String line = getLineFromBinary();
if (line == null) break;
updateProgressDialog(line.length());
// find the ":" separator
int colonPos = line.indexOf(':');
if (colonPos < 0) continue;
String keyWord = line.substring(0, colonPos);
String restOfLine = line.substring(colonPos+1).trim();
if (keyWord.equals("Plotname"))
{
// see if known analysis is specified
if (restOfLine.equals("AC Analysis")) aType = AnalogAnalysis.ANALYSIS_AC;
continue;
}
if (keyWord.equals("Flags"))
{
// the first signal is Time
int complex = restOfLine.indexOf("complex");
if (complex >= 0) complexValues = true;
int r = restOfLine.indexOf("real");
if (r >= 0) realValues = true;
continue;
}
if (keyWord.equals("No. Variables"))
{
// the first signal is Time
signalCount = TextUtils.atoi(restOfLine) - 1;
continue;
}
if (keyWord.equals("No. Points"))
{
rowCount = TextUtils.atoi(restOfLine);
continue;
}
if (keyWord.equals("Variables"))
{
if (signalCount < 0)
{
System.out.println("Missing variable count in file");
return null;
}
signalNames = new String[signalCount];
for(int i=0; i<=signalCount; i++)
{
restOfLine = getLineFromBinary();
if (restOfLine == null) break;
updateProgressDialog(restOfLine.length());
restOfLine = restOfLine.trim();
int indexOnLine = TextUtils.atoi(restOfLine);
if (indexOnLine != i)
System.out.println("Warning: Variable " + i + " has number " + indexOnLine);
int nameStart = 0;
while (nameStart < restOfLine.length() && !Character.isWhitespace(restOfLine.charAt(nameStart))) nameStart++;
while (nameStart < restOfLine.length() && Character.isWhitespace(restOfLine.charAt(nameStart))) nameStart++;
int nameEnd = nameStart;
while (nameEnd < restOfLine.length() && !Character.isWhitespace(restOfLine.charAt(nameEnd))) nameEnd++;
String name = restOfLine.substring(nameStart, nameEnd);
- if (name.startsWith("v(") && name.endsWith(")"))
+ if (name.startsWith("V(") && name.endsWith(")"))
{
name = name.substring(2, name.length()-1);
}
if (i > 0) signalNames[i-1] = name;
}
continue;
}
if (keyWord.equals("Binary"))
{
if (signalCount < 0)
{
System.out.println("Missing variable count in file");
return null;
}
if (rowCount < 0)
{
System.out.println("Missing point count in file");
return null;
}
// initialize the stimuli object
Stimuli sd = new Stimuli();
SweepAnalysisLT an = new SweepAnalysisLT(sd, aType);
sd.setCell(cell);
if (DEBUG)
{
System.out.println(signalCount+" VARIABLES, "+rowCount+" SAMPLES");
for(int i=0; i<signalCount; i++)
System.out.println("VARIABLE "+i+" IS "+signalNames[i]);
}
// read all of the data in the RAW file
double[][] values = new double[signalCount][rowCount];
double [] timeValues = new double[rowCount];
for(int j=0; j<rowCount; j++)
{
double time = getNextDouble();
if (DEBUG) System.out.println("TIME AT "+j+" IS "+time);
timeValues[j] = Math.abs(time);
for(int i=0; i<signalCount; i++)
{
double value = 0;
if (realValues) value = getNextFloat(); else
value = getNextDouble();
if (DEBUG) System.out.println(" DATA POINT "+i+" ("+signalNames[i]+") IS "+value);
values[i][j] = value;
}
}
// figure out where the sweep breaks occur
int sweepLength = -1;
int sweepStart = 0;
int sweepCount = 0;
for(int j=1; j<=rowCount; j++)
{
if (j == rowCount || timeValues[j] < timeValues[j-1])
{
int sl = j - sweepStart;
if (sweepLength >= 0 && sweepLength != sl)
System.out.println("ERROR! Sweeps have different length (" + sweepLength + " and " + sl + ")");
sweepLength = sl;
sweepStart = j;
sweepCount++;
an.addSweep(Integer.toString(sweepCount));
}
}
if (DEBUG) System.out.println("FOUND " + sweepCount + " SWEEPS OF LENGTH " + sweepLength);
// place data into the Analysis object
an.commonTime = new double[sweepCount][];
for(int s=0; s<sweepCount; s++)
{
int offset = s * sweepLength;
an.commonTime[s] = new double[sweepLength];
for (int j = 0; j < sweepLength; j++)
an.commonTime[s][j] = timeValues[j + offset];
List<double[]> allTheData = new ArrayList<double[]>();
for(int i=0; i<signalCount; i++)
{
double[] oneSetOfData = new double[sweepLength];
for(int j=0; j<sweepLength; j++)
oneSetOfData[j] = values[i][j+offset];
allTheData.add(oneSetOfData);
}
an.theSweeps.add(allTheData);
}
// add signal names to the analysis
for (int i = 0; i < signalCount; i++)
{
String name = signalNames[i];
int lastDotPos = name.lastIndexOf('.');
String context = null;
if (lastDotPos >= 0)
{
context = name.substring(0, lastDotPos);
name = name.substring(lastDotPos + 1);
}
double minTime = 0, maxTime = 0, minValues = 0, maxValues = 0;
an.addSignal(signalNames[i], context, minTime, maxTime, minValues, maxValues);
}
return sd;
}
}
return null;
}
private double getNextDouble()
throws IOException
{
// double values appear with reversed bytes
long lt = dataInputStream.readLong();
lt = Long.reverseBytes(lt);
double t = Double.longBitsToDouble(lt);
int amtRead = 8;
// for complex plots, ignore imaginary part
if (complexValues) { amtRead *= 2; dataInputStream.readLong(); }
updateProgressDialog(amtRead);
return t;
}
private float getNextFloat()
throws IOException
{
// float values appear with reversed bytes
int lt = dataInputStream.readInt();
lt = Integer.reverseBytes(lt);
float t = Float.intBitsToFloat(lt);
int amtRead = 4;
// for complex plots, ignore imaginary part
if (complexValues) { amtRead *= 2; dataInputStream.readInt(); }
updateProgressDialog(amtRead);
return t;
}
}
| true | true | private Stimuli readRawLTSpiceFile(Cell cell)
throws IOException
{
complexValues = false;
boolean realValues = false;
int signalCount = -1;
String[] signalNames = null;
int rowCount = -1;
AnalogAnalysis.AnalysisType aType = AnalogAnalysis.ANALYSIS_TRANS;
for(;;)
{
String line = getLineFromBinary();
if (line == null) break;
updateProgressDialog(line.length());
// find the ":" separator
int colonPos = line.indexOf(':');
if (colonPos < 0) continue;
String keyWord = line.substring(0, colonPos);
String restOfLine = line.substring(colonPos+1).trim();
if (keyWord.equals("Plotname"))
{
// see if known analysis is specified
if (restOfLine.equals("AC Analysis")) aType = AnalogAnalysis.ANALYSIS_AC;
continue;
}
if (keyWord.equals("Flags"))
{
// the first signal is Time
int complex = restOfLine.indexOf("complex");
if (complex >= 0) complexValues = true;
int r = restOfLine.indexOf("real");
if (r >= 0) realValues = true;
continue;
}
if (keyWord.equals("No. Variables"))
{
// the first signal is Time
signalCount = TextUtils.atoi(restOfLine) - 1;
continue;
}
if (keyWord.equals("No. Points"))
{
rowCount = TextUtils.atoi(restOfLine);
continue;
}
if (keyWord.equals("Variables"))
{
if (signalCount < 0)
{
System.out.println("Missing variable count in file");
return null;
}
signalNames = new String[signalCount];
for(int i=0; i<=signalCount; i++)
{
restOfLine = getLineFromBinary();
if (restOfLine == null) break;
updateProgressDialog(restOfLine.length());
restOfLine = restOfLine.trim();
int indexOnLine = TextUtils.atoi(restOfLine);
if (indexOnLine != i)
System.out.println("Warning: Variable " + i + " has number " + indexOnLine);
int nameStart = 0;
while (nameStart < restOfLine.length() && !Character.isWhitespace(restOfLine.charAt(nameStart))) nameStart++;
while (nameStart < restOfLine.length() && Character.isWhitespace(restOfLine.charAt(nameStart))) nameStart++;
int nameEnd = nameStart;
while (nameEnd < restOfLine.length() && !Character.isWhitespace(restOfLine.charAt(nameEnd))) nameEnd++;
String name = restOfLine.substring(nameStart, nameEnd);
if (name.startsWith("v(") && name.endsWith(")"))
{
name = name.substring(2, name.length()-1);
}
if (i > 0) signalNames[i-1] = name;
}
continue;
}
if (keyWord.equals("Binary"))
{
if (signalCount < 0)
{
System.out.println("Missing variable count in file");
return null;
}
if (rowCount < 0)
{
System.out.println("Missing point count in file");
return null;
}
// initialize the stimuli object
Stimuli sd = new Stimuli();
SweepAnalysisLT an = new SweepAnalysisLT(sd, aType);
sd.setCell(cell);
if (DEBUG)
{
System.out.println(signalCount+" VARIABLES, "+rowCount+" SAMPLES");
for(int i=0; i<signalCount; i++)
System.out.println("VARIABLE "+i+" IS "+signalNames[i]);
}
// read all of the data in the RAW file
double[][] values = new double[signalCount][rowCount];
double [] timeValues = new double[rowCount];
for(int j=0; j<rowCount; j++)
{
double time = getNextDouble();
if (DEBUG) System.out.println("TIME AT "+j+" IS "+time);
timeValues[j] = Math.abs(time);
for(int i=0; i<signalCount; i++)
{
double value = 0;
if (realValues) value = getNextFloat(); else
value = getNextDouble();
if (DEBUG) System.out.println(" DATA POINT "+i+" ("+signalNames[i]+") IS "+value);
values[i][j] = value;
}
}
// figure out where the sweep breaks occur
int sweepLength = -1;
int sweepStart = 0;
int sweepCount = 0;
for(int j=1; j<=rowCount; j++)
{
if (j == rowCount || timeValues[j] < timeValues[j-1])
{
int sl = j - sweepStart;
if (sweepLength >= 0 && sweepLength != sl)
System.out.println("ERROR! Sweeps have different length (" + sweepLength + " and " + sl + ")");
sweepLength = sl;
sweepStart = j;
sweepCount++;
an.addSweep(Integer.toString(sweepCount));
}
}
if (DEBUG) System.out.println("FOUND " + sweepCount + " SWEEPS OF LENGTH " + sweepLength);
// place data into the Analysis object
an.commonTime = new double[sweepCount][];
for(int s=0; s<sweepCount; s++)
{
int offset = s * sweepLength;
an.commonTime[s] = new double[sweepLength];
for (int j = 0; j < sweepLength; j++)
an.commonTime[s][j] = timeValues[j + offset];
List<double[]> allTheData = new ArrayList<double[]>();
for(int i=0; i<signalCount; i++)
{
double[] oneSetOfData = new double[sweepLength];
for(int j=0; j<sweepLength; j++)
oneSetOfData[j] = values[i][j+offset];
allTheData.add(oneSetOfData);
}
an.theSweeps.add(allTheData);
}
// add signal names to the analysis
for (int i = 0; i < signalCount; i++)
{
String name = signalNames[i];
int lastDotPos = name.lastIndexOf('.');
String context = null;
if (lastDotPos >= 0)
{
context = name.substring(0, lastDotPos);
name = name.substring(lastDotPos + 1);
}
double minTime = 0, maxTime = 0, minValues = 0, maxValues = 0;
an.addSignal(signalNames[i], context, minTime, maxTime, minValues, maxValues);
}
return sd;
}
}
return null;
}
| private Stimuli readRawLTSpiceFile(Cell cell)
throws IOException
{
complexValues = false;
boolean realValues = false;
int signalCount = -1;
String[] signalNames = null;
int rowCount = -1;
AnalogAnalysis.AnalysisType aType = AnalogAnalysis.ANALYSIS_TRANS;
for(;;)
{
String line = getLineFromBinary();
if (line == null) break;
updateProgressDialog(line.length());
// find the ":" separator
int colonPos = line.indexOf(':');
if (colonPos < 0) continue;
String keyWord = line.substring(0, colonPos);
String restOfLine = line.substring(colonPos+1).trim();
if (keyWord.equals("Plotname"))
{
// see if known analysis is specified
if (restOfLine.equals("AC Analysis")) aType = AnalogAnalysis.ANALYSIS_AC;
continue;
}
if (keyWord.equals("Flags"))
{
// the first signal is Time
int complex = restOfLine.indexOf("complex");
if (complex >= 0) complexValues = true;
int r = restOfLine.indexOf("real");
if (r >= 0) realValues = true;
continue;
}
if (keyWord.equals("No. Variables"))
{
// the first signal is Time
signalCount = TextUtils.atoi(restOfLine) - 1;
continue;
}
if (keyWord.equals("No. Points"))
{
rowCount = TextUtils.atoi(restOfLine);
continue;
}
if (keyWord.equals("Variables"))
{
if (signalCount < 0)
{
System.out.println("Missing variable count in file");
return null;
}
signalNames = new String[signalCount];
for(int i=0; i<=signalCount; i++)
{
restOfLine = getLineFromBinary();
if (restOfLine == null) break;
updateProgressDialog(restOfLine.length());
restOfLine = restOfLine.trim();
int indexOnLine = TextUtils.atoi(restOfLine);
if (indexOnLine != i)
System.out.println("Warning: Variable " + i + " has number " + indexOnLine);
int nameStart = 0;
while (nameStart < restOfLine.length() && !Character.isWhitespace(restOfLine.charAt(nameStart))) nameStart++;
while (nameStart < restOfLine.length() && Character.isWhitespace(restOfLine.charAt(nameStart))) nameStart++;
int nameEnd = nameStart;
while (nameEnd < restOfLine.length() && !Character.isWhitespace(restOfLine.charAt(nameEnd))) nameEnd++;
String name = restOfLine.substring(nameStart, nameEnd);
if (name.startsWith("V(") && name.endsWith(")"))
{
name = name.substring(2, name.length()-1);
}
if (i > 0) signalNames[i-1] = name;
}
continue;
}
if (keyWord.equals("Binary"))
{
if (signalCount < 0)
{
System.out.println("Missing variable count in file");
return null;
}
if (rowCount < 0)
{
System.out.println("Missing point count in file");
return null;
}
// initialize the stimuli object
Stimuli sd = new Stimuli();
SweepAnalysisLT an = new SweepAnalysisLT(sd, aType);
sd.setCell(cell);
if (DEBUG)
{
System.out.println(signalCount+" VARIABLES, "+rowCount+" SAMPLES");
for(int i=0; i<signalCount; i++)
System.out.println("VARIABLE "+i+" IS "+signalNames[i]);
}
// read all of the data in the RAW file
double[][] values = new double[signalCount][rowCount];
double [] timeValues = new double[rowCount];
for(int j=0; j<rowCount; j++)
{
double time = getNextDouble();
if (DEBUG) System.out.println("TIME AT "+j+" IS "+time);
timeValues[j] = Math.abs(time);
for(int i=0; i<signalCount; i++)
{
double value = 0;
if (realValues) value = getNextFloat(); else
value = getNextDouble();
if (DEBUG) System.out.println(" DATA POINT "+i+" ("+signalNames[i]+") IS "+value);
values[i][j] = value;
}
}
// figure out where the sweep breaks occur
int sweepLength = -1;
int sweepStart = 0;
int sweepCount = 0;
for(int j=1; j<=rowCount; j++)
{
if (j == rowCount || timeValues[j] < timeValues[j-1])
{
int sl = j - sweepStart;
if (sweepLength >= 0 && sweepLength != sl)
System.out.println("ERROR! Sweeps have different length (" + sweepLength + " and " + sl + ")");
sweepLength = sl;
sweepStart = j;
sweepCount++;
an.addSweep(Integer.toString(sweepCount));
}
}
if (DEBUG) System.out.println("FOUND " + sweepCount + " SWEEPS OF LENGTH " + sweepLength);
// place data into the Analysis object
an.commonTime = new double[sweepCount][];
for(int s=0; s<sweepCount; s++)
{
int offset = s * sweepLength;
an.commonTime[s] = new double[sweepLength];
for (int j = 0; j < sweepLength; j++)
an.commonTime[s][j] = timeValues[j + offset];
List<double[]> allTheData = new ArrayList<double[]>();
for(int i=0; i<signalCount; i++)
{
double[] oneSetOfData = new double[sweepLength];
for(int j=0; j<sweepLength; j++)
oneSetOfData[j] = values[i][j+offset];
allTheData.add(oneSetOfData);
}
an.theSweeps.add(allTheData);
}
// add signal names to the analysis
for (int i = 0; i < signalCount; i++)
{
String name = signalNames[i];
int lastDotPos = name.lastIndexOf('.');
String context = null;
if (lastDotPos >= 0)
{
context = name.substring(0, lastDotPos);
name = name.substring(lastDotPos + 1);
}
double minTime = 0, maxTime = 0, minValues = 0, maxValues = 0;
an.addSignal(signalNames[i], context, minTime, maxTime, minValues, maxValues);
}
return sd;
}
}
return null;
}
|
diff --git a/src/main/java/fr/msch/wissl/launcher/Launcher.java b/src/main/java/fr/msch/wissl/launcher/Launcher.java
index 3e20580..16adf9f 100644
--- a/src/main/java/fr/msch/wissl/launcher/Launcher.java
+++ b/src/main/java/fr/msch/wissl/launcher/Launcher.java
@@ -1,234 +1,239 @@
/* This file is part of Wissl - Copyright (C) 2012 Mathieu Schnoor
*
* 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 fr.msch.wissl.launcher;
import java.awt.Desktop;
import java.awt.GraphicsEnvironment;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.ProtectionDomain;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.bio.SocketConnector;
import org.eclipse.jetty.webapp.WebAppContext;
/**
*
*
* @author [email protected]
*
*/
public class Launcher {
public static void main(String[] args) {
File configFile = null;
int port = 8080;
boolean verbose = false;
for (int i = 0; i < args.length; i++) {
String str = args[i];
if ("-c".equals(str)) {
i++;
if (args.length == i) {
error("Option -c requires an argument");
} else {
configFile = new File(args[i]);
}
} else if ("-v".equals(str)) {
verbose = true;
} else {
if (str.startsWith("-D")) {
Pattern pat = Pattern.compile("^-D([^=]+)(?:=(.+))?");
Matcher mat = pat.matcher(str);
if (mat.matches()) {
if (mat.groupCount() > 0) {
String key = mat.group(1);
String val = mat.group(2);
if (val == null) {
System.setProperty(key, "");
} else {
System.setProperty(key, val);
}
} else {
error("Invalid argument: " + str);
}
}
} else {
if (!"-h".equals(str)) {
System.out.println("Unknown option: " + str);
}
System.out.println("Usage: java "
+ Launcher.class.getCanonicalName() + " [opts]");
System.out.println("Options:");
System.out.println("-c CONF Configuration file path [="
+ configFile.getAbsolutePath() + "]");
System.out.println("-v Verbose stdout");
System.out.println("-Dx=y JVM system property");
System.exit(0);
}
}
}
String pp = System.getProperty("wsl.http.port");
if (configFile != null) {
if (configFile.exists()) {
System.setProperty("wsl.config", configFile.getAbsolutePath());
Properties props = new Properties();
try {
props.load(new FileInputStream(configFile));
port = Integer.parseInt(props.getProperty("wsl.http.port"));
} catch (IOException e) {
e.printStackTrace();
error("Failed to read port from config");
}
} else {
error("Config file does not exist:"
+ configFile.getAbsolutePath());
}
}
if (pp != null && pp.trim().length() > 0) {
port = Integer.parseInt(pp);
}
PrintStream sysout = System.out;
if (!verbose) {
try {
PrintStream ps = new PrintStream(File.createTempFile("wissl",
".stdout"));
System.setOut(ps);
System.setErr(ps);
} catch (IOException e) {
e.printStackTrace();
}
}
setLF();
if (isRunning(port)) {
error("Wissl is already running on http://localhost:" + port);
}
- startServer(port);
+ final int fport = port;
+ new Thread(new Runnable() {
+ public void run() {
+ startServer(fport);
+ }
+ }).start();
URI uri = null;
try {
uri = new URI("http://localhost:" + port);
} catch (URISyntaxException e) {
e.printStackTrace();
System.exit(1);
}
if (GraphicsEnvironment.isHeadless()) {
sysout.println("Server started: " + uri.toString());
} else {
try {
Desktop.getDesktop().browse(uri);
} catch (IOException e) {
e.printStackTrace();
}
}
}
static void startServer(int port) {
Server server = new Server();
SocketConnector connector = new SocketConnector();
connector.setPort(port);
server.setConnectors(new Connector[] { connector });
WebAppContext context = new WebAppContext();
context.setServer(server);
context.setContextPath("/");
ProtectionDomain protectionDomain = Launcher.class
.getProtectionDomain();
URL location = protectionDomain.getCodeSource().getLocation();
context.setWar(location.toExternalForm());
server.setHandler(context);
try {
server.start();
} catch (Exception e) {
e.printStackTrace();
error("Failed to start server");
}
}
static boolean isRunning(int port) {
String endpoint = "http://localhost:" + port + "/wissl/hasusers";
try {
// can't use commons httpclient, don't have the jar inside the launcher
HttpURLConnection get = (HttpURLConnection) new URL(endpoint)
.openConnection();
if (get.getResponseCode() == 200) {
return true;
}
} catch (IOException e) {
}
return false;
}
private static void setLF() {
if (GraphicsEnvironment.isHeadless())
return;
try {
if (System.getProperty("os.name").toLowerCase().contains("linux")) {
UIManager
.setLookAndFeel("com.sun.java.swing.plaf.gtk.GTKLookAndFeel");
} else {
UIManager.setLookAndFeel(UIManager
.getSystemLookAndFeelClassName());
}
} catch (Exception e) {
e.printStackTrace();
}
}
static void error(String msg) {
if (GraphicsEnvironment.isHeadless()) {
System.out.println(msg);
System.exit(1);
} else {
setLF();
JOptionPane.showMessageDialog(null, msg, "wissl",
JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
}
}
| true | true | public static void main(String[] args) {
File configFile = null;
int port = 8080;
boolean verbose = false;
for (int i = 0; i < args.length; i++) {
String str = args[i];
if ("-c".equals(str)) {
i++;
if (args.length == i) {
error("Option -c requires an argument");
} else {
configFile = new File(args[i]);
}
} else if ("-v".equals(str)) {
verbose = true;
} else {
if (str.startsWith("-D")) {
Pattern pat = Pattern.compile("^-D([^=]+)(?:=(.+))?");
Matcher mat = pat.matcher(str);
if (mat.matches()) {
if (mat.groupCount() > 0) {
String key = mat.group(1);
String val = mat.group(2);
if (val == null) {
System.setProperty(key, "");
} else {
System.setProperty(key, val);
}
} else {
error("Invalid argument: " + str);
}
}
} else {
if (!"-h".equals(str)) {
System.out.println("Unknown option: " + str);
}
System.out.println("Usage: java "
+ Launcher.class.getCanonicalName() + " [opts]");
System.out.println("Options:");
System.out.println("-c CONF Configuration file path [="
+ configFile.getAbsolutePath() + "]");
System.out.println("-v Verbose stdout");
System.out.println("-Dx=y JVM system property");
System.exit(0);
}
}
}
String pp = System.getProperty("wsl.http.port");
if (configFile != null) {
if (configFile.exists()) {
System.setProperty("wsl.config", configFile.getAbsolutePath());
Properties props = new Properties();
try {
props.load(new FileInputStream(configFile));
port = Integer.parseInt(props.getProperty("wsl.http.port"));
} catch (IOException e) {
e.printStackTrace();
error("Failed to read port from config");
}
} else {
error("Config file does not exist:"
+ configFile.getAbsolutePath());
}
}
if (pp != null && pp.trim().length() > 0) {
port = Integer.parseInt(pp);
}
PrintStream sysout = System.out;
if (!verbose) {
try {
PrintStream ps = new PrintStream(File.createTempFile("wissl",
".stdout"));
System.setOut(ps);
System.setErr(ps);
} catch (IOException e) {
e.printStackTrace();
}
}
setLF();
if (isRunning(port)) {
error("Wissl is already running on http://localhost:" + port);
}
startServer(port);
URI uri = null;
try {
uri = new URI("http://localhost:" + port);
} catch (URISyntaxException e) {
e.printStackTrace();
System.exit(1);
}
if (GraphicsEnvironment.isHeadless()) {
sysout.println("Server started: " + uri.toString());
} else {
try {
Desktop.getDesktop().browse(uri);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| public static void main(String[] args) {
File configFile = null;
int port = 8080;
boolean verbose = false;
for (int i = 0; i < args.length; i++) {
String str = args[i];
if ("-c".equals(str)) {
i++;
if (args.length == i) {
error("Option -c requires an argument");
} else {
configFile = new File(args[i]);
}
} else if ("-v".equals(str)) {
verbose = true;
} else {
if (str.startsWith("-D")) {
Pattern pat = Pattern.compile("^-D([^=]+)(?:=(.+))?");
Matcher mat = pat.matcher(str);
if (mat.matches()) {
if (mat.groupCount() > 0) {
String key = mat.group(1);
String val = mat.group(2);
if (val == null) {
System.setProperty(key, "");
} else {
System.setProperty(key, val);
}
} else {
error("Invalid argument: " + str);
}
}
} else {
if (!"-h".equals(str)) {
System.out.println("Unknown option: " + str);
}
System.out.println("Usage: java "
+ Launcher.class.getCanonicalName() + " [opts]");
System.out.println("Options:");
System.out.println("-c CONF Configuration file path [="
+ configFile.getAbsolutePath() + "]");
System.out.println("-v Verbose stdout");
System.out.println("-Dx=y JVM system property");
System.exit(0);
}
}
}
String pp = System.getProperty("wsl.http.port");
if (configFile != null) {
if (configFile.exists()) {
System.setProperty("wsl.config", configFile.getAbsolutePath());
Properties props = new Properties();
try {
props.load(new FileInputStream(configFile));
port = Integer.parseInt(props.getProperty("wsl.http.port"));
} catch (IOException e) {
e.printStackTrace();
error("Failed to read port from config");
}
} else {
error("Config file does not exist:"
+ configFile.getAbsolutePath());
}
}
if (pp != null && pp.trim().length() > 0) {
port = Integer.parseInt(pp);
}
PrintStream sysout = System.out;
if (!verbose) {
try {
PrintStream ps = new PrintStream(File.createTempFile("wissl",
".stdout"));
System.setOut(ps);
System.setErr(ps);
} catch (IOException e) {
e.printStackTrace();
}
}
setLF();
if (isRunning(port)) {
error("Wissl is already running on http://localhost:" + port);
}
final int fport = port;
new Thread(new Runnable() {
public void run() {
startServer(fport);
}
}).start();
URI uri = null;
try {
uri = new URI("http://localhost:" + port);
} catch (URISyntaxException e) {
e.printStackTrace();
System.exit(1);
}
if (GraphicsEnvironment.isHeadless()) {
sysout.println("Server started: " + uri.toString());
} else {
try {
Desktop.getDesktop().browse(uri);
} catch (IOException e) {
e.printStackTrace();
}
}
}
|
diff --git a/eol-globi-data-tool/src/main/java/org/eol/globi/service/EcoRegionFinderProxy.java b/eol-globi-data-tool/src/main/java/org/eol/globi/service/EcoRegionFinderProxy.java
index aad4c71b..a9457aec 100644
--- a/eol-globi-data-tool/src/main/java/org/eol/globi/service/EcoRegionFinderProxy.java
+++ b/eol-globi-data-tool/src/main/java/org/eol/globi/service/EcoRegionFinderProxy.java
@@ -1,39 +1,39 @@
package org.eol.globi.service;
import org.eol.globi.geo.EcoRegion;
import org.eol.globi.geo.EcoRegionFinder;
import org.eol.globi.geo.EcoRegionFinderException;
import org.eol.globi.geo.EcoRegionFinderFactory;
import org.eol.globi.geo.EcoRegionFinderFactoryImpl;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class EcoRegionFinderProxy implements EcoRegionFinder {
public static final ArrayList<EcoRegion> EMPTY_REGIONS = new ArrayList<EcoRegion>();
private final EcoRegionFinderFactory factory;
public List<EcoRegionFinder> finders;
public EcoRegionFinderProxy(EcoRegionFinderFactory factory) {
this.factory = factory;
}
@Override
public Collection<EcoRegion> findEcoRegion(double lat, double lng) throws EcoRegionFinderException {
if (finders == null) {
finders = factory.createAll();
}
Collection<EcoRegion> regions = null;
for (EcoRegionFinder finder : finders) {
Collection<EcoRegion> ecoRegion = finder.findEcoRegion(lat, lng);
- if (ecoRegion.size() > 0 && regions == null) {
+ if (ecoRegion != null && ecoRegion.size() > 0 && regions == null) {
regions = new ArrayList<EcoRegion>();
for (EcoRegion region : ecoRegion) {
regions.add(region);
}
}
}
return regions == null ? EMPTY_REGIONS : regions;
}
}
| true | true | public Collection<EcoRegion> findEcoRegion(double lat, double lng) throws EcoRegionFinderException {
if (finders == null) {
finders = factory.createAll();
}
Collection<EcoRegion> regions = null;
for (EcoRegionFinder finder : finders) {
Collection<EcoRegion> ecoRegion = finder.findEcoRegion(lat, lng);
if (ecoRegion.size() > 0 && regions == null) {
regions = new ArrayList<EcoRegion>();
for (EcoRegion region : ecoRegion) {
regions.add(region);
}
}
}
return regions == null ? EMPTY_REGIONS : regions;
}
| public Collection<EcoRegion> findEcoRegion(double lat, double lng) throws EcoRegionFinderException {
if (finders == null) {
finders = factory.createAll();
}
Collection<EcoRegion> regions = null;
for (EcoRegionFinder finder : finders) {
Collection<EcoRegion> ecoRegion = finder.findEcoRegion(lat, lng);
if (ecoRegion != null && ecoRegion.size() > 0 && regions == null) {
regions = new ArrayList<EcoRegion>();
for (EcoRegion region : ecoRegion) {
regions.add(region);
}
}
}
return regions == null ? EMPTY_REGIONS : regions;
}
|
diff --git a/designs/cinematic/plugins/org.obeonetwork.dsl.cinematic.design/src/org/obeonetwork/dsl/cinematic/design/services/CinematicToolkitsServices.java b/designs/cinematic/plugins/org.obeonetwork.dsl.cinematic.design/src/org/obeonetwork/dsl/cinematic/design/services/CinematicToolkitsServices.java
index 122d6bc6..1b17e44e 100644
--- a/designs/cinematic/plugins/org.obeonetwork.dsl.cinematic.design/src/org/obeonetwork/dsl/cinematic/design/services/CinematicToolkitsServices.java
+++ b/designs/cinematic/plugins/org.obeonetwork.dsl.cinematic.design/src/org/obeonetwork/dsl/cinematic/design/services/CinematicToolkitsServices.java
@@ -1,105 +1,108 @@
/**
* Copyright (c) 2012 Obeo.
* 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:
* Obeo - initial API and implementation
*/
package org.obeonetwork.dsl.cinematic.design.services;
import java.util.ArrayList;
import java.util.Collection;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.obeonetwork.dsl.cinematic.CinematicRoot;
import org.obeonetwork.dsl.cinematic.toolkits.Toolkit;
import org.obeonetwork.dsl.cinematic.toolkits.util.ToolkitsProvider;
public class CinematicToolkitsServices {
public static Collection<Toolkit> getCinematicProvidedToolkits(EObject context, Collection<Toolkit> alreadyUsedToolkits) {
Collection<Toolkit> toolkits = new ArrayList<Toolkit>();
+ Collection<URI> toolkitsURI = new ArrayList<URI>();
// Get toolkits in ResourceSet
Collection<Toolkit> toolkitsInResourceSet = getToolkitsInResourceSet(context);
for (Toolkit toolkitInResourceSet : toolkitsInResourceSet) {
// We do not propose the already used toolkits
if (!alreadyUsedToolkits.contains(toolkitInResourceSet)) {
toolkits.add(toolkitInResourceSet);
+ toolkitsURI.add(EcoreUtil.getURI(toolkitInResourceSet));
}
}
// Get the already used toolkits URI which should not be proposed
Collection<URI> alreadyUsedToolkitsURIs = new ArrayList<URI>();
for (Toolkit usedToolkit : alreadyUsedToolkits) {
alreadyUsedToolkitsURIs.add(EcoreUtil.getURI(usedToolkit));
}
// Get toolkits provided using the extension point
- Collection<URI> toolkitsURI = ToolkitsProvider.getProvidedToolkits();
- for (URI uri : toolkitsURI) {
+ Collection<URI> providedToolkitsURI = ToolkitsProvider.getProvidedToolkits();
+ for (URI uri : providedToolkitsURI) {
ResourceSet set = new ResourceSetImpl();
Resource resource = set.getResource(uri, true);
if (resource != null && resource.getContents() != null) {
for (EObject root : resource.getContents()) {
if (root instanceof Toolkit) {
Toolkit toolkit = (Toolkit)root;
- if (!toolkits.contains(toolkit) && !alreadyUsedToolkitsURIs.contains(EcoreUtil.getURI(toolkit))) {
+ URI toolkitURI = EcoreUtil.getURI(toolkit);
+ if (!toolkitsURI.contains(toolkitURI) && !alreadyUsedToolkitsURIs.contains(toolkitURI)) {
toolkits.add(toolkit);
}
}
}
}
}
// Get toolkits in ResourceSet
return toolkits;
}
private static Collection<Toolkit> getToolkitsInResourceSet(EObject context) {
Collection<Toolkit> toolkits = new ArrayList<Toolkit>();
// Get ResourceSet
if (context.eResource() != null) {
ResourceSet set = context.eResource().getResourceSet();
if (set != null) {
for (Resource resource : set.getResources()) {
for (EObject object : resource.getContents()) {
if (object instanceof Toolkit) {
toolkits.add((Toolkit)object);
}
}
}
}
}
return toolkits;
}
public static CinematicRoot associateToolkit(CinematicRoot root, Toolkit toolkit) {
URI toolkitUri = EcoreUtil.getURI(toolkit);
// Check if it's already associated
for (Toolkit usedToolkit : root.getToolkits()) {
if (EcoreUtil.getURI(usedToolkit).equals(toolkitUri)) {
// already associated, do nothing and just return
return root;
}
}
// We now have to associate the toolkit to the root object
ResourceSet set = root.eResource().getResourceSet();
EObject newToolkit = set.getEObject(toolkitUri, true);
if (newToolkit instanceof Toolkit) {
root.getToolkits().add((Toolkit)newToolkit);
}
return root;
}
}
| false | true | public static Collection<Toolkit> getCinematicProvidedToolkits(EObject context, Collection<Toolkit> alreadyUsedToolkits) {
Collection<Toolkit> toolkits = new ArrayList<Toolkit>();
// Get toolkits in ResourceSet
Collection<Toolkit> toolkitsInResourceSet = getToolkitsInResourceSet(context);
for (Toolkit toolkitInResourceSet : toolkitsInResourceSet) {
// We do not propose the already used toolkits
if (!alreadyUsedToolkits.contains(toolkitInResourceSet)) {
toolkits.add(toolkitInResourceSet);
}
}
// Get the already used toolkits URI which should not be proposed
Collection<URI> alreadyUsedToolkitsURIs = new ArrayList<URI>();
for (Toolkit usedToolkit : alreadyUsedToolkits) {
alreadyUsedToolkitsURIs.add(EcoreUtil.getURI(usedToolkit));
}
// Get toolkits provided using the extension point
Collection<URI> toolkitsURI = ToolkitsProvider.getProvidedToolkits();
for (URI uri : toolkitsURI) {
ResourceSet set = new ResourceSetImpl();
Resource resource = set.getResource(uri, true);
if (resource != null && resource.getContents() != null) {
for (EObject root : resource.getContents()) {
if (root instanceof Toolkit) {
Toolkit toolkit = (Toolkit)root;
if (!toolkits.contains(toolkit) && !alreadyUsedToolkitsURIs.contains(EcoreUtil.getURI(toolkit))) {
toolkits.add(toolkit);
}
}
}
}
}
// Get toolkits in ResourceSet
return toolkits;
}
| public static Collection<Toolkit> getCinematicProvidedToolkits(EObject context, Collection<Toolkit> alreadyUsedToolkits) {
Collection<Toolkit> toolkits = new ArrayList<Toolkit>();
Collection<URI> toolkitsURI = new ArrayList<URI>();
// Get toolkits in ResourceSet
Collection<Toolkit> toolkitsInResourceSet = getToolkitsInResourceSet(context);
for (Toolkit toolkitInResourceSet : toolkitsInResourceSet) {
// We do not propose the already used toolkits
if (!alreadyUsedToolkits.contains(toolkitInResourceSet)) {
toolkits.add(toolkitInResourceSet);
toolkitsURI.add(EcoreUtil.getURI(toolkitInResourceSet));
}
}
// Get the already used toolkits URI which should not be proposed
Collection<URI> alreadyUsedToolkitsURIs = new ArrayList<URI>();
for (Toolkit usedToolkit : alreadyUsedToolkits) {
alreadyUsedToolkitsURIs.add(EcoreUtil.getURI(usedToolkit));
}
// Get toolkits provided using the extension point
Collection<URI> providedToolkitsURI = ToolkitsProvider.getProvidedToolkits();
for (URI uri : providedToolkitsURI) {
ResourceSet set = new ResourceSetImpl();
Resource resource = set.getResource(uri, true);
if (resource != null && resource.getContents() != null) {
for (EObject root : resource.getContents()) {
if (root instanceof Toolkit) {
Toolkit toolkit = (Toolkit)root;
URI toolkitURI = EcoreUtil.getURI(toolkit);
if (!toolkitsURI.contains(toolkitURI) && !alreadyUsedToolkitsURIs.contains(toolkitURI)) {
toolkits.add(toolkit);
}
}
}
}
}
// Get toolkits in ResourceSet
return toolkits;
}
|
diff --git a/TetrisClone/src/Shape.java b/TetrisClone/src/Shape.java
index 7c3bccc..7bad882 100644
--- a/TetrisClone/src/Shape.java
+++ b/TetrisClone/src/Shape.java
@@ -1,251 +1,251 @@
import java.util.Random;
import LinkedQueue.LinkedQueue;
public abstract class Shape {
protected Block[][] blocks;
protected int x;
protected int y;
protected int rotation;
protected String color;
protected static Game game;
public Block[][] getBlocks() {
return blocks;
}
public void setBlocks(Block[][] blocks) {
this.blocks = blocks;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getRotation() {
return rotation;
}
public void setRotation(int rotation) {
this.rotation = rotation;
}
public static Game getGame() {
return game;
}
public static void setGame(Game game) {
Shape.game = game;
}
//draw shape to screen
public void draw() {
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; j++) {
if (blocks[i][j] != null)
if (y + i > 1)
//draw the block
blocks[i][j].getImage().draw((x + j) * game.getColumnWidth(),
(y + i - 2) * game.getRowHeight());
}
}
}
//clockwise rotation
public void rotateCW() {
++rotation;
rotation = rotation % 4;
Block[][] copyListBlocks = new Block[4][4];
//copy the current shape
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
copyListBlocks[i][j] = blocks[i][j];
}
}
//rotate clockwise
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
blocks[i][j] = copyListBlocks[3-j][i];
}
}
//shift blocks
shiftBlocksUpLeft();
}
//adjusts blocks
private void shiftBlocksUpLeft() {
if (!(this instanceof IShape || this instanceof OShape
|| this instanceof SShape || this instanceof ZShape))
switch (rotation) {
case 0 :
++y;
break;
case 1 :
--x;
break;
case 2 :
--y;
break;
case 3 :
++x;
break;
}
else if (this instanceof SShape || this instanceof ZShape){
if (rotation == 1){
--y;
--x;
}
else {
++y;
++x;
rotation = 0;
blocks = new Block[4][4];
if (this instanceof SShape) {
for (int i = 1; i < 3; ++i) {
blocks[0][i] = new Block(color);
}
for (int i = 0; i < 2; ++i) {
blocks[1][i] = new Block(color);
}
}
else {
for (int i = 0; i < 2; ++i) {
blocks[0][i] = new Block(color);
}
for (int i = 1; i < 3; ++i) {
blocks[1][i] = new Block(color);
}
}
}
}
- else {
+ else if (this instanceof IShape){
if (rotation == 2) {
rotation = 0;
blocks = new Block[4][4];
if (this instanceof IShape) {
for (int i = 0; i < 4; ++i) {
blocks[1][i] = new Block(color);
}
}
}
}
}
//counterclockwise rotation
public void rotateCCW() {
if (!(this instanceof IShape || this instanceof OShape
|| this instanceof SShape || this instanceof ZShape)) {
for (int i = 0; i < 3; ++i)
rotateCW();
}
else
rotateCW();
}
//resets the position and rotation of a shape to above the grid
public void reset() {
//reset rotation
while (rotation > 0)
{
rotateCW();
}
// start in the center, just above the grid
if (!(this instanceof OShape)) {
x = 3;
y = 0;
}
//set OShape 1 higher than the rest
else {
x = 3;
y = -1;
}
}
//returns y position of the highest block
public int getTop() {
for (int i = 0; i < 4; ++i){
for (int j = 0; j < 4; ++j) {
if (blocks[i][j] != null)
return y + i;
}
}
return -1;
}
//returns y position of the lowest block
public int getBottom() {
for (int i = 3; i >= 0; --i){
for (int j = 0; j < 4; ++j) {
if (blocks[i][j] != null)
return y + i;
}
}
return -1;
}
//returns x position of the leftmost block
public int getLeft() {
for (int j = 0; j < 4; ++j){
for (int i = 0; i < 4; ++i) {
if (blocks[i][j] != null)
return x + j;
}
}
return -1;
}
//returns x position of the rightmost block
public int getRight() {
for (int j = 3; j >= 0; --j){
for (int i = 0; i < 4; ++i) {
if (blocks[i][j] != null)
return x + j;
}
}
return -1;
}
//generate the next 7 shapes
public static LinkedQueue<Shape> generate() {
LinkedQueue<Shape> upcoming = new LinkedQueue<Shape>();
Random rand = new Random();
//array containing one of each shape
Shape[] bag = {new IShape(), new JShape(), new LShape(), new OShape(), new SShape(), new TShape(), new ZShape()};
//randomize order of shapes
for (int i = bag.length - 1; i >= 0; --i) {
Shape temp;
int j = rand.nextInt(i + 1);
//swap
temp = bag[j];
bag[j] = bag[i];
bag[i] = temp;
}
for (int i = 0; i < bag.length; ++i) {
upcoming.add(bag[i]);
}
return upcoming;
}
}
| true | true | private void shiftBlocksUpLeft() {
if (!(this instanceof IShape || this instanceof OShape
|| this instanceof SShape || this instanceof ZShape))
switch (rotation) {
case 0 :
++y;
break;
case 1 :
--x;
break;
case 2 :
--y;
break;
case 3 :
++x;
break;
}
else if (this instanceof SShape || this instanceof ZShape){
if (rotation == 1){
--y;
--x;
}
else {
++y;
++x;
rotation = 0;
blocks = new Block[4][4];
if (this instanceof SShape) {
for (int i = 1; i < 3; ++i) {
blocks[0][i] = new Block(color);
}
for (int i = 0; i < 2; ++i) {
blocks[1][i] = new Block(color);
}
}
else {
for (int i = 0; i < 2; ++i) {
blocks[0][i] = new Block(color);
}
for (int i = 1; i < 3; ++i) {
blocks[1][i] = new Block(color);
}
}
}
}
else {
if (rotation == 2) {
rotation = 0;
blocks = new Block[4][4];
if (this instanceof IShape) {
for (int i = 0; i < 4; ++i) {
blocks[1][i] = new Block(color);
}
}
}
}
}
| private void shiftBlocksUpLeft() {
if (!(this instanceof IShape || this instanceof OShape
|| this instanceof SShape || this instanceof ZShape))
switch (rotation) {
case 0 :
++y;
break;
case 1 :
--x;
break;
case 2 :
--y;
break;
case 3 :
++x;
break;
}
else if (this instanceof SShape || this instanceof ZShape){
if (rotation == 1){
--y;
--x;
}
else {
++y;
++x;
rotation = 0;
blocks = new Block[4][4];
if (this instanceof SShape) {
for (int i = 1; i < 3; ++i) {
blocks[0][i] = new Block(color);
}
for (int i = 0; i < 2; ++i) {
blocks[1][i] = new Block(color);
}
}
else {
for (int i = 0; i < 2; ++i) {
blocks[0][i] = new Block(color);
}
for (int i = 1; i < 3; ++i) {
blocks[1][i] = new Block(color);
}
}
}
}
else if (this instanceof IShape){
if (rotation == 2) {
rotation = 0;
blocks = new Block[4][4];
if (this instanceof IShape) {
for (int i = 0; i < 4; ++i) {
blocks[1][i] = new Block(color);
}
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.