answer
stringlengths 17
10.2M
|
|---|
package org.jpos.iso;
import java.util.Arrays;
import java.util.BitSet;
import java.util.StringTokenizer;
import java.io.UnsupportedEncodingException;
/**
* varios functions needed to pack/unpack ISO-8583 fields
*
* @author apr@cs.com.uy
* @author Hani S. Kirollos
* @author Alwyn Schoeman
* @version $Id$
* @see ISOComponent
*/
public class ISOUtil {
public static byte[] EBCDIC2ASCII = new byte[] {
(byte)0x0, (byte)0x1, (byte)0x2, (byte)0x3,
(byte)0x9C, (byte)0x9, (byte)0x86, (byte)0x7F,
(byte)0x97, (byte)0x8D, (byte)0x8E, (byte)0xB,
(byte)0xC, (byte)0xD, (byte)0xE, (byte)0xF,
(byte)0x10, (byte)0x11, (byte)0x12, (byte)0x13,
(byte)0x9D, (byte)0xA, (byte)0x8, (byte)0x87,
(byte)0x18, (byte)0x19, (byte)0x92, (byte)0x8F,
(byte)0x1C, (byte)0x1D, (byte)0x1E, (byte)0x1F,
(byte)0x80, (byte)0x81, (byte)0x82, (byte)0x83,
(byte)0x84, (byte)0x85, (byte)0x17, (byte)0x1B,
(byte)0x88, (byte)0x89, (byte)0x8A, (byte)0x8B,
(byte)0x8C, (byte)0x5, (byte)0x6, (byte)0x7,
(byte)0x90, (byte)0x91, (byte)0x16, (byte)0x93,
(byte)0x94, (byte)0x95, (byte)0x96, (byte)0x4,
(byte)0x98, (byte)0x99, (byte)0x9A, (byte)0x9B,
(byte)0x14, (byte)0x15, (byte)0x9E, (byte)0x1A,
(byte)0x20, (byte)0xA0, (byte)0xE2, (byte)0xE4,
(byte)0xE0, (byte)0xE1, (byte)0xE3, (byte)0xE5,
(byte)0xE7, (byte)0xF1, (byte)0xA2, (byte)0x2E,
(byte)0x3C, (byte)0x28, (byte)0x2B, (byte)0x7C,
(byte)0x26, (byte)0xE9, (byte)0xEA, (byte)0xEB,
(byte)0xE8, (byte)0xED, (byte)0xEE, (byte)0xEF,
(byte)0xEC, (byte)0xDF, (byte)0x21, (byte)0x24,
(byte)0x2A, (byte)0x29, (byte)0x3B, (byte)0x5E,
(byte)0x2D, (byte)0x2F, (byte)0xC2, (byte)0xC4,
(byte)0xC0, (byte)0xC1, (byte)0xC3, (byte)0xC5,
(byte)0xC7, (byte)0xD1, (byte)0xA6, (byte)0x2C,
(byte)0x25, (byte)0x5F, (byte)0x3E, (byte)0x3F,
(byte)0xF8, (byte)0xC9, (byte)0xCA, (byte)0xCB,
(byte)0xC8, (byte)0xCD, (byte)0xCE, (byte)0xCF,
(byte)0xCC, (byte)0x60, (byte)0x3A, (byte)0x23,
(byte)0x40, (byte)0x27, (byte)0x3D, (byte)0x22,
(byte)0xD8, (byte)0x61, (byte)0x62, (byte)0x63,
(byte)0x64, (byte)0x65, (byte)0x66, (byte)0x67,
(byte)0x68, (byte)0x69, (byte)0xAB, (byte)0xBB,
(byte)0xF0, (byte)0xFD, (byte)0xFE, (byte)0xB1,
(byte)0xB0, (byte)0x6A, (byte)0x6B, (byte)0x6C,
(byte)0x6D, (byte)0x6E, (byte)0x6F, (byte)0x70,
(byte)0x71, (byte)0x72, (byte)0xAA, (byte)0xBA,
(byte)0xE6, (byte)0xB8, (byte)0xC6, (byte)0xA4,
(byte)0xB5, (byte)0x7E, (byte)0x73, (byte)0x74,
(byte)0x75, (byte)0x76, (byte)0x77, (byte)0x78,
(byte)0x79, (byte)0x7A, (byte)0xA1, (byte)0xBF,
(byte)0xD0, (byte)0x5B, (byte)0xDE, (byte)0xAE,
(byte)0xAC, (byte)0xA3, (byte)0xA5, (byte)0xB7,
(byte)0xA9, (byte)0xA7, (byte)0xB6, (byte)0xBC,
(byte)0xBD, (byte)0xBE, (byte)0xDD, (byte)0xA8,
(byte)0xAF, (byte)0x5D, (byte)0xB4, (byte)0xD7,
(byte)0x7B, (byte)0x41, (byte)0x42, (byte)0x43,
(byte)0x44, (byte)0x45, (byte)0x46, (byte)0x47,
(byte)0x48, (byte)0x49, (byte)0xAD, (byte)0xF4,
(byte)0xF6, (byte)0xF2, (byte)0xF3, (byte)0xF5,
(byte)0x7D, (byte)0x4A, (byte)0x4B, (byte)0x4C,
(byte)0x4D, (byte)0x4E, (byte)0x4F, (byte)0x50,
(byte)0x51, (byte)0x52, (byte)0xB9, (byte)0xFB,
(byte)0xFC, (byte)0xF9, (byte)0xFA, (byte)0xFF,
(byte)0x5C, (byte)0xF7, (byte)0x53, (byte)0x54,
(byte)0x55, (byte)0x56, (byte)0x57, (byte)0x58,
(byte)0x59, (byte)0x5A, (byte)0xB2, (byte)0xD4,
(byte)0xD6, (byte)0xD2, (byte)0xD3, (byte)0xD5,
(byte)0x30, (byte)0x31, (byte)0x32, (byte)0x33,
(byte)0x34, (byte)0x35, (byte)0x36, (byte)0x37,
(byte)0x38, (byte)0x39, (byte)0xB3, (byte)0xDB,
(byte)0xDC, (byte)0xD9, (byte)0xDA, (byte)0x9F
};
public static byte[] ASCII2EBCDIC = new byte[] {
(byte)0x0, (byte)0x1, (byte)0x2, (byte)0x3,
(byte)0x37, (byte)0x2D, (byte)0x2E, (byte)0x2F,
(byte)0x16, (byte)0x5, (byte)0x15, (byte)0xB,
(byte)0xC, (byte)0xD, (byte)0xE, (byte)0xF,
(byte)0x10, (byte)0x11, (byte)0x12, (byte)0x13,
(byte)0x3C, (byte)0x3D, (byte)0x32, (byte)0x26,
(byte)0x18, (byte)0x19, (byte)0x3F, (byte)0x27,
(byte)0x1C, (byte)0x1D, (byte)0x1E, (byte)0x1F,
(byte)0x40, (byte)0x5A, (byte)0x7F, (byte)0x7B,
(byte)0x5B, (byte)0x6C, (byte)0x50, (byte)0x7D,
(byte)0x4D, (byte)0x5D, (byte)0x5C, (byte)0x4E,
(byte)0x6B, (byte)0x60, (byte)0x4B, (byte)0x61,
(byte)0xF0, (byte)0xF1, (byte)0xF2, (byte)0xF3,
(byte)0xF4, (byte)0xF5, (byte)0xF6, (byte)0xF7,
(byte)0xF8, (byte)0xF9, (byte)0x7A, (byte)0x5E,
(byte)0x4C, (byte)0x7E, (byte)0x6E, (byte)0x6F,
(byte)0x7C, (byte)0xC1, (byte)0xC2, (byte)0xC3,
(byte)0xC4, (byte)0xC5, (byte)0xC6, (byte)0xC7,
(byte)0xC8, (byte)0xC9, (byte)0xD1, (byte)0xD2,
(byte)0xD3, (byte)0xD4, (byte)0xD5, (byte)0xD6,
(byte)0xD7, (byte)0xD8, (byte)0xD9, (byte)0xE2,
(byte)0xE3, (byte)0xE4, (byte)0xE5, (byte)0xE6,
(byte)0xE7, (byte)0xE8, (byte)0xE9, (byte)0xAD,
(byte)0xE0, (byte)0xBD, (byte)0x5F, (byte)0x6D,
(byte)0x79, (byte)0x81, (byte)0x82, (byte)0x83,
(byte)0x84, (byte)0x85, (byte)0x86, (byte)0x87,
(byte)0x88, (byte)0x89, (byte)0x91, (byte)0x92,
(byte)0x93, (byte)0x94, (byte)0x95, (byte)0x96,
(byte)0x97, (byte)0x98, (byte)0x99, (byte)0xA2,
(byte)0xA3, (byte)0xA4, (byte)0xA5, (byte)0xA6,
(byte)0xA7, (byte)0xA8, (byte)0xA9, (byte)0xC0,
(byte)0x4F, (byte)0xD0, (byte)0xA1, (byte)0x7,
(byte)0x20, (byte)0x21, (byte)0x22, (byte)0x23,
(byte)0x24, (byte)0x25, (byte)0x6, (byte)0x17,
(byte)0x28, (byte)0x29, (byte)0x2A, (byte)0x2B,
(byte)0x2C, (byte)0x9, (byte)0xA, (byte)0x1B,
(byte)0x30, (byte)0x31, (byte)0x1A, (byte)0x33,
(byte)0x34, (byte)0x35, (byte)0x36, (byte)0x8,
(byte)0x38, (byte)0x39, (byte)0x3A, (byte)0x3B,
(byte)0x4, (byte)0x14, (byte)0x3E, (byte)0xFF,
(byte)0x41, (byte)0xAA, (byte)0x4A, (byte)0xB1,
(byte)0x9F, (byte)0xB2, (byte)0x6A, (byte)0xB5,
(byte)0xBB, (byte)0xB4, (byte)0x9A, (byte)0x8A,
(byte)0xB0, (byte)0xCA, (byte)0xAF, (byte)0xBC,
(byte)0x90, (byte)0x8F, (byte)0xEA, (byte)0xFA,
(byte)0xBE, (byte)0xA0, (byte)0xB6, (byte)0xB3,
(byte)0x9D, (byte)0xDA, (byte)0x9B, (byte)0x8B,
(byte)0xB7, (byte)0xB8, (byte)0xB9, (byte)0xAB,
(byte)0x64, (byte)0x65, (byte)0x62, (byte)0x66,
(byte)0x63, (byte)0x67, (byte)0x9E, (byte)0x68,
(byte)0x74, (byte)0x71, (byte)0x72, (byte)0x73,
(byte)0x78, (byte)0x75, (byte)0x76, (byte)0x77,
(byte)0xAC, (byte)0x69, (byte)0xED, (byte)0xEE,
(byte)0xEB, (byte)0xEF, (byte)0xEC, (byte)0xBF,
(byte)0x80, (byte)0xFD, (byte)0xFE, (byte)0xFB,
(byte)0xFC, (byte)0xBA, (byte)0xAE, (byte)0x59,
(byte)0x44, (byte)0x45, (byte)0x42, (byte)0x46,
(byte)0x43, (byte)0x47, (byte)0x9C, (byte)0x48,
(byte)0x54, (byte)0x51, (byte)0x52, (byte)0x53,
(byte)0x58, (byte)0x55, (byte)0x56, (byte)0x57,
(byte)0x8C, (byte)0x49, (byte)0xCD, (byte)0xCE,
(byte)0xCB, (byte)0xCF, (byte)0xCC, (byte)0xE1,
(byte)0x70, (byte)0xDD, (byte)0xDE, (byte)0xDB,
(byte)0xDC, (byte)0x8D, (byte)0x8E, (byte)0xDF
};
public static final byte STX = 0x02;
public static final byte FS = 0x1C;
public static final byte US = 0x1F;
public static final byte RS = 0x1D;
public static final byte GS = 0x1E;
public static final byte ETX = 0x03;
public static String ebcdicToAscii(byte[] e) {
try {
return new String (
ebcdicToAsciiBytes (e, 0, e.length), "ISO8859_1"
);
} catch (UnsupportedEncodingException ex) {
return ex.toString(); // should never happen
}
}
public static String ebcdicToAscii(byte[] e, int offset, int len) {
try {
return new String (
ebcdicToAsciiBytes (e, offset, len), "ISO8859_1"
);
} catch (UnsupportedEncodingException ex) {
return ex.toString(); // should never happen
}
}
public static byte[] ebcdicToAsciiBytes (byte[] e) {
return ebcdicToAsciiBytes (e, 0, e.length);
}
public static byte[] ebcdicToAsciiBytes(byte[] e, int offset, int len) {
byte[] a = new byte[len];
for (int i=0; i<len; i++)
a[i] = EBCDIC2ASCII[e[offset+i]&0xFF];
return a;
}
public static byte[] asciiToEbcdic(String s) {
return asciiToEbcdic (s.getBytes());
}
public static byte[] asciiToEbcdic(byte[] a) {
byte[] e = new byte[a.length];
for (int i=0; i<a.length; i++)
e[i] = ASCII2EBCDIC[a[i]&0xFF];
return e;
}
public static void asciiToEbcdic(String s, byte[] e, int offset) {
int len = s.length();
for (int i=0; i<len; i++)
e[offset + i] = ASCII2EBCDIC[s.charAt(i)&0xFF];
}
/**
* pad to the left
* @param s - original string
* @param len - desired len
* @param c - padding char
* @return padded string
*/
public static String padleft(String s, int len, char c)
throws ISOException
{
s = s.trim();
if (s.length() > len)
throw new ISOException("invalid len " +s.length() + "/" +len);
StringBuffer d = new StringBuffer (len);
int fill = len - s.length();
while (fill
d.append (c);
d.append(s);
return d.toString();
}
/**
* trim String (if not null)
* @param s String to trim
* @return String (may be null)
*/
public static String trim (String s) {
return s != null ? s.trim() : null;
}
/**
* left pad with '0'
* @param s - original string
* @param len - desired len
* @return zero padded string
*/
public static String zeropad(String s, int len) throws ISOException {
return padleft(s, len, '0');
}
/**
* pads to the right
* @param s - original string
* @param len - desired len
* @return space padded string
*/
public static String strpad(String s, int len) {
StringBuffer d = new StringBuffer(s);
while (d.length() < len)
d.append(' ');
return d.toString();
}
public static String zeropadRight (String s, int len) {
StringBuffer d = new StringBuffer(s);
while (d.length() < len)
d.append('0');
return d.toString();
}
/**
* converts to BCD
* @param s - the number
* @param padLeft - flag indicating left/right padding
* @param d The byte array to copy into.
* @param offset Where to start copying into.
* @return BCD representation of the number
*/
public static byte[] str2bcd(String s, boolean padLeft, byte[] d, int offset) {
int len = s.length();
int start = (((len & 1) == 1) && padLeft) ? 1 : 0;
for (int i=start; i < len+start; i++)
d [offset + (i >> 1)] |= (s.charAt(i-start)-'0') << ((i & 1) == 1 ? 0 : 4);
return d;
}
/**
* converts to BCD
* @param s - the number
* @param padLeft - flag indicating left/right padding
* @return BCD representation of the number
*/
public static byte[] str2bcd(String s, boolean padLeft) {
int len = s.length();
byte[] d = new byte[ (len+1) >> 1 ];
return str2bcd(s, padLeft, d, 0);
}
/**
* converts to BCD
* @param s - the number
* @param padLeft - flag indicating left/right padding
* @param fill - fill value
* @return BCD representation of the number
*/
public static byte[] str2bcd(String s, boolean padLeft, byte fill) {
int len = s.length();
byte[] d = new byte[ (len+1) >> 1 ];
Arrays.fill (d, fill);
int start = (((len & 1) == 1) && padLeft) ? 1 : 0;
for (int i=start; i < len+start; i++)
d [i >> 1] |= (s.charAt(i-start)-'0') << ((i & 1) == 1 ? 0 : 4);
return d;
}
/**
* converts a BCD representation of a number to a String
* @param b - BCD representation
* @param offset - starting offset
* @param len - BCD field len
* @param padLeft - was padLeft packed?
* @return the String representation of the number
*/
public static String bcd2str(byte[] b, int offset,
int len, boolean padLeft)
{
StringBuffer d = new StringBuffer(len);
int start = (((len & 1) == 1) && padLeft) ? 1 : 0;
for (int i=start; i < len+start; i++) {
int shift = ((i & 1) == 1 ? 0 : 4);
char c = Character.forDigit (
((b[offset+(i>>1)] >> shift) & 0x0F), 16);
if (c == 'd')
c = '=';
d.append (Character.toUpperCase (c));
}
return d.toString();
}
/**
* converts a byte array to hex string
* (suitable for dumps and ASCII packaging of Binary fields
* @param b - byte array
* @return String representation
*/
public static String hexString(byte[] b) {
StringBuffer d = new StringBuffer(b.length * 2);
for (int i=0; i<b.length; i++) {
char hi = Character.forDigit ((b[i] >> 4) & 0x0F, 16);
char lo = Character.forDigit (b[i] & 0x0F, 16);
d.append(Character.toUpperCase(hi));
d.append(Character.toUpperCase(lo));
}
return d.toString();
}
/**
* converts a byte array to printable characters
* @param b - byte array
* @return String representation
*/
public static String dumpString(byte[] b) {
StringBuffer d = new StringBuffer(b.length * 2);
for (int i=0; i<b.length; i++) {
char c = (char) b[i];
if (Character.isISOControl (c)) {
// TODO: complete list of control characters,
// use a String[] instead of this weird switch
switch (c) {
case '\r' : d.append ("{CR}"); break;
case '\n' : d.append ("{LF}"); break;
case '\000': d.append ("{NULL}"); break;
case '\001': d.append ("{SOH}"); break;
case '\002': d.append ("{STX}"); break;
case '\003': d.append ("{ETX}"); break;
case '\004': d.append ("{EOT}"); break;
case '\005': d.append ("{ENQ}"); break;
case '\006': d.append ("{ACK}"); break;
case '\007': d.append ("{BEL}"); break;
case '\020': d.append ("{DLE}"); break;
case '\025': d.append ("{NAK}"); break;
case '\026': d.append ("{SYN}"); break;
case '\034': d.append ("{FS}"); break;
case '\036': d.append ("{RS}"); break;
default:
char hi = Character.forDigit ((b[i] >> 4) & 0x0F, 16);
char lo = Character.forDigit (b[i] & 0x0F, 16);
d.append('[');
d.append(Character.toUpperCase(hi));
d.append(Character.toUpperCase(lo));
d.append(']');
break;
}
}
else
d.append (c);
}
return d.toString();
}
/**
* converts a byte array to hex string
* (suitable for dumps and ASCII packaging of Binary fields
* @param b - byte array
* @param offset - starting position
* @param len
* @return String representation
*/
public static String hexString(byte[] b, int offset, int len) {
StringBuffer d = new StringBuffer(len * 2);
len += offset;
for (int i=offset; i<len; i++) {
char hi = Character.forDigit ((b[i] >> 4) & 0x0F, 16);
char lo = Character.forDigit (b[i] & 0x0F, 16);
d.append(Character.toUpperCase(hi));
d.append(Character.toUpperCase(lo));
}
return d.toString();
}
/**
* bit representation of a BitSet
* suitable for dumps and debugging
* @param b - the BitSet
* @return string representing the bits (i.e. 011010010...)
*/
public static String bitSet2String (BitSet b) {
int len = b.size();
len = (len > 128) ? 128: len;
StringBuffer d = new StringBuffer(len);
for (int i=0; i<len; i++)
d.append (b.get(i) ? '1' : '0');
return d.toString();
}
/**
* converts a BitSet into a binary field
* used in pack routines
* @param b - the BitSet
* @return binary representation
*/
public static byte[] bitSet2byte (BitSet b)
{
int len = (b.length() > 65) ? 128 : 64;
byte[] d = new byte[len >> 3];
for (int i=0; i<len; i++)
if (b.get(i+1))
d[i >> 3] |= (0x80 >> (i % 8));
if (len>64)
d[0] |= 0x80;
return d;
}
/**
* Converts a binary representation of a Bitmap field
* into a Java BitSet
* @param b - binary representation
* @param offset - staring offset
* @param bitZeroMeansExtended - true for ISO-8583
* @return java BitSet object
*/
public static BitSet byte2BitSet
(byte[] b, int offset, boolean bitZeroMeansExtended)
{
int len = bitZeroMeansExtended ?
((b[offset] & 0x80) == 0x80 ? 128 : 64) : 64;
BitSet bmap = new BitSet (len);
for (int i=0; i<len; i++)
if (((b[offset + (i >> 3)]) & (0x80 >> (i % 8))) > 0)
bmap.set(i+1);
return bmap;
}
/**
* Converts a binary representation of a Bitmap field
* into a Java BitSet
* @param bmap - BitSet
* @param b - hex representation
* @param bitOffset - (i.e. 0 for primary bitmap, 64 for secondary)
* @return java BitSet object
*/
public static BitSet byte2BitSet (BitSet bmap, byte[] b, int bitOffset)
{
int len = b.length << 3;
for (int i=0; i<len; i++)
if (((b[i >> 3]) & (0x80 >> (i % 8))) > 0)
bmap.set(bitOffset + i + 1);
return bmap;
}
/**
* Converts an ASCII representation of a Bitmap field
* into a Java BitSet
* @param b - hex representation
* @param offset - starting offset
* @param bitZeroMeansExtended - true for ISO-8583
* @return java BitSet object
*/
public static BitSet hex2BitSet
(byte[] b, int offset, boolean bitZeroMeansExtended)
{
int len = bitZeroMeansExtended ?
((Character.digit((char)b[offset],16) & 0x08) == 8 ? 128 : 64) :
64;
BitSet bmap = new BitSet (len);
for (int i=0; i<len; i++) {
int digit = Character.digit((char)b[offset + (i >> 2)], 16);
if ((digit & (0x08 >> (i%4))) > 0)
bmap.set(i+1);
}
return bmap;
}
/**
* Converts an ASCII representation of a Bitmap field
* into a Java BitSet
* @param bmap - BitSet
* @param b - hex representation
* @param bitOffset - (i.e. 0 for primary bitmap, 64 for secondary)
* @return java BitSet object
*/
public static BitSet hex2BitSet (BitSet bmap, byte[] b, int bitOffset)
{
int len = b.length << 2;
for (int i=0; i<len; i++) {
int digit = Character.digit((char)b[i >> 2], 16);
if ((digit & (0x08 >> (i%4))) > 0)
bmap.set (bitOffset + i + 1);
}
return bmap;
}
/**
* @param b source byte array
* @param offset starting offset
* @param len number of bytes in destination (processes len*2)
* @return byte[len]
*/
public static byte[] hex2byte (byte[] b, int offset, int len) {
byte[] d = new byte[len];
for (int i=0; i<len*2; i++) {
int shift = i%2 == 1 ? 0 : 4;
d[i>>1] |= Character.digit((char) b[offset+i], 16) << shift;
}
return d;
}
/**
* @param s source string (with Hex representation)
* @return byte array
*/
public static byte[] hex2byte (String s) {
return hex2byte (s.getBytes(), 0, s.length() >> 1);
}
/**
* format double value
* @param amount the amount
* @param fieldLen the field len
* @return a String of fieldLen characters (right justified)
*/
public static String formatDouble(double d, int len) {
String prefix = Long.toString((long) d);
String suffix = Integer.toString (
(int) ((Math.round(d * 100f)) % 100) );
try {
prefix = ISOUtil.padleft(prefix,len-3,' ');
suffix = ISOUtil.zeropad(suffix, 2);
} catch (ISOException e) {
e.printStackTrace();
}
return prefix + "." + suffix;
}
/**
* prepare long value used as amount for display
* (implicit 2 decimals)
* @param l value
* @param len display len
* @return formated field
* @exception ISOException
*/
public static String formatAmount(long l, int len) throws ISOException {
String buf = Long.toString(l);
if (l < 100)
buf = zeropad(buf, 3);
StringBuffer s = new StringBuffer(padleft (buf, len-1, ' ') );
s.insert(len-3, '.');
return s.toString();
}
/**
* XML normalizer
* @param s source String
* @param canonical true if we want to normalize \r and \n as well
* @return normalized string suitable for XML Output
*/
public static String normalize (String s, boolean canonical) {
StringBuffer str = new StringBuffer();
int len = (s != null) ? s.length() : 0;
for (int i = 0; i < len; i++) {
char ch = s.charAt(i);
switch (ch) {
case '<':
str.append("<");
break;
case '>':
str.append(">");
break;
case '&':
str.append("&");
break;
case '"':
str.append(""");
break;
case '\r':
case '\n':
if (canonical) {
str.append("&
str.append(Integer.toString(ch));
str.append(';');
break;
}
// else, default append char
default:
if (ch >= 0x20 && ch <= 0x7F)
str.append(ch);
else {
str.append("&
str.append(Integer.toString(ch));
str.append(';');
}
}
}
return (str.toString());
}
/**
* XML normalizer (default canonical)
* @param s source String
* @return normalized string suitable for XML Output
*/
public static String normalize (String s) {
return normalize (s, true);
}
public static String protect (String s) {
StringBuffer sb = new StringBuffer();
int len = s.length();
int clear = len > 6 ? 6 : 0;
int lastFourIndex = -1;
if (clear > 0) {
lastFourIndex = s.indexOf ('=') - 4;
if (lastFourIndex < 0) {
lastFourIndex = s.indexOf ('^') - 4;
if (lastFourIndex < 0)
lastFourIndex = len - 4;
}
}
for (int i=0; i<len; i++) {
if (s.charAt(i) == '=')
clear = 5;
else if (s.charAt(i) == '^') {
lastFourIndex = 0;
clear = len - i;
}
else if (i == lastFourIndex)
clear = 4;
sb.append (clear-- > 0 ? s.charAt(i) : '_');
}
return sb.toString();
}
public static int[] toIntArray(String s) {
StringTokenizer st = new StringTokenizer (s);
int[] array = new int [st.countTokens()];
for (int i=0; st.hasMoreTokens(); i++)
array[i] = Integer.parseInt (st.nextToken());
return array;
}
/**
* Bitwise XOR between corresponding bytes
* @param op1 byteArray1
* @param op2 byteArray2
* @return an array of length = the smallest between op1 and op2
*/
public static byte[] xor (byte[] op1, byte[] op2) {
byte[] result = null;
// Use the smallest array
if (op2.length > op1.length) {
result = new byte[op1.length];
}
else {
result = new byte[op2.length];
}
for (int i = 0; i < result.length; i++) {
result[i] = (byte)(op1[i] ^ op2[i]);
}
return result;
}
/**
* Bitwise XOR between corresponding byte arrays represented in hex
* @param op1 hexstring 1
* @param op2 hexstring 2
* @return an array of length = the smallest between op1 and op2
*/
public static String hexor (String op1, String op2) {
byte[] xor = xor (hex2byte (op1), hex2byte (op2));
return hexString (xor);
}
/**
* Trims a byte[] to a certain length
* @param array the byte[] to be trimmed
* @param length the wanted length
* @return the trimmed byte[]
*/
public static byte[] trim (byte[] array, int length) {
byte[] trimmedArray = new byte[length];
System.arraycopy(array, 0, trimmedArray, 0, length);
return trimmedArray;
}
/**
* Concatenates two byte arrays (array1 and array2)
* @param array1
* @param array2
* @return the concatenated array
*/
public static byte[] concat (byte[] array1, byte[] array2) {
byte[] concatArray = new byte[array1.length + array2.length];
System.arraycopy(array1, 0, concatArray, 0, array1.length);
System.arraycopy(array2, 0, concatArray, array1.length, array2.length);
return concatArray;
}
/**
* Concatenates two byte arrays (array1 and array2)
* @param array1
* @param beginIndex1
* @param length1
* @param array2
* @param beginIndex2
* @param length2
* @return the concatenated array
*/
public static byte[] concat (byte[] array1, int beginIndex1, int length1, byte[] array2,
int beginIndex2, int length2) {
byte[] concatArray = new byte[length1 + length2];
System.arraycopy(array1, beginIndex1, concatArray, 0, length1);
System.arraycopy(array2, beginIndex2, concatArray, length1, length2);
return concatArray;
}
/**
* Causes the currently executing thread to sleep (temporarily cease
* execution) for the specified number of milliseconds. The thread
* does not lose ownership of any monitors.
*
* This is the same as Thread.sleep () without throwing InterruptedException
*
* @param millis the length of time to sleep in milliseconds.
*/
public static void sleep (long millis) {
try {
Thread.sleep (millis);
} catch (InterruptedException e) { }
}
/**
* Left unPad with '0'
* @param s - original string
* @return zero unPadded string
*/
public static String zeroUnPad( String s ) {
return unPadLeft(s, '0');
}
/**
* Right unPad with ' '
* @param s - original string
* @return blank unPadded string
*/
public static String blankUnPad( String s ) {
return unPadRight(s, ' ');
}
/**
* Unpad from right. In case the string to be returned
* is empty, the result is c
* @param s - original string
* @param c - padding char
* @return unPadded string.
*/
public static String unPadRight(String s, char c) {
if ( (s.trim().length() == 0) && (c == ' ') )
return (new Character( c )).toString();
else if ( (s.trim().length() == 0) )
return s;
s = s.trim();
int end = s.length();
while ( ( 0 < end) && (s.charAt(end-1) == c) ) end
return ( 0 < end )? s.substring( 0, end ): s.substring( 0, 1 );
}
/**
* Unpad from left. In case the string to be returned
* is empty, the result is c
* @param s - original string
* @param c - padding char
* @return unPadded string.
*/
public static String unPadLeft(String s, char c) {
if ( (s.trim().length() == 0) && (c == ' ') )
return (new Character( c )).toString();
else if ( (s.trim().length() == 0) )
return s;
s = s.trim();
int fill = 0, end = s.length();
while ( (fill < end) && (s.charAt(fill) == c) ) fill ++;
return ( fill < end )? s.substring( fill, end ): s.substring( fill-1, end );
}
/**
* @return true if the string is zero-filled ( 0 char filled )
**/
public static boolean isZero( String s ) {
int i = 0, len = s.length();
while ( i < len && ( s.charAt( i ) == '0' ) ){
i++;
}
return ( i >= len );
}
/**
* @return true if the string is blank filled (space char filled)
*/
public static boolean isBlank( String s ){
return (s.trim().length() == 0);
}
/**
* Return true if the string is alphanum.
* <code>{letter digit (.) (_) (-) ( ) (?) }</code>
*
**/
public static boolean isAlphaNumeric ( String s ) {
int i = 0, len = s.length();
while ( i < len && ( Character.isLetterOrDigit( s.charAt( i ) ) ||
s.charAt( i ) == ' ' || s.charAt( i ) == '.' ||
s.charAt( i ) == '-' || s.charAt( i ) == '_' )
|| s.charAt( i ) == '?' ){
i++;
}
return ( i >= len );
}
/**
* Return true if the string represent a number
* in the specified radix.
* <br><br>
**/
public static boolean isNumeric ( String s, int radix ) {
int i = 0, len = s.length();
while ( i < len && Character.digit( s.charAt( i ), radix ) > -1 ){
i++;
}
return ( i >= len );
}
/**
* Converts a BitSet into an extended binary field
* used in pack routines. The result is always in the
* extended format: (16 bytes of length)
* <br><br>
* @param b the BitSet
* @return binary representation
*/
public static byte[] bitSet2extendedByte ( BitSet b ){
int len = 128;
byte[] d = new byte[len >> 3];
for ( int i=0; i<len; i++ )
if (b.get(i+1))
d[i >> 3] |= (0x80 >> (i % 8));
d[0] |= 0x80;
return d;
}
/**
* Converts a String to an integer of base radix.
* <br><br>
* String constraints are:
* <li>Number must be less than 10 digits</li>
* <li>Number must be positive</li>
* @param s String representation of number
* @param radix Number base to use
* @return integer value of number
* @throws NumberFormatException
*/
public static int parseInt (String s, int radix) throws NumberFormatException {
int length = s.length();
if (length > 9)
throw new NumberFormatException ("Number can have maximum 9 digits");
int result = 0;
int index = 0;
int digit = Character.digit (s.charAt(index++), radix);
if (digit == -1)
throw new NumberFormatException ("String contains non-digit");
result = digit;
while (index < length) {
result *= radix;
digit = Character.digit (s.charAt(index++), radix);
if (digit == -1)
throw new NumberFormatException ("String contains non-digit");
result += digit;
}
return result;
}
/**
* Converts a String to an integer of radix 10.
* <br><br>
* String constraints are:
* <li>Number must be less than 10 digits</li>
* <li>Number must be positive</li>
* @param s String representation of number
* @return integer value of number
* @throws NumberFormatException
*/
public static int parseInt (String s) throws NumberFormatException {
return parseInt (s, 10);
}
/**
* Converts a character array to an integer of base radix.
* <br><br>
* Array constraints are:
* <li>Number must be less than 10 digits</li>
* <li>Number must be positive</li>
* @param cArray Character Array representation of number
* @param radix Number base to use
* @return integer value of number
* @throws NumberFormatException
*/
public static int parseInt (char[] cArray, int radix) throws NumberFormatException {
int length = cArray.length;
if (length > 9)
throw new NumberFormatException ("Number can have maximum 9 digits");
int result = 0;
int index = 0;
int digit = Character.digit(cArray[index++], radix);
if (digit == -1)
throw new NumberFormatException ("Char array contains non-digit");
result = digit;
while (index < length) {
result *= radix;
digit = Character.digit(cArray[index++],radix);
if (digit == -1)
throw new NumberFormatException ("Char array contains non-digit");
result += digit;
}
return result;
}
/**
* Converts a character array to an integer of radix 10.
* <br><br>
* Array constraints are:
* <li>Number must be less than 10 digits</li>
* <li>Number must be positive</li>
* @param cArray Character Array representation of number
* @return integer value of number
* @throws NumberFormatException
*/
public static int parseInt (char[] cArray) throws NumberFormatException {
return parseInt (cArray,10);
}
/**
* Converts a byte array to an integer of base radix.
* <br><br>
* Array constraints are:
* <li>Number must be less than 10 digits</li>
* <li>Number must be positive</li>
* @param bArray Byte Array representation of number
* @param radix Number base to use
* @return integer value of number
* @throws NumberFormatException
*/
public static int parseInt (byte[] bArray, int radix) throws NumberFormatException {
int length = bArray.length;
if (length > 9)
throw new NumberFormatException ("Number can have maximum 9 digits");
int result = 0;
int index = 0;
int digit = Character.digit((char)bArray[index++], radix);
if (digit == -1)
throw new NumberFormatException ("Byte array contains non-digit");
result = digit;
while (index < length) {
result *= radix;
digit = Character.digit((char)bArray[index++],radix);
if (digit == -1)
throw new NumberFormatException ("Byte array contains non-digit");
result += digit;
}
return result;
}
/**
* Converts a byte array to an integer of radix 10.
* <br><br>
* Array constraints are:
* <li>Number must be less than 10 digits</li>
* <li>Number must be positive</li>
* @param bArray Byte Array representation of number
* @return integer value of number
* @throws NumberFormatException
*/
public static int parseInt (byte[] bArray) throws NumberFormatException {
return parseInt (bArray,10);
}
private static String hexOffset (int i) {
i = (i>>4) << 4;
int w = i > 0xFFFF ? 8 : 4;
try {
return zeropad (Integer.toString (i, 16), w);
} catch (ISOException e) {
// should not happen
return e.getMessage();
}
}
/**
* @param b a byte[] buffer
* @return hexdump
*/
public static String hexdump (byte[] b) {
return hexdump (b, 0, b.length);
}
/**
* @param b a byte[] buffer
* @param offset starting offset
* @param len the Length
* @return hexdump
*/
public static String hexdump (byte[] b, int offset, int len) {
StringBuffer sb = new StringBuffer ();
StringBuffer hex = new StringBuffer ();
StringBuffer ascii = new StringBuffer ();
String sep = " ";
String lineSep = System.getProperty ("line.separator");
for (int i=offset; i<len; i++) {
char hi = Character.forDigit ((b[i] >> 4) & 0x0F, 16);
char lo = Character.forDigit (b[i] & 0x0F, 16);
hex.append (Character.toUpperCase(hi));
hex.append (Character.toUpperCase(lo));
hex.append (' ');
char c = (char) b[i];
ascii.append ((c >= 32 && c < 127) ? c : '.');
int j = i % 16;
switch (j) {
case 7 :
hex.append (' ');
break;
case 15 :
sb.append (hexOffset (i));
sb.append (sep);
sb.append (hex.toString());
sb.append (' ');
sb.append (ascii.toString());
sb.append (lineSep);
hex = new StringBuffer ();
ascii = new StringBuffer ();
break;
}
}
if (hex.length() > 0) {
while (hex.length () < 49)
hex.append (' ');
sb.append (hexOffset (len));
sb.append (sep);
sb.append (hex.toString());
sb.append (' ');
sb.append (ascii.toString());
sb.append (lineSep);
}
return sb.toString();
}
/**
* pads a string with 'F's (useful for pinoffset management)
* @param s an [hex]string
* @param len desired length
* @return string right padded with 'F's
*/
public static String strpadf (String s, int len) {
StringBuffer d = new StringBuffer(s);
while (d.length() < len)
d.append('F');
return d.toString();
}
/**
* reverse the effect of strpadf
* @param s F padded string
* @return trimmed string
*/
public static String trimf (String s) {
if (s != null) {
int l = s.length();
if (l > 0) {
while (--l >= 0) {
if (s.charAt (l) != 'F')
break;
}
s = l == 0 ? "" : s.substring (0, l+1);
}
}
return s;
}
}
|
package org.jpos.iso;
import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.BitSet;
import java.util.StringTokenizer;
/**
* varios functions needed to pack/unpack ISO-8583 fields
*
* @author apr@cs.com.uy
* @author Hani S. Kirollos
* @author Alwyn Schoeman
* @version $Id$
* @see ISOComponent
*/
public class ISOUtil {
public static final byte[] EBCDIC2ASCII = new byte[] {
(byte)0x0, (byte)0x1, (byte)0x2, (byte)0x3,
(byte)0x9C, (byte)0x9, (byte)0x86, (byte)0x7F,
(byte)0x97, (byte)0x8D, (byte)0x8E, (byte)0xB,
(byte)0xC, (byte)0xD, (byte)0xE, (byte)0xF,
(byte)0x10, (byte)0x11, (byte)0x12, (byte)0x13,
(byte)0x9D, (byte)0xA, (byte)0x8, (byte)0x87,
(byte)0x18, (byte)0x19, (byte)0x92, (byte)0x8F,
(byte)0x1C, (byte)0x1D, (byte)0x1E, (byte)0x1F,
(byte)0x80, (byte)0x81, (byte)0x82, (byte)0x83,
(byte)0x84, (byte)0x85, (byte)0x17, (byte)0x1B,
(byte)0x88, (byte)0x89, (byte)0x8A, (byte)0x8B,
(byte)0x8C, (byte)0x5, (byte)0x6, (byte)0x7,
(byte)0x90, (byte)0x91, (byte)0x16, (byte)0x93,
(byte)0x94, (byte)0x95, (byte)0x96, (byte)0x4,
(byte)0x98, (byte)0x99, (byte)0x9A, (byte)0x9B,
(byte)0x14, (byte)0x15, (byte)0x9E, (byte)0x1A,
(byte)0x20, (byte)0xA0, (byte)0xE2, (byte)0xE4,
(byte)0xE0, (byte)0xE1, (byte)0xE3, (byte)0xE5,
(byte)0xE7, (byte)0xF1, (byte)0xA2, (byte)0x2E,
(byte)0x3C, (byte)0x28, (byte)0x2B, (byte)0x7C,
(byte)0x26, (byte)0xE9, (byte)0xEA, (byte)0xEB,
(byte)0xE8, (byte)0xED, (byte)0xEE, (byte)0xEF,
(byte)0xEC, (byte)0xDF, (byte)0x21, (byte)0x24,
(byte)0x2A, (byte)0x29, (byte)0x3B, (byte)0x5E,
(byte)0x2D, (byte)0x2F, (byte)0xC2, (byte)0xC4,
(byte)0xC0, (byte)0xC1, (byte)0xC3, (byte)0xC5,
(byte)0xC7, (byte)0xD1, (byte)0xA6, (byte)0x2C,
(byte)0x25, (byte)0x5F, (byte)0x3E, (byte)0x3F,
(byte)0xF8, (byte)0xC9, (byte)0xCA, (byte)0xCB,
(byte)0xC8, (byte)0xCD, (byte)0xCE, (byte)0xCF,
(byte)0xCC, (byte)0x60, (byte)0x3A, (byte)0x23,
(byte)0x40, (byte)0x27, (byte)0x3D, (byte)0x22,
(byte)0xD8, (byte)0x61, (byte)0x62, (byte)0x63,
(byte)0x64, (byte)0x65, (byte)0x66, (byte)0x67,
(byte)0x68, (byte)0x69, (byte)0xAB, (byte)0xBB,
(byte)0xF0, (byte)0xFD, (byte)0xFE, (byte)0xB1,
(byte)0xB0, (byte)0x6A, (byte)0x6B, (byte)0x6C,
(byte)0x6D, (byte)0x6E, (byte)0x6F, (byte)0x70,
(byte)0x71, (byte)0x72, (byte)0xAA, (byte)0xBA,
(byte)0xE6, (byte)0xB8, (byte)0xC6, (byte)0xA4,
(byte)0xB5, (byte)0x7E, (byte)0x73, (byte)0x74,
(byte)0x75, (byte)0x76, (byte)0x77, (byte)0x78,
(byte)0x79, (byte)0x7A, (byte)0xA1, (byte)0xBF,
(byte)0xD0, (byte)0x5B, (byte)0xDE, (byte)0xAE,
(byte)0xAC, (byte)0xA3, (byte)0xA5, (byte)0xB7,
(byte)0xA9, (byte)0xA7, (byte)0xB6, (byte)0xBC,
(byte)0xBD, (byte)0xBE, (byte)0xDD, (byte)0xA8,
(byte)0xAF, (byte)0x5D, (byte)0xB4, (byte)0xD7,
(byte)0x7B, (byte)0x41, (byte)0x42, (byte)0x43,
(byte)0x44, (byte)0x45, (byte)0x46, (byte)0x47,
(byte)0x48, (byte)0x49, (byte)0xAD, (byte)0xF4,
(byte)0xF6, (byte)0xF2, (byte)0xF3, (byte)0xF5,
(byte)0x7D, (byte)0x4A, (byte)0x4B, (byte)0x4C,
(byte)0x4D, (byte)0x4E, (byte)0x4F, (byte)0x50,
(byte)0x51, (byte)0x52, (byte)0xB9, (byte)0xFB,
(byte)0xFC, (byte)0xF9, (byte)0xFA, (byte)0xFF,
(byte)0x5C, (byte)0xF7, (byte)0x53, (byte)0x54,
(byte)0x55, (byte)0x56, (byte)0x57, (byte)0x58,
(byte)0x59, (byte)0x5A, (byte)0xB2, (byte)0xD4,
(byte)0xD6, (byte)0xD2, (byte)0xD3, (byte)0xD5,
(byte)0x30, (byte)0x31, (byte)0x32, (byte)0x33,
(byte)0x34, (byte)0x35, (byte)0x36, (byte)0x37,
(byte)0x38, (byte)0x39, (byte)0xB3, (byte)0xDB,
(byte)0xDC, (byte)0xD9, (byte)0xDA, (byte)0x9F
};
public static final byte[] ASCII2EBCDIC = new byte[] {
(byte)0x0, (byte)0x1, (byte)0x2, (byte)0x3,
(byte)0x37, (byte)0x2D, (byte)0x2E, (byte)0x2F,
(byte)0x16, (byte)0x5, (byte)0x15, (byte)0xB,
(byte)0xC, (byte)0xD, (byte)0xE, (byte)0xF,
(byte)0x10, (byte)0x11, (byte)0x12, (byte)0x13,
(byte)0x3C, (byte)0x3D, (byte)0x32, (byte)0x26,
(byte)0x18, (byte)0x19, (byte)0x3F, (byte)0x27,
(byte)0x1C, (byte)0x1D, (byte)0x1E, (byte)0x1F,
(byte)0x40, (byte)0x5A, (byte)0x7F, (byte)0x7B,
(byte)0x5B, (byte)0x6C, (byte)0x50, (byte)0x7D,
(byte)0x4D, (byte)0x5D, (byte)0x5C, (byte)0x4E,
(byte)0x6B, (byte)0x60, (byte)0x4B, (byte)0x61,
(byte)0xF0, (byte)0xF1, (byte)0xF2, (byte)0xF3,
(byte)0xF4, (byte)0xF5, (byte)0xF6, (byte)0xF7,
(byte)0xF8, (byte)0xF9, (byte)0x7A, (byte)0x5E,
(byte)0x4C, (byte)0x7E, (byte)0x6E, (byte)0x6F,
(byte)0x7C, (byte)0xC1, (byte)0xC2, (byte)0xC3,
(byte)0xC4, (byte)0xC5, (byte)0xC6, (byte)0xC7,
(byte)0xC8, (byte)0xC9, (byte)0xD1, (byte)0xD2,
(byte)0xD3, (byte)0xD4, (byte)0xD5, (byte)0xD6,
(byte)0xD7, (byte)0xD8, (byte)0xD9, (byte)0xE2,
(byte)0xE3, (byte)0xE4, (byte)0xE5, (byte)0xE6,
(byte)0xE7, (byte)0xE8, (byte)0xE9, (byte)0xAD,
(byte)0xE0, (byte)0xBD, (byte)0x5F, (byte)0x6D,
(byte)0x79, (byte)0x81, (byte)0x82, (byte)0x83,
(byte)0x84, (byte)0x85, (byte)0x86, (byte)0x87,
(byte)0x88, (byte)0x89, (byte)0x91, (byte)0x92,
(byte)0x93, (byte)0x94, (byte)0x95, (byte)0x96,
(byte)0x97, (byte)0x98, (byte)0x99, (byte)0xA2,
(byte)0xA3, (byte)0xA4, (byte)0xA5, (byte)0xA6,
(byte)0xA7, (byte)0xA8, (byte)0xA9, (byte)0xC0,
(byte)0x4F, (byte)0xD0, (byte)0xA1, (byte)0x7,
(byte)0x20, (byte)0x21, (byte)0x22, (byte)0x23,
(byte)0x24, (byte)0x25, (byte)0x6, (byte)0x17,
(byte)0x28, (byte)0x29, (byte)0x2A, (byte)0x2B,
(byte)0x2C, (byte)0x9, (byte)0xA, (byte)0x1B,
(byte)0x30, (byte)0x31, (byte)0x1A, (byte)0x33,
(byte)0x34, (byte)0x35, (byte)0x36, (byte)0x8,
(byte)0x38, (byte)0x39, (byte)0x3A, (byte)0x3B,
(byte)0x4, (byte)0x14, (byte)0x3E, (byte)0xFF,
(byte)0x41, (byte)0xAA, (byte)0x4A, (byte)0xB1,
(byte)0x9F, (byte)0xB2, (byte)0x6A, (byte)0xB5,
(byte)0xBB, (byte)0xB4, (byte)0x9A, (byte)0x8A,
(byte)0xB0, (byte)0xCA, (byte)0xAF, (byte)0xBC,
(byte)0x90, (byte)0x8F, (byte)0xEA, (byte)0xFA,
(byte)0xBE, (byte)0xA0, (byte)0xB6, (byte)0xB3,
(byte)0x9D, (byte)0xDA, (byte)0x9B, (byte)0x8B,
(byte)0xB7, (byte)0xB8, (byte)0xB9, (byte)0xAB,
(byte)0x64, (byte)0x65, (byte)0x62, (byte)0x66,
(byte)0x63, (byte)0x67, (byte)0x9E, (byte)0x68,
(byte)0x74, (byte)0x71, (byte)0x72, (byte)0x73,
(byte)0x78, (byte)0x75, (byte)0x76, (byte)0x77,
(byte)0xAC, (byte)0x69, (byte)0xED, (byte)0xEE,
(byte)0xEB, (byte)0xEF, (byte)0xEC, (byte)0xBF,
(byte)0x80, (byte)0xFD, (byte)0xFE, (byte)0xFB,
(byte)0xFC, (byte)0xBA, (byte)0xAE, (byte)0x59,
(byte)0x44, (byte)0x45, (byte)0x42, (byte)0x46,
(byte)0x43, (byte)0x47, (byte)0x9C, (byte)0x48,
(byte)0x54, (byte)0x51, (byte)0x52, (byte)0x53,
(byte)0x58, (byte)0x55, (byte)0x56, (byte)0x57,
(byte)0x8C, (byte)0x49, (byte)0xCD, (byte)0xCE,
(byte)0xCB, (byte)0xCF, (byte)0xCC, (byte)0xE1,
(byte)0x70, (byte)0xDD, (byte)0xDE, (byte)0xDB,
(byte)0xDC, (byte)0x8D, (byte)0x8E, (byte)0xDF
};
public static final byte STX = 0x02;
public static final byte FS = 0x1C;
public static final byte US = 0x1F;
public static final byte RS = 0x1D;
public static final byte GS = 0x1E;
public static final byte ETX = 0x03;
public static String ebcdicToAscii(byte[] e) {
try {
return new String (
ebcdicToAsciiBytes (e, 0, e.length), "ISO8859_1"
);
} catch (UnsupportedEncodingException ex) {
return ex.toString(); // should never happen
}
}
public static String ebcdicToAscii(byte[] e, int offset, int len) {
try {
return new String (
ebcdicToAsciiBytes (e, offset, len), "ISO8859_1"
);
} catch (UnsupportedEncodingException ex) {
return ex.toString(); // should never happen
}
}
public static byte[] ebcdicToAsciiBytes (byte[] e) {
return ebcdicToAsciiBytes (e, 0, e.length);
}
public static byte[] ebcdicToAsciiBytes(byte[] e, int offset, int len) {
byte[] a = new byte[len];
for (int i=0; i<len; i++)
a[i] = EBCDIC2ASCII[e[offset+i]&0xFF];
return a;
}
public static byte[] asciiToEbcdic(String s) {
return asciiToEbcdic (s.getBytes());
}
public static byte[] asciiToEbcdic(byte[] a) {
byte[] e = new byte[a.length];
for (int i=0; i<a.length; i++)
e[i] = ASCII2EBCDIC[a[i]&0xFF];
return e;
}
public static void asciiToEbcdic(String s, byte[] e, int offset) {
int len = s.length();
for (int i=0; i<len; i++)
e[offset + i] = ASCII2EBCDIC[s.charAt(i)&0xFF];
}
/**
* pad to the left
* @param s - original string
* @param len - desired len
* @param c - padding char
* @return padded string
*/
public static String padleft(String s, int len, char c)
throws ISOException
{
s = s.trim();
if (s.length() > len)
throw new ISOException("invalid len " +s.length() + "/" +len);
StringBuffer d = new StringBuffer (len);
int fill = len - s.length();
while (fill
d.append (c);
d.append(s);
return d.toString();
}
/**
* pad to the right
*
* @param s -
* original string
* @param len -
* desired len
* @param c -
* padding char
* @return padded string
*/
public static String padright(String s, int len, char c) throws ISOException {
s = s.trim();
if (s.length() > len)
throw new ISOException("invalid len " + s.length() + "/" + len);
StringBuffer d = new StringBuffer(len);
int fill = len - s.length();
d.append(s);
while (fill
d.append(c);
return d.toString();
}
/**
* trim String (if not null)
* @param s String to trim
* @return String (may be null)
*/
public static String trim (String s) {
return s != null ? s.trim() : null;
}
/**
* left pad with '0'
* @param s - original string
* @param len - desired len
* @return zero padded string
*/
public static String zeropad(String s, int len) throws ISOException {
return padleft(s, len, '0');
}
/**
* pads to the right
* @param s - original string
* @param len - desired len
* @return space padded string
*/
public static String strpad(String s, int len) {
StringBuffer d = new StringBuffer(s);
while (d.length() < len)
d.append(' ');
return d.toString();
}
public static String zeropadRight (String s, int len) {
StringBuffer d = new StringBuffer(s);
while (d.length() < len)
d.append('0');
return d.toString();
}
/**
* converts to BCD
* @param s - the number
* @param padLeft - flag indicating left/right padding
* @param d The byte array to copy into.
* @param offset Where to start copying into.
* @return BCD representation of the number
*/
public static byte[] str2bcd(String s, boolean padLeft, byte[] d, int offset) {
int len = s.length();
int start = (((len & 1) == 1) && padLeft) ? 1 : 0;
for (int i=start; i < len+start; i++)
d [offset + (i >> 1)] |= (s.charAt(i-start)-'0') << ((i & 1) == 1 ? 0 : 4);
return d;
}
/**
* converts to BCD
* @param s - the number
* @param padLeft - flag indicating left/right padding
* @return BCD representation of the number
*/
public static byte[] str2bcd(String s, boolean padLeft) {
int len = s.length();
byte[] d = new byte[ (len+1) >> 1 ];
return str2bcd(s, padLeft, d, 0);
}
/**
* converts to BCD
* @param s - the number
* @param padLeft - flag indicating left/right padding
* @param fill - fill value
* @return BCD representation of the number
*/
public static byte[] str2bcd(String s, boolean padLeft, byte fill) {
int len = s.length();
byte[] d = new byte[ (len+1) >> 1 ];
Arrays.fill (d, fill);
int start = (((len & 1) == 1) && padLeft) ? 1 : 0;
for (int i=start; i < len+start; i++)
d [i >> 1] |= (s.charAt(i-start)-'0') << ((i & 1) == 1 ? 0 : 4);
return d;
}
/**
* converts a BCD representation of a number to a String
* @param b - BCD representation
* @param offset - starting offset
* @param len - BCD field len
* @param padLeft - was padLeft packed?
* @return the String representation of the number
*/
public static String bcd2str(byte[] b, int offset,
int len, boolean padLeft)
{
StringBuffer d = new StringBuffer(len);
int start = (((len & 1) == 1) && padLeft) ? 1 : 0;
for (int i=start; i < len+start; i++) {
int shift = ((i & 1) == 1 ? 0 : 4);
char c = Character.forDigit (
((b[offset+(i>>1)] >> shift) & 0x0F), 16);
if (c == 'd')
c = '=';
d.append (Character.toUpperCase (c));
}
return d.toString();
}
/**
* converts a byte array to hex string
* (suitable for dumps and ASCII packaging of Binary fields
* @param b - byte array
* @return String representation
*/
public static String hexString(byte[] b) {
StringBuffer d = new StringBuffer(b.length * 2);
for (int i=0; i<b.length; i++) {
char hi = Character.forDigit ((b[i] >> 4) & 0x0F, 16);
char lo = Character.forDigit (b[i] & 0x0F, 16);
d.append(Character.toUpperCase(hi));
d.append(Character.toUpperCase(lo));
}
return d.toString();
}
/**
* converts a byte array to printable characters
* @param b - byte array
* @return String representation
*/
public static String dumpString(byte[] b) {
StringBuffer d = new StringBuffer(b.length * 2);
for (int i=0; i<b.length; i++) {
char c = (char) b[i];
if (Character.isISOControl (c)) {
// TODO: complete list of control characters,
// use a String[] instead of this weird switch
switch (c) {
case '\r' : d.append ("{CR}"); break;
case '\n' : d.append ("{LF}"); break;
case '\000': d.append ("{NULL}"); break;
case '\001': d.append ("{SOH}"); break;
case '\002': d.append ("{STX}"); break;
case '\003': d.append ("{ETX}"); break;
case '\004': d.append ("{EOT}"); break;
case '\005': d.append ("{ENQ}"); break;
case '\006': d.append ("{ACK}"); break;
case '\007': d.append ("{BEL}"); break;
case '\020': d.append ("{DLE}"); break;
case '\025': d.append ("{NAK}"); break;
case '\026': d.append ("{SYN}"); break;
case '\034': d.append ("{FS}"); break;
case '\036': d.append ("{RS}"); break;
default:
char hi = Character.forDigit ((b[i] >> 4) & 0x0F, 16);
char lo = Character.forDigit (b[i] & 0x0F, 16);
d.append('[');
d.append(Character.toUpperCase(hi));
d.append(Character.toUpperCase(lo));
d.append(']');
break;
}
}
else
d.append (c);
}
return d.toString();
}
/**
* converts a byte array to hex string
* (suitable for dumps and ASCII packaging of Binary fields
* @param b - byte array
* @param offset - starting position
* @param len
* @return String representation
*/
public static String hexString(byte[] b, int offset, int len) {
StringBuffer d = new StringBuffer(len * 2);
len += offset;
for (int i=offset; i<len; i++) {
char hi = Character.forDigit ((b[i] >> 4) & 0x0F, 16);
char lo = Character.forDigit (b[i] & 0x0F, 16);
d.append(Character.toUpperCase(hi));
d.append(Character.toUpperCase(lo));
}
return d.toString();
}
/**
* bit representation of a BitSet
* suitable for dumps and debugging
* @param b - the BitSet
* @return string representing the bits (i.e. 011010010...)
*/
public static String bitSet2String (BitSet b) {
int len = b.size();
len = (len > 128) ? 128: len;
StringBuffer d = new StringBuffer(len);
for (int i=0; i<len; i++)
d.append (b.get(i) ? '1' : '0');
return d.toString();
}
/**
* converts a BitSet into a binary field
* used in pack routines
* @param b - the BitSet
* @return binary representation
*/
public static byte[] bitSet2byte (BitSet b)
{
int len = (((b.length()+62)>>6)<<6);
byte[] d = new byte[len >> 3];
for (int i=0; i<len; i++)
if (b.get(i+1))
d[i >> 3] |= (0x80 >> (i % 8));
if (len>64)
d[0] |= 0x80;
if (len>128)
d[8] |= 0x80;
return d;
}
/**
* converts a BitSet into a binary field
* used in pack routines
* @param b - the BitSet
* @param bytes - number of bytes to return
* @return binary representation
*/
public static byte[] bitSet2byte (BitSet b, int bytes)
{
int len = bytes * 8;
byte[] d = new byte[bytes];
for (int i=0; i<len; i++)
if (b.get(i+1))
d[i >> 3] |= (0x80 >> (i % 8));
//TODO: review why 2nd & 3rd bit map flags are set here???
if (len>64)
d[0] |= 0x80;
if (len>128)
d[8] |= 0x80;
return d;
}
/*
* Convert BitSet to int value.
*/
public static int bitSet2Int(BitSet bs) {
int total = 0;
int b = bs.length() - 1;
if (b > 0) {
int value = (int) Math.pow(2,b);
for (int i = 0; i <= b; i++) {
if (bs.get(i))
total += value;
value = value >> 1;
}
}
return total;
}
/*
* Convert int value to BitSet.
*/
public static BitSet int2BitSet(int value) {
return int2BitSet(value,0);
}
/*
* Convert int value to BitSet.
*/
public static BitSet int2BitSet(int value, int offset) {
BitSet bs = new BitSet();
String hex = Integer.toHexString(value);
hex2BitSet(bs, hex.getBytes(), offset);
return bs;
}
/**
* Converts a binary representation of a Bitmap field
* into a Java BitSet
* @param b - binary representation
* @param offset - staring offset
* @param bitZeroMeansExtended - true for ISO-8583
* @return java BitSet object
*/
public static BitSet byte2BitSet
(byte[] b, int offset, boolean bitZeroMeansExtended)
{
int len = bitZeroMeansExtended ?
((b[offset] & 0x80) == 0x80 ? 128 : 64) : 64;
BitSet bmap = new BitSet (len);
for (int i=0; i<len; i++)
if (((b[offset + (i >> 3)]) & (0x80 >> (i % 8))) > 0)
bmap.set(i+1);
return bmap;
}
/**
* Converts a binary representation of a Bitmap field
* into a Java BitSet
* @param b - binary representation
* @param offset - staring offset
* @param maxBits - max number of bits (supports 64,128 or 192)
* @return java BitSet object
*/
public static BitSet byte2BitSet (byte[] b, int offset, int maxBits) {
int len = maxBits > 64 ?
((b[offset] & 0x80) == 0x80 ? 128 : 64) : maxBits;
if (maxBits > 128 &&
b.length > offset+8 &&
(b[offset+8] & 0x80) == 0x80)
{
len = 192;
}
BitSet bmap = new BitSet (len);
for (int i=0; i<len; i++)
if (((b[offset + (i >> 3)]) & (0x80 >> (i % 8))) > 0)
bmap.set(i+1);
return bmap;
}
/**
* Converts a binary representation of a Bitmap field
* into a Java BitSet
* @param bmap - BitSet
* @param b - hex representation
* @param bitOffset - (i.e. 0 for primary bitmap, 64 for secondary)
* @return java BitSet object
*/
public static BitSet byte2BitSet (BitSet bmap, byte[] b, int bitOffset)
{
int len = b.length << 3;
for (int i=0; i<len; i++)
if (((b[i >> 3]) & (0x80 >> (i % 8))) > 0)
bmap.set(bitOffset + i + 1);
return bmap;
}
/**
* Converts an ASCII representation of a Bitmap field
* into a Java BitSet
* @param b - hex representation
* @param offset - starting offset
* @param bitZeroMeansExtended - true for ISO-8583
* @return java BitSet object
*/
public static BitSet hex2BitSet
(byte[] b, int offset, boolean bitZeroMeansExtended)
{
int len = bitZeroMeansExtended ?
((Character.digit((char)b[offset],16) & 0x08) == 8 ? 128 : 64) :
64;
BitSet bmap = new BitSet (len);
for (int i=0; i<len; i++) {
int digit = Character.digit((char)b[offset + (i >> 2)], 16);
if ((digit & (0x08 >> (i%4))) > 0)
bmap.set(i+1);
}
return bmap;
}
/**
* Converts an ASCII representation of a Bitmap field
* into a Java BitSet
* @param b - hex representation
* @param offset - starting offset
* @param maxBits - max number of bits (supports 8, 16, 24, 32, 48, 52, 64,.. 128 or 192)
* @return java BitSet object
*/
public static BitSet hex2BitSet (byte[] b, int offset, int maxBits) {
int len = maxBits > 64?
((Character.digit((char)b[offset],16) & 0x08) == 8 ? 128 : 64) :
maxBits;
BitSet bmap = new BitSet (len);
for (int i=0; i<len; i++) {
int digit = Character.digit((char)b[offset + (i >> 2)], 16);
if ((digit & (0x08 >> (i%4))) > 0) {
bmap.set(i+1);
if (i==65 && maxBits > 128)
len = 192;
}
}
return bmap;
}
/**
* Converts an ASCII representation of a Bitmap field
* into a Java BitSet
* @param bmap - BitSet
* @param b - hex representation
* @param bitOffset - (i.e. 0 for primary bitmap, 64 for secondary)
* @return java BitSet object
*/
public static BitSet hex2BitSet (BitSet bmap, byte[] b, int bitOffset)
{
int len = b.length << 2;
for (int i=0; i<len; i++) {
int digit = Character.digit((char)b[i >> 2], 16);
if ((digit & (0x08 >> (i%4))) > 0)
bmap.set (bitOffset + i + 1);
}
return bmap;
}
/**
* @param b source byte array
* @param offset starting offset
* @param len number of bytes in destination (processes len*2)
* @return byte[len]
*/
public static byte[] hex2byte (byte[] b, int offset, int len) {
byte[] d = new byte[len];
for (int i=0; i<len*2; i++) {
int shift = i%2 == 1 ? 0 : 4;
d[i>>1] |= Character.digit((char) b[offset+i], 16) << shift;
}
return d;
}
/**
* @param s source string (with Hex representation)
* @return byte array
*/
public static byte[] hex2byte (String s) {
if (s.length() % 2 == 0) {
return hex2byte (s.getBytes(), 0, s.length() >> 1);
} else {
// Padding left zero to make it even size #Bug raised by tommy
return hex2byte("0"+s);
}
}
/**
* format double value
* @param d the amount
* @param len the field len
* @return a String of fieldLen characters (right justified)
*/
public static String formatDouble(double d, int len) {
String prefix = Long.toString((long) d);
String suffix = Integer.toString (
(int) ((Math.round(d * 100f)) % 100) );
try {
if (len > 3)
prefix = ISOUtil.padleft(prefix,len-3,' ');
suffix = ISOUtil.zeropad(suffix, 2);
} catch (ISOException e) {
// should not happen
}
return prefix + "." + suffix;
}
/**
* prepare long value used as amount for display
* (implicit 2 decimals)
* @param l value
* @param len display len
* @return formated field
* @exception ISOException
*/
public static String formatAmount(long l, int len) throws ISOException {
String buf = Long.toString(l);
if (l < 100)
buf = zeropad(buf, 3);
StringBuffer s = new StringBuffer(padleft (buf, len-1, ' ') );
s.insert(len-3, '.');
return s.toString();
}
/**
* XML normalizer
* @param s source String
* @param canonical true if we want to normalize \r and \n as well
* @return normalized string suitable for XML Output
*/
public static String normalize (String s, boolean canonical) {
StringBuffer str = new StringBuffer();
int len = (s != null) ? s.length() : 0;
for (int i = 0; i < len; i++) {
char ch = s.charAt(i);
switch (ch) {
case '<':
str.append("<");
break;
case '>':
str.append(">");
break;
case '&':
str.append("&");
break;
case '"':
str.append(""");
break;
case '\r':
case '\n':
if (canonical) {
str.append("&
str.append(Integer.toString((int) (ch & 0xFF)));
str.append(';');
break;
}
// else, default append char
default:
if (ch < 0x20) {
str.append("&
str.append(Integer.toString((int) (ch & 0xFF)));
str.append(';');
}
else if (ch > 0xff00) {
str.append((char) (ch & 0xFF));
} else
str.append(ch);
}
}
return (str.toString());
}
/**
* XML normalizer (default canonical)
* @param s source String
* @return normalized string suitable for XML Output
*/
public static String normalize (String s) {
return normalize (s, true);
}
public static String protect (String s) {
StringBuffer sb = new StringBuffer();
int len = s.length();
int clear = len > 6 ? 6 : 0;
int lastFourIndex = -1;
if (clear > 0) {
lastFourIndex = s.indexOf ('=') - 4;
if (lastFourIndex < 0) {
lastFourIndex = s.indexOf ('^') - 4;
if (lastFourIndex < 0)
lastFourIndex = len - 4;
}
}
for (int i=0; i<len; i++) {
if (s.charAt(i) == '=')
clear = 1; // use clear=5 to keep the expiration date
else if (s.charAt(i) == '^') {
lastFourIndex = 0;
clear = len - i;
}
else if (i == lastFourIndex)
clear = 4;
sb.append (clear-- > 0 ? s.charAt(i) : '_');
}
s = sb.toString();
try {
//Addresses Track1 Truncation
int charCount = s.replaceAll("[^\\^]", "").length();
if (charCount == 2 ) {
s = s.substring(0, s.lastIndexOf("^")+1);
s = ISOUtil.padright(s, len, '_');
}
} catch (ISOException e){
//cannot PAD - should never get here
}
return s;
}
}
public static int[] toIntArray(String s) {
StringTokenizer st = new StringTokenizer (s);
int[] array = new int [st.countTokens()];
for (int i=0; st.hasMoreTokens(); i++)
array[i] = Integer.parseInt (st.nextToken());
return array;
}
public static String[] toStringArray(String s) {
StringTokenizer st = new StringTokenizer (s);
String[] array = new String [st.countTokens()];
for (int i=0; st.hasMoreTokens(); i++)
array[i] = st.nextToken();
return array;
}
/**
* Bitwise XOR between corresponding bytes
* @param op1 byteArray1
* @param op2 byteArray2
* @return an array of length = the smallest between op1 and op2
*/
public static byte[] xor (byte[] op1, byte[] op2) {
byte[] result = null;
// Use the smallest array
if (op2.length > op1.length) {
result = new byte[op1.length];
}
else {
result = new byte[op2.length];
}
for (int i = 0; i < result.length; i++) {
result[i] = (byte)(op1[i] ^ op2[i]);
}
return result;
}
/**
* Bitwise XOR between corresponding byte arrays represented in hex
* @param op1 hexstring 1
* @param op2 hexstring 2
* @return an array of length = the smallest between op1 and op2
*/
public static String hexor (String op1, String op2) {
byte[] xor = xor (hex2byte (op1), hex2byte (op2));
return hexString (xor);
}
/**
* Trims a byte[] to a certain length
* @param array the byte[] to be trimmed
* @param length the wanted length
* @return the trimmed byte[]
*/
public static byte[] trim (byte[] array, int length) {
byte[] trimmedArray = new byte[length];
System.arraycopy(array, 0, trimmedArray, 0, length);
return trimmedArray;
}
/**
* Concatenates two byte arrays (array1 and array2)
* @param array1
* @param array2
* @return the concatenated array
*/
public static byte[] concat (byte[] array1, byte[] array2) {
byte[] concatArray = new byte[array1.length + array2.length];
System.arraycopy(array1, 0, concatArray, 0, array1.length);
System.arraycopy(array2, 0, concatArray, array1.length, array2.length);
return concatArray;
}
/**
* Concatenates two byte arrays (array1 and array2)
* @param array1
* @param beginIndex1
* @param length1
* @param array2
* @param beginIndex2
* @param length2
* @return the concatenated array
*/
public static byte[] concat (byte[] array1, int beginIndex1, int length1, byte[] array2,
int beginIndex2, int length2) {
byte[] concatArray = new byte[length1 + length2];
System.arraycopy(array1, beginIndex1, concatArray, 0, length1);
System.arraycopy(array2, beginIndex2, concatArray, length1, length2);
return concatArray;
}
/**
* Causes the currently executing thread to sleep (temporarily cease
* execution) for the specified number of milliseconds. The thread
* does not lose ownership of any monitors.
*
* This is the same as Thread.sleep () without throwing InterruptedException
*
* @param millis the length of time to sleep in milliseconds.
*/
public static void sleep (long millis) {
try {
Thread.sleep (millis);
} catch (InterruptedException e) { }
}
/**
* Left unPad with '0'
* @param s - original string
* @return zero unPadded string
*/
public static String zeroUnPad( String s ) {
return unPadLeft(s, '0');
}
/**
* Right unPad with ' '
* @param s - original string
* @return blank unPadded string
*/
public static String blankUnPad( String s ) {
return unPadRight(s, ' ');
}
/**
* Unpad from right.
* @param s - original string
* @param c - padding char
* @return unPadded string.
*/
public static String unPadRight(String s, char c) {
int end = s.length();
if (end == 0)
return s;
while ( ( 0 < end) && (s.charAt(end-1) == c) ) end
return ( 0 < end )? s.substring( 0, end ): s.substring( 0, 1 );
}
/**
* Unpad from left.
* @param s - original string
* @param c - padding char
* @return unPadded string.
*/
public static String unPadLeft(String s, char c) {
int fill = 0, end = s.length();
if (end == 0)
return s;
while ( (fill < end) && (s.charAt(fill) == c) ) fill ++;
return ( fill < end )? s.substring( fill, end ): s.substring( fill-1, end );
}
/**
* @return true if the string is zero-filled ( 0 char filled )
**/
public static boolean isZero( String s ) {
int i = 0, len = s.length();
while ( i < len && ( s.charAt( i ) == '0' ) ){
i++;
}
return ( i >= len );
}
/**
* @return true if the string is blank filled (space char filled)
*/
public static boolean isBlank( String s ){
return (s.trim().length() == 0);
}
/**
* Return true if the string is alphanum.
* <code>{letter digit (.) (_) (-) ( ) (?) }</code>
*
**/
public static boolean isAlphaNumeric ( String s ) {
int i = 0, len = s.length();
while ( i < len && ( Character.isLetterOrDigit( s.charAt( i ) ) ||
s.charAt( i ) == ' ' || s.charAt( i ) == '.' ||
s.charAt( i ) == '-' || s.charAt( i ) == '_' )
|| s.charAt( i ) == '?' ){
i++;
}
return ( i >= len );
}
/**
* Return true if the string represent a number
* in the specified radix.
* <br><br>
**/
public static boolean isNumeric ( String s, int radix ) {
int i = 0, len = s.length();
while ( i < len && Character.digit( s.charAt( i ), radix ) > -1 ){
i++;
}
return ( i >= len );
}
/**
* Converts a BitSet into an extended binary field
* used in pack routines. The result is always in the
* extended format: (16 bytes of length)
* <br><br>
* @param b the BitSet
* @return binary representation
*/
public static byte[] bitSet2extendedByte ( BitSet b ){
int len = 128;
byte[] d = new byte[len >> 3];
for ( int i=0; i<len; i++ )
if (b.get(i+1))
d[i >> 3] |= (0x80 >> (i % 8));
d[0] |= 0x80;
return d;
}
/**
* Converts a String to an integer of base radix.
* <br><br>
* String constraints are:
* <li>Number must be less than 10 digits</li>
* <li>Number must be positive</li>
* @param s String representation of number
* @param radix Number base to use
* @return integer value of number
* @throws NumberFormatException
*/
public static int parseInt (String s, int radix) throws NumberFormatException {
int length = s.length();
if (length > 9)
throw new NumberFormatException ("Number can have maximum 9 digits");
int result = 0;
int index = 0;
int digit = Character.digit (s.charAt(index++), radix);
if (digit == -1)
throw new NumberFormatException ("String contains non-digit");
result = digit;
while (index < length) {
result *= radix;
digit = Character.digit (s.charAt(index++), radix);
if (digit == -1)
throw new NumberFormatException ("String contains non-digit");
result += digit;
}
return result;
}
/**
* Converts a String to an integer of radix 10.
* <br><br>
* String constraints are:
* <li>Number must be less than 10 digits</li>
* <li>Number must be positive</li>
* @param s String representation of number
* @return integer value of number
* @throws NumberFormatException
*/
public static int parseInt (String s) throws NumberFormatException {
return parseInt (s, 10);
}
/**
* Converts a character array to an integer of base radix.
* <br><br>
* Array constraints are:
* <li>Number must be less than 10 digits</li>
* <li>Number must be positive</li>
* @param cArray Character Array representation of number
* @param radix Number base to use
* @return integer value of number
* @throws NumberFormatException
*/
public static int parseInt (char[] cArray, int radix) throws NumberFormatException {
int length = cArray.length;
if (length > 9)
throw new NumberFormatException ("Number can have maximum 9 digits");
int result = 0;
int index = 0;
int digit = Character.digit(cArray[index++], radix);
if (digit == -1)
throw new NumberFormatException ("Char array contains non-digit");
result = digit;
while (index < length) {
result *= radix;
digit = Character.digit(cArray[index++],radix);
if (digit == -1)
throw new NumberFormatException ("Char array contains non-digit");
result += digit;
}
return result;
}
/**
* Converts a character array to an integer of radix 10.
* <br><br>
* Array constraints are:
* <li>Number must be less than 10 digits</li>
* <li>Number must be positive</li>
* @param cArray Character Array representation of number
* @return integer value of number
* @throws NumberFormatException
*/
public static int parseInt (char[] cArray) throws NumberFormatException {
return parseInt (cArray,10);
}
/**
* Converts a byte array to an integer of base radix.
* <br><br>
* Array constraints are:
* <li>Number must be less than 10 digits</li>
* <li>Number must be positive</li>
* @param bArray Byte Array representation of number
* @param radix Number base to use
* @return integer value of number
* @throws NumberFormatException
*/
public static int parseInt (byte[] bArray, int radix) throws NumberFormatException {
int length = bArray.length;
if (length > 9)
throw new NumberFormatException ("Number can have maximum 9 digits");
int result = 0;
int index = 0;
int digit = Character.digit((char)bArray[index++], radix);
if (digit == -1)
throw new NumberFormatException ("Byte array contains non-digit");
result = digit;
while (index < length) {
result *= radix;
digit = Character.digit((char)bArray[index++],radix);
if (digit == -1)
throw new NumberFormatException ("Byte array contains non-digit");
result += digit;
}
return result;
}
/**
* Converts a byte array to an integer of radix 10.
* <br><br>
* Array constraints are:
* <li>Number must be less than 10 digits</li>
* <li>Number must be positive</li>
* @param bArray Byte Array representation of number
* @return integer value of number
* @throws NumberFormatException
*/
public static int parseInt (byte[] bArray) throws NumberFormatException {
return parseInt (bArray,10);
}
private static String hexOffset (int i) {
i = (i>>4) << 4;
int w = i > 0xFFFF ? 8 : 4;
try {
return zeropad (Integer.toString (i, 16), w);
} catch (ISOException e) {
// should not happen
return e.getMessage();
}
}
/**
* @param b a byte[] buffer
* @return hexdump
*/
public static String hexdump (byte[] b) {
return hexdump (b, 0, b.length);
}
/**
* @param b a byte[] buffer
* @param offset starting offset
* @param len the Length
* @return hexdump
*/
public static String hexdump (byte[] b, int offset, int len) {
StringBuffer sb = new StringBuffer ();
StringBuffer hex = new StringBuffer ();
StringBuffer ascii = new StringBuffer ();
String sep = " ";
String lineSep = System.getProperty ("line.separator");
for (int i=offset; i<len; i++) {
char hi = Character.forDigit ((b[i] >> 4) & 0x0F, 16);
char lo = Character.forDigit (b[i] & 0x0F, 16);
hex.append (Character.toUpperCase(hi));
hex.append (Character.toUpperCase(lo));
hex.append (' ');
char c = (char) b[i];
ascii.append ((c >= 32 && c < 127) ? c : '.');
int j = i % 16;
switch (j) {
case 7 :
hex.append (' ');
break;
case 15 :
sb.append (hexOffset (i));
sb.append (sep);
sb.append (hex.toString());
sb.append (' ');
sb.append (ascii.toString());
sb.append (lineSep);
hex = new StringBuffer ();
ascii = new StringBuffer ();
break;
}
}
if (hex.length() > 0) {
while (hex.length () < 49)
hex.append (' ');
sb.append (hexOffset (len));
sb.append (sep);
sb.append (hex.toString());
sb.append (' ');
sb.append (ascii.toString());
sb.append (lineSep);
}
return sb.toString();
}
/**
* pads a string with 'F's (useful for pinoffset management)
* @param s an [hex]string
* @param len desired length
* @return string right padded with 'F's
*/
public static String strpadf (String s, int len) {
StringBuffer d = new StringBuffer(s);
while (d.length() < len)
d.append('F');
return d.toString();
}
/**
* reverse the effect of strpadf
* @param s F padded string
* @return trimmed string
*/
public static String trimf (String s) {
if (s != null) {
int l = s.length();
if (l > 0) {
while (--l >= 0) {
if (s.charAt (l) != 'F')
break;
}
s = l == 0 ? "" : s.substring (0, l+1);
}
}
return s;
}
/**
* return the last n characters of the passed String, left padding where required with 0
*
* @param s
* String to take from
* @param n nuber of characters to take
*
* @return String (may be null)
*/
public static String takeLastN(String s,int n) throws ISOException {
if (s.length()>n) {
return s.substring(s.length()-n);
}
else {
if (s.length()<n){
return zeropad(s,n);
}
else {
return s;
}
}
}
/**
* return the first n characters of the passed String, left padding where required with 0
*
* @param s
* String to take from
* @param n nuber of characters to take
*
* @return String (may be null)
*/
public static String takeFirstN(String s,int n) throws ISOException {
if (s.length()>n) {
return s.substring(0,n);
}
else {
if (s.length()<n){
return zeropad(s,n);
}
else {
return s;
}
}
}
}
|
package javafx.embed.swt;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.CharacterIterator;
import java.util.ArrayList;
import java.util.List;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.scene.input.InputMethodHighlight;
import javafx.scene.input.InputMethodTextRun;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.IME;
import com.sun.javafx.collections.ObservableListWrapper;
import com.sun.javafx.embed.EmbeddedSceneInterface;
public class FXCanvas2 extends FXCanvas
{
private static Field scenePeerField;
private static Method sendResizeEventToFXMethod;
static
{
try
{
scenePeerField = FXCanvas.class.getDeclaredField("scenePeer");
sendResizeEventToFXMethod = FXCanvas.class.getDeclaredMethod("sendResizeEventToFX");
}
catch (ReflectiveOperationException e)
{
throw new RuntimeException(e);
}
scenePeerField.setAccessible(true);
sendResizeEventToFXMethod.setAccessible(true);
}
private final IME ime;
private EmbeddedSceneInterface scenePeer;
@SuppressWarnings("deprecation")
public FXCanvas2(Composite parent, int style)
{
super(parent, style);
this.ime = new IME(this, SWT.NONE);
this.ime.addListener(SWT.ImeComposition, new org.eclipse.swt.widgets.Listener()
{
@Override
public void handleEvent(org.eclipse.swt.widgets.Event event)
{
switch (event.detail)
{
case SWT.COMPOSITION_CHANGED:
FXCanvas2.this.sendInputMethodEventToFX();
break;
}
}
});
}
/**
* JavaFX
*
* @return
*/
public EmbeddedSceneInterface getScenePeer()
{
if (this.scenePeer == null)
{
try
{
this.scenePeer = (EmbeddedSceneInterface) scenePeerField.get(this);
}
catch (IllegalAccessException e)
{
throw new RuntimeException(e);
}
}
return this.scenePeer;
}
/**
* JavaFX{@link javafx.stage.Stage}{@link javafx.scene.Scene}
*/
public void sendResizeEventToFX()
{
try
{
FXCanvas2.sendResizeEventToFXMethod.invoke(this);
}
catch (ReflectiveOperationException e)
{
throw new RuntimeException(e);
}
}
private void sendInputMethodEventToFX()
{
String text = this.getTextForEvent(this.ime.getText());
EmbeddedSceneInterface scenePeer = this.getScenePeer();
if (scenePeer != null)
{
String committed = text.substring(0, this.ime.getCommitCount());
if (this.ime.getText().length() == this.ime.getCommitCount())
{
// Send empty text when committed, because the actual chars will then be immediately sent via keys.
scenePeer.inputMethodEvent(
javafx.scene.input.InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
FXCollections.emptyObservableList(), "", this.ime.getCompositionOffset());
}
else
{
ObservableList<InputMethodTextRun> composed = this.inputMethodEventComposed(text, this.ime.getCommitCount());
scenePeer.inputMethodEvent(
javafx.scene.input.InputMethodEvent.INPUT_METHOD_TEXT_CHANGED,
composed, committed, this.ime.getCaretOffset());
}
}
}
private String getTextForEvent(String text)
{
if (text == null)
return "";
StringBuilder builder = new StringBuilder();
for (int i = 0; i < text.length(); i++)
{
char c = text.charAt(i);
if (c == CharacterIterator.DONE)
break;
builder.append(c);
}
return builder.toString();
}
private ObservableList<InputMethodTextRun> inputMethodEventComposed(String text, int commitCount)
{
List<InputMethodTextRun> composed = new ArrayList<>();
if (commitCount < text.length())
{
composed.add(new InputMethodTextRun(
text.substring(commitCount), InputMethodHighlight.UNSELECTED_RAW));
}
return new ObservableListWrapper<>(composed);
}
}
|
package info.limpet.data2;
import info.limpet.rcp.TestReflectivePropertySource;
import junit.framework.TestSuite;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@Suite.SuiteClasses(
{
TestAdmin.class,
TestAnalysis.class,
TestArithmeticCollections.class,
TestBistaticAngleCalculations.class,
TestCollectionCompliance.class,
TestCollections.class,
TestCsvParser.class,
TestDynamic.class,
TestExport.class,
TestExport.class,
TestGeotoolsGeometry.class,
TestGrids.class,
TestLocations.class,
TestOperations.class,
TestPersistence.class,
TestReflectivePropertySource.class,
TestRepParser.class
})
@RunWith(Suite.class)
public class AllTests extends TestSuite
{
}
|
package com.innovaee.eorder.service.impl;
import com.innovaee.eorder.dao.DishDao;
import com.innovaee.eorder.dao.OrderDao;
import com.innovaee.eorder.dao.OrderItemDao;
import com.innovaee.eorder.dao.UserDao;
import com.innovaee.eorder.entity.Dish;
import com.innovaee.eorder.entity.Order;
import com.innovaee.eorder.entity.OrderItem;
import com.innovaee.eorder.entity.User;
import com.innovaee.eorder.exception.DishNotFoundException;
import com.innovaee.eorder.exception.UserNotFoundException;
import com.innovaee.eorder.exception.ZeroOrderItemException;
import com.innovaee.eorder.service.OrderService;
import com.innovaee.eorder.support.Constants;
import com.innovaee.eorder.support.DateUtil;
import com.innovaee.eorder.support.MessageUtil;
import com.innovaee.eorder.vo.NewOrderItemVO;
import com.innovaee.eorder.vo.NewOrderVO;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* @Title: OrderServiceImpl
* @Description:
* @version V1.0
*/
public class OrderServiceImpl implements OrderService {
private OrderDao orderDao;
private OrderItemDao orderItemDao;
private DishDao dishDao;
private UserDao userDao;
/** setter/getter */
public void setOrderDao(OrderDao orderDao) {
this.orderDao = orderDao;
}
public OrderDao getOrderDao() {
return orderDao;
}
public DishDao getDishDao() {
return dishDao;
}
public void setDishDao(DishDao dishDao) {
this.dishDao = dishDao;
}
public UserDao getUserDao() {
return userDao;
}
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
public OrderItemDao getOrderItemDao() {
return orderItemDao;
}
public void setOrderItemDao(OrderItemDao orderItemDao) {
this.orderItemDao = orderItemDao;
}
/**
* ID
*
* @param orderId
* ID
* @return
*/
@Override
public Order getOrderById(Long orderId) {
return orderDao.get(orderId);
}
/**
* ID
*
* @param memberId
* ID
* @return
*/
@Override
public List<Order> getOrdersByMemberId(Long memberId) {
return orderDao.getOrdersByMemberId(memberId);
}
/**
*
*
* @param newOrder
*
* @return id-1
* @throws UserNotFoundException
* @throws ZeroOrderItemException
* @throws DishNotFoundException
*/
@Override
@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)
public Long placeOrder(NewOrderVO newOrder) throws UserNotFoundException,
ZeroOrderItemException, DishNotFoundException {
// 1. OrderSeqyyMMdd00001
Date currentDay = Calendar.getInstance().getTime();
Integer maxOrderSeq = orderDao.getMaxOrderSeqofDate(currentDay);
String curOrderSeq = String
.format("%s%05d", DateUtil.formatDate(
Constants.DATE_FORMAT_YYYYMMDD, currentDay),
maxOrderSeq.intValue() + 1);
// 2. Order
Order order = new Order();
order.setOrderSeq(curOrderSeq);
order.setTableNumber(newOrder.getTableNumber());
order.setAttendeeNumber(newOrder.getAttendeeNumber());
order.setOrderStatus(Constants.ORDER_NEW);
order.setCreateDate(currentDay);
order.setUpdateDate(currentDay);
User servent = userDao.get(newOrder.getServentId());
if (null == servent) {
throw new UserNotFoundException(
MessageUtil.getMessage("employee_id", ""+newOrder.getServentId()));
} else {
order.setServent(servent);
}
float discount = 1.0f;
if (newOrder.getMemberId() > 0) {
User member = userDao.get(newOrder.getMemberId());
if (null != member) {
order.setMember(member);
discount = member.getMemberShip() == null ? 1.0f : member.getMemberShip().getLevel().getDiscount() / 10f;
}
}
Long orderId = orderDao.save(order);
order = orderDao.get(orderId);
Float totalPrice = 0.0f;
if (null != newOrder.getItems() && newOrder.getItems().size() > 0) {
for (NewOrderItemVO item : newOrder.getItems()) {
OrderItem orderItem = new OrderItem();
Dish dish = dishDao.get(item.getDishId());
if (null != dish) {
orderItem.setDish(dish);
orderItem.setDishAmount(item.getDishAmount());
} else {
throw new DishNotFoundException(MessageUtil.getMessage(
"dish_id", item.getDishId() + ""));
}
orderItem.setCreateDate(currentDay);
orderItem.setUpdateDate(currentDay);
orderItem.setOrder(order);
orderItemDao.save(orderItem);
totalPrice += dish.getPrice() * orderItem.getDishAmount();
order.getOrderItems().add(orderItem);
}
order.setTotalPrice(totalPrice);
order.setDiscountPrice(totalPrice * discount);
orderDao.update(order);
} else {
throw new ZeroOrderItemException();
}
return orderId;
}
}
|
package org.usfirst.frc.team1736.robot;
public class RobotSpeedomitar {
public RobotSpeedomitar(){
return;
}
public void update(){
double WheelSpeedOno;
double WheelSpeedDos;
double WheelSpeedTres;
double WheelSpeedCuatro;
double Vx;
double Vy;
double netSpeed;
//Calculate wheel speeds in radians per second
WheelSpeedOno =RobotState.frontLeftWheelVelocity_rpm * 2.0 * Math.PI / 60;
WheelSpeedDos =RobotState.frontRightWheelVelocity_rpm * 2.0 * Math.PI / 60;
WheelSpeedTres =RobotState.rearLeftWheelVelocity_rpm * 2.0 * Math.PI / 60;
WheelSpeedCuatro =RobotState.rearRightWheelVelocity_rpm * 2.0 * Math.PI / 60;
//Calculate translational velocity x/y components via inverse mechanum kinematic equations
Vx = (WheelSpeedOno + WheelSpeedDos + WheelSpeedTres + WheelSpeedCuatro) * 0.17 / 4;
Vy = (WheelSpeedOno - WheelSpeedDos + WheelSpeedTres - WheelSpeedCuatro) * 0.17 / 4;
//Calculate net speed vector with pythagorean theorem
netSpeed = Math.sqrt(Vx*Vx+Vy*Vy);
//Store results into state variables
RobotState.robotNetSpeed_ftpers = netSpeed;
RobotState.robotFwdRevVel_ftpers = Vx;
RobotState.robotStrafeVel_ftpers = Vy;
}
}
|
package alma.acs.logging.engine.parser;
public class ACSLogParserFactory {
/**
* The supported parsers.
* <P>
* This has been introduced to allow the usage of a specific parser
* especially useful for testing where we need to test parsing against
* each possible parser.
*
* @author acaproni
*
*/
public enum ParserTypes {
DOM,
VTD
}
/**
* The parser is a singleton built at the first invocation
* of <code>getParser()</code>.
* <P>
* Calls to <code>getParser(ParserType...)</code> do not change the value of this
* property.
*/
private static ACSLogParser parser=null;
/**
* This property is used to check if VTD is installed to avoid trying to instantiate
* if the library is missing
* <P>
* It is initially set to <code>true</code> to try to instantiate VTD the first time
* <code>getParser()</code> is called
*/
private static boolean usingVTD=true;
/**
* Get a parser.
* <P>
* The <code>ACSLogParser</code> returned by this method can be a new instance
* or not, depending on the implementation.
*
* @return The parser.
* @throws <code>Exception</code> in case of error building the parser
*/
public static ACSLogParser getParser() throws Exception {
if (parser!=null) {
return parser;
}
if (usingVTD) {
try {
// Initially try to in instantiate VTD-XML parser
parser = getParser(ParserTypes.VTD);
return parser;
} catch (Throwable t) {
usingVTD=false;
}
}
parser = getParser(ParserTypes.DOM);
return parser;
}
/**
* Get a parser of the given type.
* <P>
* This method allows to get a parser of a specific type and is thought for
* testing purposes.
* <P>
* If the type of the requested parser is not the type of the parser in use then
* a new parser is instantiated and returned but the parser in use remains untouched.
*
* @param parserType The type of the parser to instantiate. It can't be <code>null</code>.
* @return The parser of the given type
* @throws <{@link Exception} in case of error instantiating the parser.
*/
public static ACSLogParser getParser(ParserTypes parserType) throws Exception {
if (parserType==null) {
throw new IllegalArgumentException("Tye type can't be null");
}
if (parserType==ParserTypes.VTD) {
parser = new ACSLogParserVTD();
} else {
parser = new ACSLogParserDOM();
}
return parser;
}
/**
* Return the type of the passed parser.
*
* @param parser The parser whose type has to be checked. It can't be <code>null</code>.
* @return The type of the parser.
* @throw <code>Exception</code> if the type of the parser is not recognized/supported.
*/
public static ParserTypes getParserType(ACSLogParser parserToCheck) throws Exception {
if (parserToCheck==null) {
throw new IllegalArgumentException("The parser can't be null");
}
if (parserToCheck instanceof ACSLogParserDOM) {
return ParserTypes.DOM;
}
if (parserToCheck instanceof ACSLogParserVTD) {
return ParserTypes.VTD;
}
throw new Exception("Unknown parser type: "+parserToCheck.getClass().getName());
}
/**
* Return the type of the parser in use.
*
* @return The type of the parser in use or <code>null</code> if no parser is still in use
* i.e. <code>getParser()</code> has not been executed yet.
* @throw <code>Exception</code> if the type of the parser is not recognized/supported.
*/
public static ParserTypes getParserType() throws Exception {
if (parser==null) {
return null;
}
return getParserType(parser);
}
}
|
package com.navigation.reactnative;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import androidx.fragment.app.FragmentActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.uimanager.events.RCTEventEmitter;
import java.util.ArrayList;
import java.util.List;
public class TabBarView extends ViewGroup {
List<TabFragment> tabFragments = new ArrayList<>();
private FragmentManager fragmentManager;
private TabFragment selectedTabFragment;
int selectedTab = 0;
int nativeEventCount;
int mostRecentEventCount;
private int selectedIndex = 0;
public TabBarView(Context context) {
super(context);
FragmentActivity activity = (FragmentActivity) ((ReactContext) getContext()).getCurrentActivity();
fragmentManager = activity != null ? activity.getSupportFragmentManager() : null;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
setCurrentTab(selectedTab);
}
void populateTabs() {
TabNavigationView tabNavigation = getTabNavigation();
if (tabNavigation != null) {
for(int i = 0; i < tabFragments.size(); i++) {
tabFragments.get(i).tabBarItem.setTabView(tabNavigation, i);
}
}
}
private TabNavigationView getTabNavigation() {
ViewGroup parent = (ViewGroup) getParent();
for(int i = 0; parent != null && i < parent.getChildCount(); i++) {
View child = parent.getChildAt(i);
if (child instanceof TabNavigationView)
return (TabNavigationView) child;
}
return null;
}
void onAfterUpdateTransaction() {
if (tabFragments.size() == 0)
return;
if (selectedTabFragment != null) {
int reselectedTab = tabFragments.indexOf(selectedTabFragment);
selectedTab = reselectedTab != -1 ? reselectedTab : Math.min(selectedTab, tabFragments.size() - 1);
}
setCurrentTab(selectedTab);
}
void setCurrentTab(int index) {
if (index != selectedIndex) {
nativeEventCount++;
WritableMap event = Arguments.createMap();
event.putInt("tab", index);
event.putInt("eventCount", nativeEventCount);
ReactContext reactContext = (ReactContext) getContext();
reactContext.getJSModule(RCTEventEmitter.class).receiveEvent(getId(), "onTabSelected", event);
tabFragments.get(index).tabBarItem.pressed();
}
selectedTab = selectedIndex = index;
selectedTabFragment = tabFragments.get(index);
if (getTabNavigation() != null)
getTabNavigation().setSelectedItemId(index);
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(getId(), tabFragments.get(index), "TabBar" + getId());
transaction.commit();
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
}
}
|
package com.nlbhub.nlb.api;
import com.nlbhub.nlb.domain.ModificationImpl;
import com.nlbhub.nlb.domain.VariableImpl;
import com.nlbhub.nlb.util.MultiLangString;
import com.nlbhub.nlb.util.StringHelper;
import org.jetbrains.annotations.NotNull;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* The LinkLw class
*
* @author Anton P. Kolosov
* @version 1.0 2/18/14
*/
@XmlAccessorType(XmlAccessType.NONE)
@XmlRootElement(name = "link")
public class LinkLw implements Link {
public static enum Type {Traverse, Return, AutowiredIn, AutowiredOut}
private Type m_type;
private String m_target;
private IdentifiableItem m_parent;
private MultiLangString m_text;
private String m_constrId;
private boolean m_auto;
private boolean m_positiveConstraint;
private boolean m_shouldObeyToModuleConstraint;
private List<Modification> m_modifications = new ArrayList<>();
public LinkLw(
Type type,
String target,
IdentifiableItem parent,
MultiLangString text,
String constrId,
boolean auto,
boolean positiveConstraint,
boolean shouldObeyToModuleConstraint
) {
m_type = type;
m_target = target;
m_parent = parent;
m_text = text;
m_constrId = constrId;
m_auto = auto;
m_positiveConstraint = positiveConstraint;
m_shouldObeyToModuleConstraint = shouldObeyToModuleConstraint;
if (m_type == Type.AutowiredIn || m_type == Type.AutowiredOut) {
ModificationImpl modification = new ModificationImpl();
modification.setType(Modification.Type.ASSIGN.name());
modification.setParent(this);
modification.setVarId(
(m_type == Type.AutowiredIn) ? parent.getId() : target
);
modification.setExprId((m_type == Type.AutowiredIn) ? NonLinearBook.TRUE_VARID : NonLinearBook.FALSE_VARID);
m_modifications.add(modification);
}
}
@Override
@XmlElement(name = "varid")
public String getVarId() {
return Constants.EMPTY_STRING;
}
@Override
@XmlElement(name = "target")
public String getTarget() {
return m_target;
}
@Override
@XmlElement(name = "text")
public String getText() {
return m_text.get(m_parent.getCurrentNLB().getLanguage());
}
@Override
public MultiLangString getTexts() {
return MultiLangString.createCopy(m_text);
}
@Override
@XmlElement(name = "constrid")
public String getConstrId() {
return m_constrId;
}
@Override
@XmlElement(name = "is-positive")
public boolean isPositiveConstraint() {
return m_positiveConstraint;
}
@Override
@XmlElement(name = "is-obey-to-module-constraint")
public boolean isObeyToModuleConstraint() {
return m_shouldObeyToModuleConstraint;
}
@Override
@XmlElement(name = "is-traversal")
public boolean isTraversalLink() {
return m_type == Type.Traverse;
}
@Override
@XmlElement(name = "is-return")
public boolean isReturnLink() {
return m_type == Type.Return;
}
@Override
@XmlElement(name = "stroke")
public String getStroke() {
return Constants.EMPTY_STRING;
}
@Override
public Coords getCoords() {
return new CoordsLw();
}
@Override
@XmlElement(name = "is-auto")
public boolean isAuto() {
return m_auto;
}
@Override
public List<Modification> getModifications() {
return m_modifications;
}
@Override
public Modification getModificationById(@NotNull String modId) {
for (Modification modification : m_modifications) {
if (modification.getId().equals(modId)) {
return modification;
}
}
return null;
}
@Override
public String getId() {
return m_parent.getId() + "_" + m_target + "_" + m_type.name();
}
@Override
public String getFullId() {
String[] temp = {m_parent.getId(), getId()};
return StringHelper.formatSequence(Arrays.asList(temp));
}
@Override
public boolean isDeleted() {
return false;
}
@Override
public IdentifiableItem getParent() {
return m_parent;
}
@Override
public NonLinearBook getCurrentNLB() {
return m_parent.getCurrentNLB();
}
@Override
public String addObserver(NLBObserver observer) {
return Constants.EMPTY_STRING;
}
@Override
public void removeObserver(String observerId) {
}
@Override
public void notifyObservers() {
}
public static String decorateId(String id) {
return "vl_" + id.replaceAll("-", "_");
}
}
|
package se.sics.cooja.dialogs;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.Frame;
import java.awt.GraphicsEnvironment;
import java.awt.List;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Vector;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import org.apache.log4j.Logger;
import se.sics.cooja.GUI;
import se.sics.cooja.ProjectConfig;
/**
* This dialog allows a user to manage the project directory configurations. Project
* directories can be added, removed or reordered. The resulting
* configuration can also be viewed.
*
* This dialog reads from the external project configuration files in each project
* directory, as well as from any specified default configuration files.
*
* @author Fredrik Osterlind
*/
public class ProjectDirectoriesDialog extends JDialog {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(ProjectDirectoriesDialog.class);
private GUI gui;
private File[] projects = null;
private List projectsList = new List();
/**
* Allows editing the project directories list by adding new,
* reordering or removing project directories.
*
* @param parent Parent container
* @param currentProjects Current project directories
* @return The new project directories, or null if dialog was aborted
*/
public static File[] showDialog(Container parent, GUI gui, File[] currentProjects) {
if (GUI.isVisualizedInApplet()) {
return null;
}
ProjectDirectoriesDialog dialog = new ProjectDirectoriesDialog((Window) parent, currentProjects);
dialog.gui = gui;
dialog.setLocationRelativeTo(parent);
dialog.setVisible(true);
return dialog.projects;
}
private ProjectDirectoriesDialog(Container parent, File[] projects) {
super(
parent instanceof Dialog?(Dialog)parent:
parent instanceof Window?(Window)parent:
(Frame)parent, "Manage Project Directories", ModalityType.APPLICATION_MODAL);
JPanel mainPane = new JPanel();
mainPane.setLayout(new BoxLayout(mainPane, BoxLayout.Y_AXIS));
JPanel smallPane;
JButton button;
// BOTTOM BUTTON PART
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
buttonPane.add(Box.createHorizontalGlue());
button = new JButton("Cancel");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ProjectDirectoriesDialog.this.projects = null;
dispose();
}
});
buttonPane.add(button);
buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
button = new JButton("Set default");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Object[] options = { "Ok", "Cancel" };
String newDefaultProjectDirs = "";
for (String directory : projectsList.getItems()) {
if (newDefaultProjectDirs != "") {
newDefaultProjectDirs += ";";
}
newDefaultProjectDirs += gui.createPortablePath(new File(directory)).getPath();
}
newDefaultProjectDirs = newDefaultProjectDirs.replace('\\', '/');
String question = "External tools setting DEFAULT_PROJECTDIRS will change from:\n"
+ GUI.getExternalToolsSetting("DEFAULT_PROJECTDIRS")
+ "\n to:\n"
+ newDefaultProjectDirs;
String title = "Change external tools settings?";
int answer = JOptionPane.showOptionDialog(ProjectDirectoriesDialog.this, question, title,
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE, null,
options, options[0]);
if (answer != JOptionPane.YES_OPTION) {
return;
}
GUI.setExternalToolsSetting("DEFAULT_PROJECTDIRS", newDefaultProjectDirs);
}
});
buttonPane.add(button);
buttonPane.add(Box.createRigidArea(new Dimension(10, 0)));
button = new JButton("OK");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ArrayList<File> newProjects = new ArrayList<File>();
for (String directory : projectsList.getItems()) {
newProjects.add(new File(directory));
}
ProjectDirectoriesDialog.this.projects = newProjects.toArray(new File[0]);
dispose();
}
});
buttonPane.add(button);
this.getRootPane().setDefaultButton(button);
// LIST PART
JPanel listPane = new JPanel();
listPane.setLayout(new BoxLayout(listPane, BoxLayout.X_AXIS));
listPane.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
JPanel listPane2 = new JPanel();
listPane2.setLayout(new BoxLayout(listPane2, BoxLayout.Y_AXIS));
listPane2.add(projectsList);
listPane.add(listPane2);
smallPane = new JPanel();
smallPane.setLayout(new BoxLayout(smallPane, BoxLayout.Y_AXIS));
button = new JButton("Move up");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int selectedIndex = projectsList.getSelectedIndex();
if (selectedIndex <= 0) {
return;
}
File file = new File(projectsList.getItem(selectedIndex));
removeProjectDir(selectedIndex);
addProjectDir(file, selectedIndex - 1);
projectsList.select(selectedIndex - 1);
}
});
smallPane.add(button);
button = new JButton("Move down");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int selectedIndex = projectsList.getSelectedIndex();
if (selectedIndex < 0) {
return;
}
if (selectedIndex >= projectsList.getItemCount() - 1) {
return;
}
File file = new File(projectsList.getItem(selectedIndex));
removeProjectDir(selectedIndex);
addProjectDir(file, selectedIndex + 1);
projectsList.select(selectedIndex + 1);
}
});
smallPane.add(button);
smallPane.add(Box.createRigidArea(new Dimension(10, 10)));
button = new JButton("Remove");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (projectsList.getSelectedIndex() < 0) {
return;
}
removeProjectDir(projectsList.getSelectedIndex());
}
});
smallPane.add(button);
listPane.add(smallPane);
// ADD/REMOVE PART
JPanel addRemovePane = new JPanel();
addRemovePane.setLayout(new BoxLayout(addRemovePane, BoxLayout.X_AXIS));
addRemovePane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
button = new JButton("View resulting config");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ProjectConfig config;
try {
// Create default configuration
config = new ProjectConfig(true);
} catch (FileNotFoundException ex) {
logger.fatal("Could not find default project config file: "
+ GUI.PROJECT_DEFAULT_CONFIG_FILENAME);
return;
} catch (IOException ex) {
logger.fatal("Error when reading default project config file: "
+ GUI.PROJECT_DEFAULT_CONFIG_FILENAME);
return;
}
// Add the project directory configurations
for (String projectDir : projectsList.getItems()) {
try {
config.appendProjectDir(new File(projectDir));
} catch (Exception ex) {
logger.fatal("Error when merging configurations: " + ex);
return;
}
}
// Show merged configuration
ConfigViewer.showDialog(ProjectDirectoriesDialog.this, config);
}
});
addRemovePane.add(button);
addRemovePane.add(Box.createRigidArea(new Dimension(10, 0)));
button = new JButton("Enter path manually");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
ProjectDirectoryInputDialog pathDialog = new ProjectDirectoryInputDialog(ProjectDirectoriesDialog.this);
pathDialog.pack();
pathDialog.setLocationRelativeTo(ProjectDirectoriesDialog.this);
pathDialog.setVisible(true);
File projectPath = pathDialog.getProjectDirectory();
if (projectPath != null) {
addProjectDir(projectPath);
}
}
});
addRemovePane.add(button);
addRemovePane.add(Box.createRigidArea(new Dimension(10, 0)));
button = new JButton("Browse");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JFileChooser fc = new JFileChooser();
fc.setCurrentDirectory(new java.io.File(GUI.getExternalToolsSetting("PATH_CONTIKI")));
fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
fc.setDialogTitle("Select project directory");
if (fc.showOpenDialog(ProjectDirectoriesDialog.this) == JFileChooser.APPROVE_OPTION) {
File dir = fc.getSelectedFile();
String selectedPath = null;
try {
selectedPath = dir.getCanonicalPath().replace('\\', '/');
String contikiPath =
new File(GUI.getExternalToolsSetting("PATH_CONTIKI", null)).
getCanonicalPath().replace('\\', '/');
if (contikiPath != null && selectedPath.startsWith(contikiPath)) {
selectedPath = selectedPath.replaceFirst(
contikiPath, GUI.getExternalToolsSetting("PATH_CONTIKI"));
}
addProjectDir(new File(selectedPath));
} catch (IOException ex) {
logger.fatal("Error in path extraction: " + ex);
}
}
}
});
addRemovePane.add(button);
// Add components
Container contentPane = getContentPane();
mainPane.add(listPane);
mainPane.add(addRemovePane);
contentPane.add(mainPane, BorderLayout.CENTER);
contentPane.add(buttonPane, BorderLayout.SOUTH);
for (File projectDir : projects) {
addProjectDir(projectDir);
}
pack();
}
private void addProjectDir(File projectDir) {
addProjectDir(projectDir, projectsList.getItemCount());
}
private void addProjectDir(File projectDir, int index) {
// Check that file exists, is a directory and contains the correct files
if (!projectDir.exists()) {
logger.fatal("Can't find project directory: " + projectDir);
return;
}
if (!projectDir.isDirectory()) {
logger.fatal("Specified path is not a directory: " + projectDir);
return;
}
projectsList.add(projectDir.getPath(), index);
}
private void removeProjectDir(int index) {
projectsList.remove(index);
}
}
/**
* Modal frame that shows all keys with their respective values of a given class
* configuration.
*
* @author Fredrik Osterlind
*/
class ConfigViewer extends JDialog {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(ConfigViewer.class);
public static void showDialog(Frame parentFrame, ProjectConfig config) {
ConfigViewer myDialog = new ConfigViewer(parentFrame, config);
myDialog.setLocationRelativeTo(parentFrame);
myDialog.setAlwaysOnTop(true);
Rectangle maxSize = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
if (maxSize != null &&
(myDialog.getSize().getWidth() > maxSize.getWidth()
|| myDialog.getSize().getHeight() > maxSize.getHeight())) {
Dimension newSize = new Dimension();
newSize.height = Math.min((int) maxSize.getHeight(), (int) myDialog.getSize().getHeight());
newSize.width = Math.min((int) maxSize.getWidth(), (int) myDialog.getSize().getWidth());
myDialog.setSize(newSize);
}
if (myDialog != null) {
myDialog.setVisible(true);
}
}
public static void showDialog(Dialog parentDialog, ProjectConfig config) {
ConfigViewer myDialog = new ConfigViewer(parentDialog, config);
myDialog.setLocationRelativeTo(parentDialog);
myDialog.setAlwaysOnTop(true);
if (myDialog != null) {
myDialog.setVisible(true);
}
}
private ConfigViewer(Dialog dialog, ProjectConfig config) {
super(dialog, "Current class configuration", true);
init(config);
}
private ConfigViewer(Frame frame, ProjectConfig config) {
super(frame, "Current class configuration", true);
init(config);
}
private void init(ProjectConfig config) {
JPanel mainPane = new JPanel(new BorderLayout());
JLabel label;
JButton button;
// BOTTOM BUTTON PART
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.X_AXIS));
buttonPane.setBorder(BorderFactory.createEmptyBorder(0, 10, 10, 10));
buttonPane.add(Box.createHorizontalGlue());
button = new JButton("Close");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
dispose();
}
});
buttonPane.add(button);
// LIST PART
JPanel keyPane = new JPanel();
keyPane.setLayout(new BoxLayout(keyPane, BoxLayout.Y_AXIS));
mainPane.add(keyPane, BorderLayout.WEST);
JPanel valuePane = new JPanel();
valuePane.setLayout(new BoxLayout(valuePane, BoxLayout.Y_AXIS));
mainPane.add(valuePane, BorderLayout.CENTER);
label = new JLabel("KEY");
label.setForeground(Color.RED);
keyPane.add(label);
label = new JLabel("VALUE");
label.setForeground(Color.RED);
valuePane.add(label);
Enumeration<String> allPropertyNames = config.getPropertyNames();
while (allPropertyNames.hasMoreElements()) {
String propertyName = allPropertyNames.nextElement();
keyPane.add(new JLabel(propertyName));
if (config.getStringValue(propertyName).equals("")) {
valuePane.add(new JLabel(" "));
} else {
valuePane.add(new JLabel(config.getStringValue(propertyName)));
}
}
// Add components
Container contentPane = getContentPane();
contentPane.add(new JScrollPane(mainPane), BorderLayout.CENTER);
contentPane.add(buttonPane, BorderLayout.SOUTH);
pack();
/* Respect screen size */
Rectangle maxSize = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
if (maxSize != null && (getSize().width > maxSize.width)) {
setSize(maxSize.width, getSize().height);
}
if (maxSize != null && (getSize().height > maxSize.height)) {
setSize(getSize().width, maxSize.height);
}
}
}
|
package org.unipop.schema.element;
import org.apache.tinkerpop.gremlin.structure.Element;
import org.json.JSONObject;
import org.unipop.query.predicates.PredicatesHolder;
import org.unipop.query.predicates.PredicatesHolderFactory;
import org.unipop.schema.property.AbstractPropertyContainer;
import org.unipop.schema.property.NonDynamicPropertySchema;
import org.unipop.structure.UniElement;
import org.unipop.structure.UniGraph;
import org.unipop.util.ConversionUtils;
import java.util.*;
import java.util.stream.Collectors;
public abstract class AbstractElementSchema<E extends Element> extends AbstractPropertyContainer implements ElementSchema<E> {
protected UniGraph graph;
public AbstractElementSchema(JSONObject configuration, UniGraph graph) {
super(configuration, graph);
this.graph = graph;
}
public UniGraph getGraph() {
return graph;
}
protected Map<String, Object> getProperties(Map<String, Object> source) {
List<Map<String, Object>> fieldMaps = this.getPropertySchemas().stream().map(schema ->
schema.toProperties(source)).collect(Collectors.toList());
return ConversionUtils.merge(fieldMaps, this::mergeProperties, false);
}
protected Object mergeProperties(Object prop1, Object prop2) {
if(!prop1.equals(prop2))
System.out.println("merging unequal properties '" + prop1 + "' and '" + prop2 + "', schema: " + this);
return prop1;
}
@Override
public Map<String, Object> toFields(E element) {
return getFields(element);
}
protected Map<String, Object> getFields(E element) {
Map<String, Object> properties = UniElement.fullProperties(element);
if(properties == null) return null;
List<Map<String, Object>> fieldMaps = this.getPropertySchemas().stream().map(schema ->
schema.toFields(properties)).collect(Collectors.toList());
return ConversionUtils.merge(fieldMaps, this::mergeFields, false);
}
protected Object mergeFields(Object obj1, Object obj2) {
if(!obj1.equals(obj2))
System.out.println("merging unequal fields '" + obj1 + "' and '" + obj2 + "', schema: " + this);
return obj1;
}
@Override
public Set<String> toFields(Set<String> propertyKeys) {
return getPropertySchemas().stream().flatMap(propertySchema ->
propertySchema.toFields(propertyKeys).stream()).collect(Collectors.toSet());
}
@Override
public String getFieldByPropertyKey(String key){
Optional<String> first = propertySchemas.stream().filter(s -> s.getKey() != null).filter(s -> s.getKey().equals(key)).flatMap(s -> s.toFields(Collections.singleton(key)).stream()).findFirst();
if (first.isPresent()) return first.get();
else
if (dynamicProperties instanceof NonDynamicPropertySchema) return null;
else return key;
}
@Override
public PredicatesHolder toPredicates(PredicatesHolder predicatesHolder) {
Set<PredicatesHolder> predicates = getPropertySchemas().stream()
.map(schema -> schema.toPredicates(predicatesHolder))
.filter(holder -> holder != null)
.collect(Collectors.toSet());
return PredicatesHolderFactory.create(predicatesHolder.getClause(), predicates);
}
@Override
public String toString() {
return "AbstractElementSchema{" +
"graph=" + graph +
"} " + super.toString();
}
}
|
package com.blankj.utilcode.util;
import org.junit.Test;
import java.util.Arrays;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
public class EncodeUtilsTest extends BaseTest {
@Test
public void urlEncode_urlDecode() {
String urlEncodeString = "%E5%93%88%E5%93%88%E5%93%88";
assertEquals(urlEncodeString, EncodeUtils.urlEncode(""));
assertEquals(urlEncodeString, EncodeUtils.urlEncode("", "UTF-8"));
assertEquals("", EncodeUtils.urlDecode(urlEncodeString));
assertEquals("", EncodeUtils.urlDecode(urlEncodeString, "UTF-8"));
}
@Test
public void base64Decode_base64Encode() {
assertTrue(
Arrays.equals(
"blankj".getBytes(),
EncodeUtils.base64Decode(EncodeUtils.base64Encode("blankj"))
)
);
assertTrue(
Arrays.equals(
"blankj".getBytes(),
EncodeUtils.base64Decode(EncodeUtils.base64Encode2String("blankj".getBytes()))
)
);
assertEquals(
"Ymxhbmtq",
EncodeUtils.base64Encode2String("blankj".getBytes())
);
assertTrue(
Arrays.equals(
"Ymxhbmtq".getBytes(),
EncodeUtils.base64Encode("blankj".getBytes())
)
);
}
@Test
public void htmlEncode_htmlDecode() {
String html = "<html>" +
"<head>" +
"<title> HTML </title>" +
"</head>" +
"<body>" +
"<p>body </p>" +
"<p>title </p>" +
"</body>" +
"</html>";
String encodeHtml = "<html><head><title> HTML </title></head><body><p>body </p><p>title </p></body></html>";
assertEquals(encodeHtml, EncodeUtils.htmlEncode(html));
assertEquals(html, EncodeUtils.htmlDecode(encodeHtml).toString());
}
@Test
public void binEncode_binDecode(){
String test = "test";
String binary = EncodeUtils.binEncode(test);
assertEquals("test", EncodeUtils.binDecode(binary));
}
}
|
package VASSAL.configure;
import VASSAL.build.AbstractBuildable;
import VASSAL.build.AbstractConfigurable;
import VASSAL.build.Buildable;
import VASSAL.build.GameModule;
import VASSAL.build.module.Documentation;
import VASSAL.build.module.KeyNamer;
import VASSAL.build.module.PrototypeDefinition;
import VASSAL.build.module.documentation.HelpFile;
import VASSAL.build.widget.PieceSlot;
import VASSAL.counters.Decorator;
import VASSAL.counters.GamePiece;
import VASSAL.i18n.Resources;
import VASSAL.search.SearchTarget;
import VASSAL.tools.ErrorDialog;
import VASSAL.tools.NamedKeyStroke;
import VASSAL.tools.swing.SwingUtils;
import net.miginfocom.swing.MigLayout;
import org.apache.commons.lang3.StringUtils;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.awt.Frame;
import java.io.File;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class ListKeyCommandsDialog extends JDialog {
private static final long serialVersionUID = 1L;
public ListKeyCommandsDialog(Frame owner, List<Object[]> rows) {
super(owner, Resources.getString("Editor.ListKeyCommands.remove_unused_images"), true);
final JTable table = new JTable(
rows.toArray(new Object[0][]),
new Object[] { "Key", "Name", "Source Name", "Source Description" }
);
table.setAutoCreateRowSorter(true);
final JPanel panel = new JPanel(new MigLayout("fill", "[]", "[]unrel[]")); //NON-NLS
final JScrollPane scroll = new JScrollPane(table);
panel.add(scroll, "grow, push, wrap");
final JButton ok = new JButton(Resources.getString("General.ok"));
ok.addActionListener(e -> dispose());
final JButton help = new JButton(Resources.getString("General.help"));
help.addActionListener(e -> help());
final JPanel buttonPanel = new JPanel(new MigLayout("ins 0", "push[]rel[]push", "")); // NON-NLS
buttonPanel.add(ok, "tag ok, sg 1"); //$NON-NLS-1$//
buttonPanel.add(help, "tag help, sg 1");
panel.add(buttonPanel, "growx"); // NON-NLS
setLayout(new MigLayout("insets dialog, fill")); // NON-NLS
add(panel, "grow"); // NON-NLS
SwingUtils.repack(this);
}
private static void checkSearchTarget(SearchTarget target, List<Object[]> list) {
final List<NamedKeyStroke> keys = target.getNamedKeyStrokeList();
if (keys != null) {
for (final NamedKeyStroke k : keys) {
if (k != null) {
String cmd_key = null;
String cmd_name = null;
if (k.isNamed()) {
cmd_name = k.getName();
}
else {
cmd_key = KeyNamer.getKeyString(k.getStroke());
}
if (!StringUtils.isEmpty(cmd_key) || !StringUtils.isEmpty(cmd_name)) { // Could check a filter here?
String src_name = null;
String src_desc = null;
if (target instanceof AbstractConfigurable) {
src_name = ((AbstractConfigurable)target).getConfigureName();
}
else if (target instanceof GamePiece) {
src_name = ((GamePiece)target).getName();
if (target instanceof Decorator) {
src_desc = ((Decorator) target).getDescription();
}
}
list.add(new Object[] { cmd_key, cmd_name, src_name, src_desc });
}
}
}
}
}
private static void checkForKeyCommands(AbstractConfigurable target, List<Object[]> list) {
GamePiece p;
boolean protoskip;
if (target instanceof GamePiece) {
p = (GamePiece) target;
protoskip = false;
}
else if (target instanceof PieceSlot) {
p = ((PieceSlot)target).getPiece();
protoskip = false;
}
else if (target instanceof PrototypeDefinition) {
p = ((PrototypeDefinition)target).getPiece();
protoskip = true;
}
else {
checkSearchTarget(target, list);
return;
}
// We're going to search Decorator from inner-to-outer (BasicPiece-on-out), so that user sees the traits hit in
// the same order they're listed in the PieceDefiner window. So we first traverse them in the "normal" direction
// outer to inner and make a list in the order we want to traverse it (for architectural reasons, just traversing
// with getOuter() would take us inside of prototypes inside a piece, which we don't want).
final List<GamePiece> pieces = new ArrayList<>();
pieces.add(p);
while (p instanceof Decorator) {
p = ((Decorator) p).getInner();
pieces.add(p);
}
Collections.reverse(pieces);
for (final GamePiece piece : pieces) {
if (!protoskip) { // Skip the fake "Basic Piece" on a Prototype definition
if (piece instanceof SearchTarget) {
checkSearchTarget((SearchTarget)piece, list);
}
}
protoskip = false;
}
}
private static void recursivelyFindKeyCommands(AbstractBuildable target, List<Object[]> list) {
for (final Buildable b : target.getBuildables()) {
if (b instanceof AbstractConfigurable) {
checkForKeyCommands((AbstractConfigurable)b, list);
}
if (b instanceof AbstractBuildable) {
recursivelyFindKeyCommands((AbstractBuildable)b, list);
}
}
}
public static List<Object[]> findAllKeyCommands() {
final List<Object[]> keyCommandList = new ArrayList<>();
recursivelyFindKeyCommands(GameModule.getGameModule(), keyCommandList);
return keyCommandList;
}
private void help() {
HelpFile hf = null;
try {
hf = new HelpFile(null, new File(
new File(Documentation.getDocumentationBaseDir(), "ReferenceManual"),
"ListKeyCommands.html"));
}
catch (MalformedURLException ex) {
ErrorDialog.bug(ex);
}
(new ShowHelpAction(hf.getContents(), null)).actionPerformed(null);
}
}
|
package br.sp.unifae.cris.comp7.view;
import javax.swing.JFrame;
/**
*
* @author iury
*/
public class JanelaPrincipal extends javax.swing.JFrame {
/**
* Creates new form JanelaPrincipal
*/
public JanelaPrincipal() {
initComponents();
personalizacao();
}
private void personalizacao(){
this.setLocationRelativeTo(null);
this.setTitle("Loja de Games Iury");
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jMenuBar1 = new javax.swing.JMenuBar();
jMenu1 = new javax.swing.JMenu();
jMenuItem1 = new javax.swing.JMenuItem();
jMenuItem2 = new javax.swing.JMenuItem();
jMenu2 = new javax.swing.JMenu();
jMenuItem3 = new javax.swing.JMenuItem();
jMenuItem4 = new javax.swing.JMenuItem();
jMenu3 = new javax.swing.JMenu();
jMenuItem5 = new javax.swing.JMenuItem();
jMenuItem6 = new javax.swing.JMenuItem();
jMenu4 = new javax.swing.JMenu();
jMenuItem9 = new javax.swing.JMenuItem();
jMenuItem8 = new javax.swing.JMenuItem();
jMenuItem7 = new javax.swing.JMenuItem();
jMenu5 = new javax.swing.JMenu();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/sp/unifae/cris/comp7/utils/imagens/pdt_img_6657(2).jpg"))); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
);
jMenu1.setText("Iniciar");
jMenuItem1.setText("Configurações");
jMenuItem1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem1ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem1);
jMenuItem2.setText("Sair");
jMenuItem2.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem2ActionPerformed(evt);
}
});
jMenu1.add(jMenuItem2);
jMenuBar1.add(jMenu1);
jMenu2.setText("Manutenção");
jMenuItem3.setText("Venda");
jMenuItem3.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem3ActionPerformed(evt);
}
});
jMenu2.add(jMenuItem3);
jMenuItem4.setText("Entrada de Estoque");
jMenuItem4.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem4ActionPerformed(evt);
}
});
jMenu2.add(jMenuItem4);
jMenuBar1.add(jMenu2);
jMenu3.setText("Relatórios");
jMenuItem5.setText("Vendas de Produtos");
jMenu3.add(jMenuItem5);
jMenuItem6.setText("Entrada de Estoque");
jMenu3.add(jMenuItem6);
jMenuBar1.add(jMenu3);
jMenu4.setText("Tabelas");
jMenuItem9.setText("Fornecedores");
jMenuItem9.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem9ActionPerformed(evt);
}
});
jMenu4.add(jMenuItem9);
jMenuItem8.setText("Clientes");
jMenuItem8.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem8ActionPerformed(evt);
}
});
jMenu4.add(jMenuItem8);
jMenuItem7.setText("Produtos");
jMenuItem7.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenuItem7ActionPerformed(evt);
}
});
jMenu4.add(jMenuItem7);
jMenuBar1.add(jMenu4);
jMenu5.setText("Sobre");
jMenu5.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jMenu5ActionPerformed(evt);
}
});
jMenuBar1.add(jMenu5);
setJMenuBar(jMenuBar1);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed
System.exit(0);
}//GEN-LAST:event_jMenuItem2ActionPerformed
private void jMenuItem9ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem9ActionPerformed
new CadastroFornecedor2().setVisible(true);
}//GEN-LAST:event_jMenuItem9ActionPerformed
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem1ActionPerformed
new IniciarConfiguracoes().setVisible(true);
}//GEN-LAST:event_jMenuItem1ActionPerformed
private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed
new ManutencaoVenda().setVisible(true);
}//GEN-LAST:event_jMenuItem3ActionPerformed
private void jMenuItem4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem4ActionPerformed
new ManutencaoEntradaEstoque2();
}//GEN-LAST:event_jMenuItem4ActionPerformed
private void jMenuItem8ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem8ActionPerformed
new CadastroCliente2().setVisible(true);
}//GEN-LAST:event_jMenuItem8ActionPerformed
private void jMenuItem7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem7ActionPerformed
new CadastroProduto2();
}//GEN-LAST:event_jMenuItem7ActionPerformed
private void jMenu5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenu5ActionPerformed
new Sobre().setVisible(true);
}//GEN-LAST:event_jMenu5ActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JLabel jLabel1;
private javax.swing.JMenu jMenu1;
private javax.swing.JMenu jMenu2;
private javax.swing.JMenu jMenu3;
private javax.swing.JMenu jMenu4;
private javax.swing.JMenu jMenu5;
private javax.swing.JMenuBar jMenuBar1;
private javax.swing.JMenuItem jMenuItem1;
private javax.swing.JMenuItem jMenuItem2;
private javax.swing.JMenuItem jMenuItem3;
private javax.swing.JMenuItem jMenuItem4;
private javax.swing.JMenuItem jMenuItem5;
private javax.swing.JMenuItem jMenuItem6;
private javax.swing.JMenuItem jMenuItem7;
private javax.swing.JMenuItem jMenuItem8;
private javax.swing.JMenuItem jMenuItem9;
private javax.swing.JPanel jPanel1;
// End of variables declaration//GEN-END:variables
}
|
package cl.cc.main;
import org.bytedeco.javacpp.Loader;
import static org.bytedeco.javacpp.helper.opencv_objdetect.cvHaarDetectObjects;
import static org.bytedeco.javacpp.opencv_core.CV_AA;
import org.bytedeco.javacpp.opencv_core.CvMemStorage;
import org.bytedeco.javacpp.opencv_core.CvPoint;
import org.bytedeco.javacpp.opencv_core.CvRect;
import org.bytedeco.javacpp.opencv_core.CvScalar;
import org.bytedeco.javacpp.opencv_core.CvSeq;
import static org.bytedeco.javacpp.opencv_core.IPL_DEPTH_8U;
import org.bytedeco.javacpp.opencv_core.IplImage;
import static org.bytedeco.javacpp.opencv_core.cvClearMemStorage;
import static org.bytedeco.javacpp.opencv_core.cvFillConvexPoly;
import static org.bytedeco.javacpp.opencv_core.cvGetSeqElem;
import static org.bytedeco.javacpp.opencv_core.cvLoad;
import static org.bytedeco.javacpp.opencv_core.cvPoint;
import static org.bytedeco.javacpp.opencv_core.cvRectangle;
import static org.bytedeco.javacpp.opencv_imgproc.CV_BGR2GRAY;
import static org.bytedeco.javacpp.opencv_imgproc.cvCvtColor;
import org.bytedeco.javacpp.opencv_objdetect;
import static org.bytedeco.javacpp.opencv_objdetect.CV_HAAR_DO_CANNY_PRUNING;
import org.bytedeco.javacpp.opencv_objdetect.CvHaarClassifierCascade;
import org.bytedeco.javacv.CanvasFrame;
import org.bytedeco.javacv.FrameGrabber;
public class Run {
public static void main(String[] args) throws Exception {
String classifierName = "/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml";
// Preload the opencv_objdetect module to work around a known bug.
Loader.load(opencv_objdetect.class);
// We can "cast" Pointer objects by instantiating a new object of the desired class.
CvHaarClassifierCascade classifier = new CvHaarClassifierCascade(cvLoad(classifierName));
if (classifier.isNull()) {
System.err.println("Error loading classifier file \"" + classifierName + "\".");
System.exit(1);
}
// The available FrameGrabber classes include OpenCVFrameGrabber (opencv_highgui),
// DC1394FrameGrabber, FlyCaptureFrameGrabber, OpenKinectFrameGrabber,
// PS3EyeFrameGrabber, VideoInputFrameGrabber, and FFmpegFrameGrabber.
FrameGrabber grabber = FrameGrabber.createDefault(0);
grabber.setImageHeight(480);
grabber.setImageWidth(720);
grabber.start();
// FAQ about IplImage:
// - For custom raw processing of data, getByteBuffer() returns an NIO direct
// buffer wrapped around the memory pointed by imageData, and under Android we can
// also use that Buffer with Bitmap.copyPixelsFromBuffer() and copyPixelsToBuffer().
// - To get a BufferedImage from an IplImage, we may call getBufferedImage().
// - The createFrom() factory method can construct an IplImage from a BufferedImage.
// - There are also a few copy*() methods for BufferedImage<->IplImage data transfers.
IplImage grabbedImage = grabber.grab();
int width = grabbedImage.width();
int height = grabbedImage.height();
IplImage grayImage = IplImage.create(width, height, IPL_DEPTH_8U, 1);
// Objects allocated with a create*() or clone() factory method are automatically released
// by the garbage collector, but may still be explicitly released by calling release().
// You shall NOT call cvReleaseImage(), cvReleaseMemStorage(), etc. on objects allocated this way.
CvMemStorage storage = CvMemStorage.create();
// CanvasFrame is a JFrame containing a Canvas component, which is hardware accelerated.
// It can also switch into full-screen mode when called with a screenNumber.
// We should also specify the relative monitor/camera response for proper gamma correction.
CanvasFrame frame = new CanvasFrame("Sonria!!!!!! :-)", CanvasFrame.getDefaultGamma() / grabber.getGamma());
// We can allocate native arrays using constructors taking an integer as argument.
CvPoint hatPoints = new CvPoint(3);
while (frame.isVisible() && (grabbedImage = grabber.grab()) != null) {
cvClearMemStorage(storage);
// Let's try to detect some faces! but we need a grayscale image...
cvCvtColor(grabbedImage, grayImage, CV_BGR2GRAY);
CvSeq faces = cvHaarDetectObjects(grayImage, classifier, storage,
1.1, 3, CV_HAAR_DO_CANNY_PRUNING);
int total = faces.total();
for (int i = 0; i < total; i++) {
CvRect r = new CvRect(cvGetSeqElem(faces, i));
int x = r.x(), y = r.y(), w = r.width(), h = r.height();
cvRectangle(grabbedImage, cvPoint(x, y), cvPoint(x + w, y + h), CvScalar.RED, 1, CV_AA, 0);
// To access or pass as argument the elements of a native array, call position() before.
hatPoints.position(0).x(x - w / 10).y(y - h / 10);
hatPoints.position(1).x(x + w * 11 / 10).y(y - h / 10);
hatPoints.position(2).x(x + w / 2).y(y - h / 2);
cvFillConvexPoly(grabbedImage, hatPoints.position(0), 3, CvScalar.GREEN, CV_AA, 0);
}
frame.showImage(grabbedImage);
}
frame.dispose();
grabber.stop();
}
}
|
package ca.uwaterloo.joos.ast.visitor;
import ca.uwaterloo.joos.ast.ASTNode;
import ca.uwaterloo.joos.ast.decl.BodyDeclaration;
import ca.uwaterloo.joos.ast.decl.ClassDeclaration;
import ca.uwaterloo.joos.ast.decl.FieldDeclaration;
import ca.uwaterloo.joos.ast.decl.MethodDeclaration;
import ca.uwaterloo.joos.ast.decl.PackageDeclaration;
import ca.uwaterloo.joos.symbolTable.SymbolTable;
public class TopDeclVisitor extends SemanticsVisitor {
private String name = null;
public TopDeclVisitor(SymbolTable st) {
super(st);
}
public boolean visit(ASTNode node) throws Exception {
// TODO: Interface Declaration
if (node instanceof PackageDeclaration) {
PackageDeclaration PNode = (PackageDeclaration) node;
name = PNode.getPackageName();
st.setName(name);
} else if (node instanceof ClassDeclaration) {
// TODO: check if class has already been defined
String tname = ((ClassDeclaration) node).getIdentifier();
st.setName(st.getName() + "." + tname + "{}");
// Adds the current symbol table to the static symbol table map
st.addScope();
st.addClass(st.getName() + "." + tname, node);
} else if (node instanceof FieldDeclaration) {
String key = this.st.getName() + "." + ((FieldDeclaration) node).getName().getName();
if (!st.hasField(key))
st.addField(key, node);
else {
System.err.println("TopDeclVisitor.visit(): Multiple Field Declarations with same name. Exiting with 42");
System.exit(42);
}
} else if (node instanceof MethodDeclaration) {
// TODO: check signatures
String key = this.st.getName() + "." + ((MethodDeclaration) node).getName().getName();
if (!st.hasMethod(key))
st.addMethod(key, node);
}
return !(node instanceof BodyDeclaration);
}
@Override
public void willVisit(ASTNode node) {
}
@Override
public void didVisit(ASTNode node) {
}
}
|
package com.axelby.podax;
import android.bluetooth.BluetoothClass;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
// catch all of our Bluetooth events
public class BluetoothConnectionReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
// If we're not stopping when headphones disconnect, don't worry about it
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
if (!prefs.getBoolean("stopOnBluetoothPref", true))
return;
// Figure out what kind of device it is
BluetoothDevice btDevice = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
// make sure bluetooth device has a class
if (btDevice.getBluetoothClass() == null)
return;
// pause if it's headphones
if (btDevice.getBluetoothClass().getMajorDeviceClass() == BluetoothClass.Device.Major.AUDIO_VIDEO)
PlayerService.stop(context);
}
}
|
package com.coderdojo.libretalk;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.io.StreamCorruptedException;
import com.google.gson.Gson;
import android.graphics.Color;
import android.util.Log;
public final class LibretalkMessageData implements Serializable
{
/**
* [!] AUTO GENERATED DO NOT MODIFY
*/
//private static final long serialVersionUID = 2649285673568863822L;
@SuppressWarnings("unused")
private static final byte CLASS_VERSION = 0x01;
private final String data;
private final String senderTag;
public LibretalkMessageData(final String senderTag, final String message)
{
this.senderTag = senderTag;
this.data = message;
}
public static final int getColorFromString(final String s)
{
String str = s.substring(1, 2);
Log.d("libretalk::LibretalkMessageData", "Original String: " + s);
Log.d("libretalk::LibretalkMessageData", "Substring: " + str);
String[] colours = {"#9EB08E", "#9E8EB0", "#AB2E2E", "#C0FF00", "#FFACAC",
"#699FF0", "#69F0E7", "#FCD04D", "#FCED4D", "#217989", "#892121",
"#FF0000", "#2600FF", "#00FF26", "#FCFF00", "#FFF886", "#D5720F",
"#B5DC8E", "#8EDCD3", "#4A6CC3", "#CE13DF", "#2B6F9D", "#75E5DE",
"#51C121", "#EC5A32", "#5C4BDC"};
char[] alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray();
int index = 0;
for(int i = 0; i < alphabet.length; i++){
if(str.equalsIgnoreCase(Character.toString(alphabet[i]))){
Log.d("libretalk::LibretalkMessageData", "Match found at index: " + index);
index = i;
}
}
Log.d("libretalk::LibretalkMessageData", "Colour Index: " + index);
Log.d("libretalk::LibretalkMessageData", "Colour: " + colours[index]);
return Color.parseColor(colours[index]);
}
public String getSenderTag()
{
return senderTag;
}
public String getData()
{
return data;
}
public static final String serialize(final LibretalkMessageData msg)
{
Gson gson = new Gson();
return gson.toJson(msg);
}
public static final LibretalkMessageData deserialize(final String json)
{
Gson gson = new Gson();
return gson.fromJson(json, LibretalkMessageData.class);
}
@Override
public final String toString()
{
return "LibretalkMessage#" + senderTag + "->{" + data + "}_COLOR(" + getColorFromString(senderTag) + ")";
}
}
|
package com.debortoliwines.openerp.api;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import org.apache.xmlrpc.XmlRpcException;
import com.debortoliwines.openerp.api.Field.FieldType;
import com.debortoliwines.openerp.api.FilterCollection.FilterOperator;
import com.debortoliwines.openerp.api.helpers.FilterHelper;
/**
* Main class for communicating with the server. It provides extra validation for making calls to the OpenERP server. It converts data types, validates model names, validates filters, checks for nulls etc.
* @author Pieter van der Merwe
*
*/
public class ObjectAdapter {
private final String objectName;
private final OpenERPCommand commands;
private final FieldCollection allFields;
private final Version server_version;
// Object name cache so the adapter doesn't have to reread model names from the database for every new object.
// Bulk loads/reads can become very slow if every adapter requires a call back to the server
private static ArrayList<String> objectNameCache = new ArrayList<String>();
// Object workflow signal cache so the adapter doesn't have to reread signal names from the database for every workflow call.
private static ArrayList<String> signalCache = new ArrayList<String>();
// Cache used to store the name_get result of an model to cater for many2many relations in the import function
// It is cleared every time the import function is called for a specific object
private HashMap<String, HashMap<String, String>> modelNameCache = new HashMap<String, HashMap<String, String>>();
/**
* Default constructor
* @param session Session object that will be used to make the calls
* @param objectName Object name that this adapter will work for.
* @throws XmlRpcException
* @throws OpeneERPApiException
*/
public ObjectAdapter(Session session, String objectName) throws XmlRpcException, OpeneERPApiException{
this.commands = session.getOpenERPCommand();
this.objectName = objectName;
this.server_version = session.getServerVersion();
objectExists(this.commands, this.objectName);
allFields = this.getFields();
}
/**
* Validates a model name against entries in ir.model
* The function is synchronized to make use of a global (static) list of objects to increase speed
* @param commands Command object to use
* @param objectName Object name that needs to be validated
* @throws OpeneERPApiException If the model could not be validated
*/
@SuppressWarnings("unchecked")
private synchronized static void objectExists(OpenERPCommand commands, String objectName) throws OpeneERPApiException{
// If you can't find the object name, reload the cache. Somebody may have added a new module after the cache was created
// Ticket #1 from sourceforge
if (objectNameCache.indexOf(objectName) < 0){
objectNameCache.clear();
try{
Object[] ids = commands.searchObject("ir.model", new Object[]{});
Object [] result = commands.readObject("ir.model", ids, new String[]{"model"});
for (Object row : result){
objectNameCache.add(((HashMap<String, Object>) row).get("model").toString());
}
}
catch (XmlRpcException e){
throw new OpeneERPApiException("Could not validate model name: ",e);
}
}
if (objectNameCache.indexOf(objectName) < 0)
throw new OpeneERPApiException("Could not find model with name '" + objectName + "'");
}
@SuppressWarnings("unchecked")
private synchronized static void signalExists(OpenERPCommand commands, String objectName, String signal) throws OpeneERPApiException{
// If you can't find the signal, reload the cache. Somebody may have added a new module after the cache was created
// Ticket #1 from sourceforge
String signalCombo = objectName + "#" + signal;
if (signalCache.indexOf(signalCombo) < 0){
signalCache.clear();
try{
Object[] ids = commands.searchObject("workflow.transition", new Object[]{});
Object [] result = commands.readObject("workflow.transition", ids, new String[]{"signal","wkf_id"});
for (Object row : result){
/* Get the parent workflow to work out get the object name */
int wkf_id = Integer.parseInt(((Object[]) ((HashMap<String, Object>) row).get("wkf_id"))[0].toString());
Object [] workflow = commands.readObject("workflow", new Object[] {wkf_id}, new String[] {"osv"});
String obj = ((HashMap<String, Object>) workflow[0]).get("osv").toString();
String sig = ((HashMap<String, Object>) row).get("signal").toString();
signalCache.add(obj + "#" + sig);
}
}
catch (XmlRpcException e){
throw new OpeneERPApiException("Could not validate signal name: ", e);
}
}
if (signalCache.indexOf(signalCombo) < 0)
throw new OpeneERPApiException("Could not find signal with name '" + signal + "' for object '" + objectName + "'");
}
/**
* Prepares a ROW object to be used for setting values in import/write methods
* @param fields Fields that should be included in the row definition
* @return An empty row with the specified fields
* @throws XmlRpcException
* @throws OpeneERPApiException
*/
public Row getNewRow(FieldCollection fields) throws XmlRpcException, OpeneERPApiException{
Row row = new Row(new HashMap<String, Object>(), fields);
return row;
}
/**
* Prepares a ROW object to be used for setting values in import/write methods.
* This method calls to the server to get the fieldCollection. Use getNewRow(FieldCollection fields)
* if you can to reduce the number of calls to the server for a bulk load.
* @param fields Fields that should be included in the row definition
* @return An empty row with the specified fields
* @throws XmlRpcException
* @throws OpeneERPApiException
*/
public Row getNewRow(String [] fields) throws XmlRpcException, OpeneERPApiException{
FieldCollection fieldCol = getFields(fields);
Row row = new Row(new HashMap<String, Object>(), fieldCol);
return row;
}
/**
* Reads objects from the OpenERP server if you already have the ID's. If you don't, use searchAndRead with filters.
* @param ids List of ids to fetch objects for
* @param fields List of fields to fetch data for
* @return A collection of rows for an OpenERP object
* @throws XmlRpcException
* @throws OpeneERPApiException
*/
public RowCollection readObject(Object [] ids, String [] fields) throws XmlRpcException, OpeneERPApiException {
// Faster to do read existing fields that to do a server call again
FieldCollection fieldCol = new FieldCollection();
for (String fieldName : fields){
for (Field fld : allFields){
if (fld.getName().equals(fieldName)){
fieldCol.add(fld);
}
}
}
Object[] results = commands.readObject(objectName, ids, fields);
RowCollection rows = new RowCollection(results, fieldCol);
return rows;
}
/***
* Fetches field information for the current OpenERP object this adapter is linked to
* @return FieldCollecton data for all fields of the object
* @throws XmlRpcException
*/
public FieldCollection getFields() throws XmlRpcException {
return this.getFields(new String[] {});
}
/***
* Fetches field names for the current OpenERP object this adapter is linked to
* @return Array of field names
* @throws XmlRpcException
*/
public String [] getFieldNames() throws XmlRpcException {
FieldCollection fields = getFields(new String[] {});
String [] fieldNames = new String[fields.size()];
for (int i = 0; i < fields.size(); i++)
fieldNames[i] = fields.get(i).getName();
return fieldNames;
}
/***
* Fetches field information for the current OpenERP object this adapter is linked to
* @param filterFields Only return data for files in the filter list
* @return FieldCollecton data for selected fields of the object
* @throws XmlRpcException
*/
@SuppressWarnings("unchecked")
public FieldCollection getFields(String[] filterFields) throws XmlRpcException {
FieldCollection collection = new FieldCollection();
HashMap<String, Object> fields = commands.getFields(objectName,filterFields);
for (String fieldName: fields.keySet()){
HashMap<String, Object> fieldDetails = (HashMap<String, Object>) fields.get(fieldName);
collection.add(new Field(fieldName, fieldDetails));
}
return collection;
}
/**
* Helper function to validate filter parameters and returns a filter object suitable
* for the OpenERP search function by fixing data types and converting values where appropriate.
* @param filters FilterCollection containing the specified filters
* @return A validated filter Object[] correctly formatted for use by the OpenERP search function
* @throws OpeneERPApiException
*/
public Object[] validateFilters(final FilterCollection filters) throws OpeneERPApiException{
if (filters == null)
return new Object[0];
ArrayList<Object> processedFilters = new ArrayList<Object>();
for (int i = 0; i < filters.getFilters().length; i++){
Object filter = filters.getFilters()[i];
if (filter == null)
throw new OpeneERPApiException("The first filter parameter is mandatory");
// Is a logical operator
if (filter instanceof String){
String operator = filter.toString();
if (operator.equals(FilterOperator.AND))
continue;
// OR must have two parameters following
if (operator.equals(FilterOperator.OR))
if (filters.getFilters().length <= i + 2)
throw new OpeneERPApiException("Logical operator OR needs two parameters. Please read the OpenERP help.");
// NOT must have one parameter following
if (operator.equals(FilterOperator.NOT))
if (filters.getFilters().length <= i + 1)
throw new OpeneERPApiException("Logical operator NOT needs one parameter. Please read the OpenERP help.");
processedFilters.add(operator);
continue;
}
if (!(filter instanceof Object[]) && ((Object[])filter).length != 3)
throw new OpeneERPApiException("Filters aren't in the correct format. Please read the OpenERP help.");
String fieldName = ((Object[])filter)[0].toString();
String comparison = ((Object[])filter)[1].toString();
Object value = ((Object[])filter)[2];
Field fld = null;
for (int j = 0; j < allFields.size(); j++){
if (allFields.get(j).getName().equals(fieldName)){
fld = allFields.get(j);
break;
}
}
// Can't search on calculated fields
if (fld != null && fld.getFunc_method() == true)
throw new OpeneERPApiException("Can not search on function field " + fieldName);
// Fix the value type if required for the OpenERP server
if (!fieldName.equals("id") && fld == null)
throw new OpeneERPApiException("Unknow filter field " + fieldName);
else if (comparison.equals("is null")){
comparison = "=";
value = false;
}
else if (comparison.equals("is not null")){
comparison = "!=";
value = false;
}
else if (fld != null && fld.getType() == FieldType.BOOLEAN && !(value instanceof Boolean)){
if (value instanceof String){
char firstchar = value.toString().toLowerCase().charAt(0);
if (firstchar == '1' || firstchar == 'y' || firstchar == 't')
value = true;
else if (firstchar == '0' || firstchar == 'n' || firstchar == 'f')
value = false;
else throw new OpeneERPApiException ("Unknown boolean " + value.toString());
}
}
else if (fld != null && fld.getType() == FieldType.FLOAT && !(value instanceof Double) )
value = Double.parseDouble(value.toString());
else if (comparison.equals("=")){
// If a integer field is not an integer in a '=' comparison, parse it as an int
if (!(value instanceof Integer)){
if (fieldName.equals("id") ||
(fld != null && fld.getType() == FieldType.INTEGER && !(value instanceof Integer)) ||
(fld != null && fld.getType() == FieldType.MANY2ONE && !(value instanceof Integer))){
value = Integer.parseInt(value.toString());
}
}
}
else if (comparison.equalsIgnoreCase("in")){
if (value instanceof String){
// Split by , where the , isn't preceded by a \
String [] entries = value.toString().split("(?<!\\\\),");
Object [] valueArr = new Object[entries.length];
for (int entrIdx = 0; entrIdx < entries.length; entrIdx++){
String entry = FilterHelper.csvDecodeString(entries[entrIdx]);
// For relation fields or integer fields we build an array of integers
if (fld != null
&& (fld.getType() == FieldType.INTEGER
|| fld.getType() == FieldType.ONE2MANY
|| fld.getType() == FieldType.MANY2MANY
|| fld.getType() == FieldType.MANY2ONE)
|| fieldName.equals("id")){
valueArr[entrIdx] = Integer.parseInt(entry);
}
else valueArr[entrIdx] = entry;
}
value = valueArr;
}
// If it is a single value, just put it in an array
else if (!(value instanceof Object[])){
value = new Object[]{value};
}
}
processedFilters.add(new Object[] {fieldName,comparison,value});
}
return processedFilters.toArray(new Object[processedFilters.size()]);
}
private Object[] fixImportData(Row inputRow) throws OpeneERPApiException, XmlRpcException {
// +1 because we need to include the ID field
Object[] outputRow = new Object[inputRow.getFields().size() + 1];
// ID must be an integer
outputRow[0] = inputRow.get("id");
if (outputRow[0] == null)
outputRow[0] = 0;
else
outputRow[0] = Integer.parseInt(inputRow.get("id").toString());
for (int i = 0; i < inputRow.getFields().size(); i++){
int columnIndex = i + 1;
Field fld = inputRow.getFields().get(i);
String fieldName = fld.getName();
Object value = inputRow.get(fieldName);
outputRow[columnIndex] = value;
if (fld.getType() == FieldType.MANY2ONE){
if (value == null)
outputRow[columnIndex] = 0;
else
outputRow[columnIndex] = Integer.parseInt(value.toString());
continue;
}
// Null values must be false
if (value == null){
outputRow[columnIndex] = false;
continue;
}
value = formatValueForWrite(fld, value);
// Check types
switch (fld.getType()) {
case SELECTION:
boolean validValue = false;
for (SelectionOption option : fld.getSelectionOptions()){
// If the database code was specified, replace it with the value.
// The import procedure uses the value and not the code
if (option.code.equals(value.toString())){
validValue = true;
outputRow[columnIndex] = option.value;
break;
}
else if (option.value.equals(value.toString())){
outputRow[columnIndex] = value;
validValue = true;
break;
}
}
if (!validValue)
throw new OpeneERPApiException("Could not find a valid value for section field " + fieldName + " with value " + value);
break;
case MANY2MANY:
/* The import function uses the Names of the objects for the import. Replace the ID list passed
* in with a Name list for the import_data function that we are about to call
*/
HashMap<String, String> idToName = null;
if (!modelNameCache.containsKey(fld.getRelation())){
idToName = new HashMap<String, String>();
Object [] ids = commands.searchObject(fld.getRelation(), new Object[]{});
Object[] names = commands.nameGet(fld.getRelation(), ids);
for (int j = 0; j < ids.length; j++){
Object [] nameValue = (Object [])names[j];
idToName.put(nameValue[0].toString(), nameValue[1].toString());
}
modelNameCache.put(fld.getRelation(), idToName);
}
else idToName = modelNameCache.get(fld.getRelation());
String newValue = "";
// Comma separated list of IDs
if (value instanceof String){
for (String singleID : value.toString().split(","))
if (idToName.containsKey(singleID))
newValue = newValue + "," + idToName.get(singleID);
else throw new OpeneERPApiException("Could not find " + fld.getRelation() + " with ID " + singleID);
}
else {
// Object[] of values -- default
for (Object singleID : (Object[]) value)
if (idToName.containsKey(singleID.toString()))
newValue = newValue + "," + idToName.get(singleID.toString());
else throw new OpeneERPApiException("Could not find " + fld.getRelation() + " with ID " + singleID.toString());
}
outputRow[columnIndex] = newValue.substring(1);
break;
// The import procedure expects most types to be strings
default:
outputRow[columnIndex] = value.toString();
break;
}
}
return outputRow;
}
private String[] getFieldListForImport(FieldCollection currentFields) {
ArrayList<String> fieldList = new ArrayList<String>();
fieldList.add(".id");
for (Field field : currentFields){
if (field.getType() == FieldType.MANY2ONE)
fieldList.add(field.getName() + ".id");
else
fieldList.add(field.getName());
}
return fieldList.toArray(new String[fieldList.size()]);
}
/**
* Calls the import_data or load function on the server to bulk create/update records.
*
* The import_data function will be called on OpenERP servers where the version number is < 7.
* The import_data function does not return IDs and therefore IDs will not be set on imported rows.
*
* The load function will be called for V7 and the IDs will be set on the imported rows.
* The load function was introduced in V7 and the import_data function deprecated.
*
* @param rows Rows to import.
* @return If the import was successful
* @throws XmlRpcException
* @throws OpeneERPApiException
*/
@SuppressWarnings("unchecked")
public boolean importData(RowCollection rows) throws OpeneERPApiException, XmlRpcException {
// Workaround. OpenERP7 bug where old and new rows can't be sent together using the import_data or load function
if (this.server_version.getMajor() >= 7 && this.server_version.getMinor() == 0){
RowCollection newRows = new RowCollection();
RowCollection oldRows = new RowCollection();
for (int i = 0; i < rows.size(); i++){
if (rows.get(i).getID() == 0)
newRows.add(rows.get(i));
else oldRows.add(rows.get(i));
}
// If mixed rows, import old and new rows separately
if (newRows.size() != 0 && oldRows.size() != 0){
return this.importData(oldRows) && this.importData(newRows);
}
}
modelNameCache.clear();
String[] targetFieldList = getFieldListForImport(rows.get(0).getFields());
Object[][] importRows = new Object[rows.size()][];
for (int i = 0; i < rows.size(); i++){
Row row = rows.get(i);
importRows[i] = fixImportData(row);
}
// The load function was introduced in V7 and the import function deprecated
if (this.server_version.getMajor() >= 7){
// Workaround OpenERP V7 bug. Remove the .id field for new rows.
if (this.server_version.getMinor() == 0 && rows.size() > 0 && rows.get(0).getID() == 0){
String[] newTargetFieldList = new String[targetFieldList.length - 1];
for (int i = 1; i < targetFieldList.length; i++){
newTargetFieldList[i - 1] = targetFieldList[i];
}
targetFieldList = newTargetFieldList;
Object[][] newImportRows = new Object[rows.size()][];
for (int i = 0; i < importRows.length; i++){
Object[] newRow = new Object[importRows[i].length - 1];
for (int j = 1; j < importRows[i].length; j++){
newRow[j - 1] = importRows[i][j];
}
newImportRows[i] = newRow;
}
importRows = newImportRows;
}
HashMap<String, Object> results = commands.Load(objectName, targetFieldList, importRows);
// There was an error. ids is false and not an Object[]
if (results.get("ids") instanceof Boolean){
StringBuilder errorString = new StringBuilder();
Object [] messages = (Object[]) results.get("messages");
for (Object mes : messages){
HashMap<String, Object> messageHash = (HashMap<String, Object>) mes;
errorString.append("Row: " + messageHash.get("record").toString()
+ " field: " + messageHash.get("field").toString()
+ " ERROR: " + messageHash.get("message").toString() + "\n");
}
throw new OpeneERPApiException(errorString.toString());
}
// Should be in the same order as it was passed in
Object[] ids = (Object[]) results.get("ids");
for (int i = 0; i < rows.size(); i++){
Row row = rows.get(i);
row.put("id", ids[i]);
}
}
else{ // Use older import rows function
Object [] result = commands.importData(objectName, targetFieldList, importRows);
// Should return the number of rows committed. If there was an error, it returns -1
if ((Integer) result[0] != importRows.length)
throw new OpeneERPApiException(result[2].toString() + "\nRow :" + result[1].toString() + "");
}
return true;
}
/**
* Gets the number of records that satisfies the filter
* @param filter A filter collection that contains a list of filters to be applied
* @return The number of record count.
* @throws XmlRpcException
* @throws OpeneERPApiException
*/
public int getObjectCount(FilterCollection filter) throws XmlRpcException, OpeneERPApiException {
Object[] preparedFilters = validateFilters(filter);
return Integer.parseInt(commands.searchObject(objectName,preparedFilters, -1, -1, null, true).toString());
}
/***
* Combines the searchObject and readObject calls. Allows for easy read of all data
* @param filter A filter collection that contains a list of filters to be applied
* @param fields List of fields to return data for
* @return A collection of rows for an OpenERP object
* @throws XmlRpcException
* @throws OpeneERPApiException
*/
public RowCollection searchAndReadObject(FilterCollection filter, String [] fields) throws XmlRpcException, OpeneERPApiException {
return searchAndReadObject(filter,fields,-1,-1,"");
}
/**
* Combines the searchObject and readObject calls and returns rows in batches. Useful for multi-threaded ETL applications.
* @param filter A filter collection that contains a list of filters to be applied
* @param fields List of fields to return data for
* @param offset Number of records to skip. -1 for no offset.
* @param limit Maximum number of rows to return. -1 for no limit.
* @param order Field name to order on
* @return A collection of rows for an OpenERP object
* @throws XmlRpcException
* @throws OpeneERPApiException
*/
public RowCollection searchAndReadObject(final FilterCollection filter, final String[] fields, int offset, int limit, String order) throws XmlRpcException, OpeneERPApiException {
String[] fieldArray = (fields == null ? new String[]{} : fields);
Object[] preparedFilters = validateFilters(filter);
Object[] idList = (Object[]) commands.searchObject(objectName,preparedFilters, offset, limit, order, false);
return readObject(idList,fieldArray);
}
private Object formatValueForWrite(Field fld, Object value){
if (value == null)
return false;
switch (fld.getType()) {
case BOOLEAN:
value = (Boolean) value;
break;
case FLOAT:
value = Double.parseDouble(value.toString());
break;
case MANY2ONE:
value = Double.valueOf(value.toString()).intValue();
break;
case MANY2MANY:
// For write, otherwise it is a comma separated list of strings used by import
if (value instanceof Object[])
value = new Object [][]{new Object[] {6,0, (Object[]) value}};
break;
case ONE2MANY:
case INTEGER:
// To make sure 1.0 is converted to 1
value = Double.valueOf(value.toString()).intValue();
break;
default:
value = value.toString();
break;
}
return value;
}
/**
* Writes a collection of rows to the database by calling the write function on the object the Row is holding data for
* @param rows Row collection to submit
* @param changesOnly Only changed values will be submitted to the database.
* @return An array of logicals. One for each row to indicate if the update was successful
* @throws OpeneERPApiException
* @throws XmlRpcException
*/
public Boolean[] writeObject(final RowCollection rows, final boolean changesOnly) throws OpeneERPApiException, XmlRpcException{
Boolean [] returnValues = new Boolean[rows.size()];
for (int i = 0; i < rows.size(); i++)
returnValues[i] = writeObject(rows.get(i), changesOnly);
return returnValues;
}
/**
* Writes a Row to the database by calling the write function on the object the Row is holding data for
* @param row Row to be committed
* @param changesOnly Only changed values will be submitted to the database.
* @return If the update was successful
* @throws OpeneERPApiException
* @throws XmlRpcException
*/
public boolean writeObject(final Row row, boolean changesOnly) throws OpeneERPApiException, XmlRpcException{
HashMap<String, Object> valueList = new HashMap<String, Object>();
Object idObj = row.get("id");
if (idObj == null || Integer.parseInt(idObj.toString()) <= 0)
throw new OpeneERPApiException("Please set the id field with the database ID of the object");
int id = Integer.parseInt(idObj.toString());
if (changesOnly){
for (Field fld : row.getChangedFields())
valueList.put(fld.getName(), formatValueForWrite(fld,row.get(fld)));
}
else for (Field fld : row.getFields()){
valueList.put(fld.getName(), formatValueForWrite(fld,row.get(fld)));
}
if (valueList.size() == 0)
return false;
boolean success = commands.writeObject(objectName, id, valueList);
if (success)
row.changesApplied();
return success;
}
/**
* Creates an Object on the OpenERP server by calling the create function on the server.
* The id column is set on the row after the object was successfully created
* @param row Data row read data from to create the Object
* @throws OpeneERPApiException
* @throws XmlRpcException
*/
public void createObject(final Row row) throws OpeneERPApiException, XmlRpcException{
HashMap<String, Object> valueList = new HashMap<String, Object>();
for (Field fld : row.getFields())
valueList.put(fld.getName(), formatValueForWrite(fld,row.get(fld)));
if (valueList.size() == 0)
throw new OpeneERPApiException("Row doesn't have any fields to update");
Object id = commands.createObject(objectName, valueList);
row.put("id", id);
row.changesApplied();
}
/**
* Calls any function on an object that returns a field collection.
* ie. a row is retured as [{'name' : {'type' : 'char'}]
* The OpenERP function must have the signature like (self, cr, uid, *param).
* @param functionName function to call
* @param parameters Additional parameters that will be passed to the object
* @return A field collection
* @throws XmlRpcException
* @throws OpeneERPApiException
*/
@SuppressWarnings("unchecked")
public FieldCollection callFieldsFunction(String functionName, Object[] parameters) throws XmlRpcException, OpeneERPApiException{
Object[] results = commands.callObjectFunction(objectName, functionName, parameters);
// Go through the first row and fetch the fields
FieldCollection fieldCol = new FieldCollection();
if (results.length > 0){
HashMap<String, Object> rowMap = (HashMap<String, Object>) results[0];
for (String field : rowMap.keySet()){
HashMap<String, Object> fldDetails = null;
if (rowMap.get(field) instanceof HashMap<?, ?>){
try{
fldDetails = (HashMap<String, Object>) rowMap.get(field);
}
catch (Exception e){
fldDetails = null;
}
}
if (fldDetails == null)
fldDetails = new HashMap<String, Object>();
if (!fldDetails.containsKey("name"))
fldDetails.put("name", field);
if (!fldDetails.containsKey("description"))
fldDetails.put("description", field);
if (!fldDetails.containsKey("type")){
@SuppressWarnings({ "rawtypes"})
Class type = rowMap.get(field).getClass();
if (type == String.class){
fldDetails.put("type", "char");
}
else if (type == Date.class){
fldDetails.put("type", "date");
}
else if (type == Boolean.class){
fldDetails.put("type", "boolean");
}
else if (type == Double.class){
fldDetails.put("type", "float");
}
else if (type == Integer.class){
fldDetails.put("type", "integer");
}
else fldDetails.put("type", "char");
}
fieldCol.add(new Field(field,fldDetails));
}
}
return fieldCol;
}
/**
* Calls any function on an object.
* The first row is inspected to determine data fields and data types
* The OpenERP function must have the signature like (self, cr, uid, *param) and return a dictionary or object.
* @param functionName function to call
* @param parameters Additional parameters that will be passed to the object
* @param fieldCol An option field collection to use. A new one will be built by inspecting the first row if it isn't specified (null).
* @return A row collection with the data
* @throws XmlRpcException
* @throws OpeneERPApiException
*/
public RowCollection callFunction(String functionName, Object[] parameters, FieldCollection fieldCol) throws XmlRpcException, OpeneERPApiException{
Object[] results = commands.callObjectFunction(objectName, functionName, parameters);
if (fieldCol == null)
fieldCol = callFieldsFunction(functionName, parameters);
RowCollection rows = new RowCollection(results, fieldCol);
return rows;
}
/**
* Executes a workflow by sending a signal to the workflow engine for a specific object.
* @param row Row that represents the object that the signal should be sent for
* @param signal Signal name to send
* @throws XmlRpcException
* @throws OpeneERPApiException
*/
public void executeWorkflow(Row row, String signal) throws XmlRpcException, OpeneERPApiException{
ObjectAdapter.signalExists(this.commands, this.objectName, signal);
commands.executeWorkflow(this.objectName, signal, row.getID());
}
/**
* Deletes objects from the OpenERP Server
* @param rows Rows to delete
* @return If all rows were successfully deleted
* @throws XmlRpcException
*/
public boolean unlinkObject(RowCollection rows) throws XmlRpcException{
Object [] ids = new Object[rows.size()];
for(int i = 0; i< rows.size(); i++){
ids[i] = rows.get(i).getID();
}
return this.commands.unlinkObject(this.objectName, ids);
}
/**
* Deletes objects from the OpenERP Server
* @param row Row to delete
* @return If the row was successfully deleted
* @throws XmlRpcException
*/
public boolean unlinkObject(Row row) throws XmlRpcException{
RowCollection rows = new RowCollection();
rows.add(row);
return this.unlinkObject(rows);
}
}
|
package com.elusivehawk.util.storage;
import com.elusivehawk.util.IDirty;
/**
*
* Stores an object, which if modified will set off the {@link #isDirty()} flag.
*
* @author Elusivehawk
*/
public class DirtableStorage<T> implements IDirty, IStorage<T>
{
protected T obj;
protected boolean dirty = false, sync = false, enableNull = true;
public DirtableStorage()
{
this(null);
}
@SuppressWarnings("unqualified-field-access")
public DirtableStorage(T object)
{
obj = object;
}
@Override
public boolean isDirty()
{
return this.dirty;
}
@Override
public void setIsDirty(boolean b)
{
this.dirty = b;
}
@Override
public T get()
{
return this.obj;
}
@Override
public boolean set(T object)
{
if (object == null && !this.enableNull)
{
return false;
}
if (object == null ? this.obj != object : !object.equals(this.obj))
{
if (this.sync)
{
synchronized (this)
{
this.obj = object;
}
}
else
{
this.obj = object;
}
this.setIsDirty(true);
return true;
}
return false;
}
public DirtableStorage<T> setEnableNull(boolean b)
{
this.enableNull = b;
return this;
}
public DirtableStorage<T> setSync()
{
this.sync = true;
return this;
}
}
|
package com.jayantkrish.jklol.experiments.p3;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.jayantkrish.jklol.ccg.ParametricCcgParser;
import com.jayantkrish.jklol.ccg.gi.ValueGroundedParseExample;
import com.jayantkrish.jklol.ccg.lambda.ExpressionParser;
import com.jayantkrish.jklol.ccg.lambda2.Expression2;
import com.jayantkrish.jklol.ccg.lambda2.ExpressionReplacementRule;
import com.jayantkrish.jklol.ccg.lambda2.ExpressionSimplifier;
import com.jayantkrish.jklol.ccg.lambda2.LambdaApplicationReplacementRule;
import com.jayantkrish.jklol.ccg.lambda2.VariableCanonicalizationReplacementRule;
import com.jayantkrish.jklol.lisp.AmbEval;
import com.jayantkrish.jklol.lisp.AmbEval.WrappedBuiltinFunction;
import com.jayantkrish.jklol.lisp.ConstantValue;
import com.jayantkrish.jklol.lisp.Environment;
import com.jayantkrish.jklol.lisp.LispUtil;
import com.jayantkrish.jklol.lisp.SExpression;
import com.jayantkrish.jklol.lisp.inc.ContinuationIncEval;
import com.jayantkrish.jklol.models.DiscreteFactor;
import com.jayantkrish.jklol.models.DiscreteVariable;
import com.jayantkrish.jklol.models.TableFactor;
import com.jayantkrish.jklol.models.VariableNumMap;
import com.jayantkrish.jklol.nlpannotation.AnnotatedSentence;
import com.jayantkrish.jklol.tensor.DenseTensorBuilder;
import com.jayantkrish.jklol.util.IndexedList;
import com.jayantkrish.jklol.util.IoUtils;
public class P3Utils {
public static List<ValueGroundedParseExample> readTrainingData(String path,
DiscreteVariable categoryFeatureNames, DiscreteVariable relationFeatureNames,
String categoryFilePath, String relationFilePath, String trainingFilePath) {
DiscreteFactor categoryFeatures = TableFactor.fromDelimitedFile(
IoUtils.readLines(path + "/" + categoryFilePath), ",");
VariableNumMap entityVar = categoryFeatures.getVars().getFirstVariables(1)
.relabelVariableNums(new int[] {0});
VariableNumMap truthVar = VariableNumMap.singleton(2, "truthVar",
new DiscreteVariable("truthVar", Arrays.asList("F", "T")));
VariableNumMap lispTruthVar = VariableNumMap.singleton(2, "lispTruthVar",
new DiscreteVariable("truthVar", Arrays.asList(ConstantValue.FALSE, ConstantValue.TRUE)));
VariableNumMap entityFeatureVar = VariableNumMap.singleton(3, "entityFeatures",
categoryFeatureNames);
categoryFeatures = TableFactor.fromDelimitedFile(
VariableNumMap.unionAll(entityVar, truthVar, entityFeatureVar),
IoUtils.readLines(path + "/" + categoryFilePath), ",", false,
DenseTensorBuilder.getFactory());
categoryFeatures = new TableFactor(
VariableNumMap.unionAll(entityVar, lispTruthVar, entityFeatureVar),
categoryFeatures.getWeights());
VariableNumMap entityVar1 = entityVar;
VariableNumMap entityVar2 = entityVar.relabelVariableNums(new int[] {1});
VariableNumMap entityPairFeatureVar = VariableNumMap.singleton(3,
"entityPairFeatures", relationFeatureNames);
DiscreteFactor relationFeatures = TableFactor.fromDelimitedFile(
VariableNumMap.unionAll(entityVar1, entityVar2, truthVar, entityPairFeatureVar),
IoUtils.readLines(path + "/" + relationFilePath), ",", false,
DenseTensorBuilder.getFactory());
relationFeatures = new TableFactor(
VariableNumMap.unionAll(entityVar1, entityVar2, lispTruthVar, entityPairFeatureVar),
relationFeatures.getWeights());
String[] parts = path.split("/");
String id = parts[parts.length - 1];
KbEnvironment env = new KbEnvironment(id, categoryFeatures, relationFeatures);
KbState state = KbState.unassigned(env);
List<ValueGroundedParseExample> examples = Lists.newArrayList();
for (String exampleString : IoUtils.readLines(path + "/" + trainingFilePath)) {
if (exampleString.startsWith("*") || exampleString.trim().length() == 0) {
continue;
}
String[] exampleParts = exampleString.split(";");
if (exampleParts.length < 2) {
System.out.println("bad example: "+ exampleString);
continue;
}
String language = exampleParts[0];
// Hacky tokenization.
List<String> tokens = Arrays.asList(language.toLowerCase().replaceAll("([,?./\\(\\)-])", " $1 ")
.replaceAll("(['])", " $1").split("[ ]+"));
List<String> pos = Collections.nCopies(tokens.size(), ParametricCcgParser.DEFAULT_POS_TAG);
AnnotatedSentence sentence = new AnnotatedSentence(tokens, pos);
Set<String> denotation = Sets.newHashSet(exampleParts[1].split(","));
examples.add(new ValueGroundedParseExample(sentence, state, denotation));
}
return examples;
}
public static Environment getEnvironment(IndexedList<String> symbolTable) {
Environment env = AmbEval.getDefaultEnvironment(symbolTable);
env.bindName("get-entities", new WrappedBuiltinFunction(new P3Functions.GetEntities()), symbolTable);
env.bindName("kb-get", new WrappedBuiltinFunction(new P3Functions.KbGet()), symbolTable);
env.bindName("kb-set", new WrappedBuiltinFunction(new P3Functions.KbSet()), symbolTable);
env.bindName("list-to-set", new WrappedBuiltinFunction(new P3Functions.ListToSet()), symbolTable);
return env;
}
public static ContinuationIncEval getIncEval(List<String> defFilenames) {
IndexedList<String> symbolTable = AmbEval.getInitialSymbolTable();
AmbEval ambEval = new AmbEval(symbolTable);
Environment env = P3Utils.getEnvironment(symbolTable);
ExpressionSimplifier simplifier = P3Utils.getSimplifier();
SExpression defs = LispUtil.readProgram(defFilenames, symbolTable);
Expression2 lfConversion = ExpressionParser.expression2().parse(
"(lambda (x) (list-to-set-c (get-denotation x)))");
return new ContinuationIncEval(ambEval, env, simplifier, defs, lfConversion);
}
public static ExpressionSimplifier getSimplifier() {
return new ExpressionSimplifier(Arrays.<ExpressionReplacementRule>asList(
new LambdaApplicationReplacementRule(),
new VariableCanonicalizationReplacementRule()));
}
private P3Utils() {
// Prevent instantiation.
}
}
|
package com.markupartist.sthlmtraveling;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface.OnClickListener;
public class DialogHelper {
/**
* Creates a dialog to display in case of network problems.
* @param activity the activity
* @param onClickListener the on click listener for the retry button
* @return a dialog
*/
public static AlertDialog createNetworkProblemDialog(Activity activity,
OnClickListener onClickListener) {
return new AlertDialog.Builder(activity)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(activity.getText(R.string.attention_label))
.setMessage(activity.getText(R.string.network_problem_message))
.setPositiveButton(activity.getText(R.string.retry), onClickListener)
.setNegativeButton(activity.getText(android.R.string.cancel), null)
.create();
}
}
|
package com.pushtechnology.benchmarks.util;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import com.pushtechnology.diffusion.api.Logs;
/**
* Some JMX connection creation utility methods.
*
* @author nitsanw
*
*/
public final class JmxHelper {
// CHECKSTYLE:OFF
private static final String JMX_URL_PATTERN = "service:jmx:rmi://%s:%d/jndi/rmi://%s:%d/%s";
private static final String JMX_CREDENTIALS_KEY = "jmx.remote.credentials";
private static final int DEFAULT_JNDI_PORT = 1100;
private static final int DEFAULT_JMX_RMI_PORT = 1099;
private JmxHelper() {
}
// CHECKSTYLE:ON
/**
* Connect using specific JMX ports.
*
* @param host target host
* @param service target service
* @param user JMX user name
* @param pass JMX password
* @param jmxRmiPort ..
* @param jmxJndiPort ..
* @return a JMX connector to specified host
* @throws IOException if connection fails/if resulting URL is malformed
*/
@SuppressWarnings("deprecation")
public static JMXConnector getJmxConnector(final String host, final String service,
final String user, final String pass, final int jmxRmiPort, final int jmxJndiPort)
throws IOException {
final String jmxUrl = getJmxUrl(host, service, jmxRmiPort, jmxJndiPort);
Logs.advice("Using JMX URL: " + jmxUrl);
final JMXServiceURL serviceUrl = new JMXServiceURL(jmxUrl);
return getJmxConnector(user, pass, serviceUrl);
}
/**
* Connect using default JMX ports.
*
* @param host target host
* @param service target service
* @param user JMX user name
* @param pass JMX password
* @return a JMX connector to specified host
* @throws IOException if connection fails/if resulting URL is malformed
*/
public static JMXConnector getJmxConnector(final String host, final String service,
final String user, final String pass)
throws IOException {
return getJmxConnector(host, service, user, pass, DEFAULT_JMX_RMI_PORT, DEFAULT_JNDI_PORT);
}
/**
* Connect using JMXServiceURL.
*
* @param user JMX user name
* @param pass JMX password
* @param serviceUrl ..
* @return a JMX connector to specified host
* @throws IOException if connection fails/if resulting URL is malformed
*/
private static JMXConnector getJmxConnector(final String user, final String pass,
final JMXServiceURL serviceUrl) throws IOException {
final Map<String, String[]> env = new HashMap<String, String[]>();
env.put(JMX_CREDENTIALS_KEY, new String[] {user, pass});
final JMXConnector connector = JMXConnectorFactory.connect(serviceUrl, env);
return connector;
}
/**
* Create a JMX URL based on host and ports.
*
* @param host ..
* @param service ..
* @param jmxRmiPort ..
* @param jmxJndiPort ..
*
* @return service:jmx:rmi://HOST:JNDI_P/jndi/rmi://HOST:RMI_P/SERVICE
*/
private static String getJmxUrl(final String host, final String service, final int jmxRmiPort,
final int jmxJndiPort) {
return String.format(
JMX_URL_PATTERN,
host,
jmxJndiPort,
host,
jmxRmiPort,
service);
}
}
|
package com.tacticalnuclearstrike.tttumblr;
import java.io.File;
import java.io.InputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlPullParserException;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.webkit.MimeTypeMap;
import org.nerdcircus.android.tumblr.MediaUriBody;
public class TumblrApi {
public static final String TAG = "TumblrApi";
public static final String BLOGS_PREFS = "blogs";
public static final String GENERATOR = "ttTumblr"; // user-agent string.
private SharedPreferences mPrefs;
private Context context;
public TumblrApi(Context context) {
this.context = context;
mPrefs = PreferenceManager.getDefaultSharedPreferences(context);
}
public String getUserName() {
return getSharePreferences().getString("USERNAME", "");
}
public String getPassword() {
return getSharePreferences().getString("PASSWORD", "");
}
public Boolean getIntegrateWithTwitter() {
return getSharePreferences().getBoolean("TWITTER", false);
}
private SharedPreferences getSharePreferences() {
SharedPreferences settings = context.getSharedPreferences("tumblr", 0);
return settings;
}
public boolean isUserNameAndPasswordStored() {
return (getUserName().compareTo("") != 0)
&& (getPassword().compareTo("") != 0);
}
public boolean validateUsernameAndPassword(String Username, String Password) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http:
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email", Username));
nameValuePairs.add(new BasicNameValuePair("password", Password));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() != 200) {
return false;
}
// Save our list of available blogs.
SharedPreferences blogs = context.getSharedPreferences(BLOGS_PREFS,
0);
Log.d("ttT", "attempting blog list extraction");
saveBlogList(response, blogs);
return true;
} catch (ClientProtocolException e) {
Log.d(TAG, "client proto exception", e);
} catch (IOException e) {
Log.d(TAG, "io exception", e);
}
return false;
}
public List<Cookie> authenticateAndReturnCookies() {
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http:
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("email", getUserName()));
nameValuePairs
.add(new BasicNameValuePair("password", getPassword()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
return httpclient.getCookieStore().getCookies();
} catch (ClientProtocolException e) {
} catch (IOException e) {
}
return null;
}
private MultipartEntity getEntityWithBaseParamsSet(Boolean Private) {
MultipartEntity entity = new MultipartEntity();
try {
entity.addPart("email", new StringBody(getUserName()));
entity.addPart("password", new StringBody(getPassword()));
entity.addPart("generator", new StringBody(GENERATOR));
} catch (UnsupportedEncodingException e) {
Log.e("ttTumblr", e.getMessage());
}
return entity;
}
/*
* post options are fields that can be set in the tumblr api: -
* send-to-twitter - private - group - tags - format etc.
*/
public MultipartEntity getEntityWithOptions(Bundle options) {
MultipartEntity entity = getEntityWithBaseParamsSet(false);
if (options == null) {
return entity;
}
;
try {
// TODO: detect if the options have already been set?
// FIXME: use a foreach loop here.
if (options.containsKey("send-to-twitter")) {
entity.addPart("send-to-twitter", new StringBody(options
.getString("send-to-twitter")));
Log.d(TAG, "send-to-twitter: "
+ options.getString("send-to-twitter"));
} else {
// set the param from the defaults.
if (mPrefs.getBoolean("twitter", false))
entity.addPart("send-to-twitter", new StringBody("1"));
}
if (options.containsKey("group")) {
entity.addPart("group", new StringBody(options
.getString("group")
+ ".tumblr.com"));
Log.d(TAG, "group: " + options.getString("group"));
}
if (options.containsKey("private")) {
entity.addPart("private", new StringBody(options
.getString("private")));
Log.d(TAG, "private: " + options.getString("private"));
} else {
// set the param from the defaults.
if (mPrefs.getBoolean("private", false))
entity.addPart("private", new StringBody("1"));
}
if(options.containsKey("tags")){
entity.addPart("tags", new StringBody(options.getString("tags")));
Log.d(TAG, "tags: " + options.getString("tags"));
}
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "unsupported encoding: " + e.getMessage());
}
return entity;
}
/* helper to enclose all the http-related code */
private HttpResponse postEntity(MultipartEntity entity) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http:
try {
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
return response;
} catch (ClientProtocolException e) {
Log.e(TAG, "client proto exception!", e);
} catch (IOException e) {
Log.e(TAG, "io exception", e);
}
return null;
}
public boolean postText(String title, String body, Bundle options) {
MultipartEntity entity = getEntityWithOptions(options);
try {
entity.addPart("type", new StringBody("regular"));
if (title != null)
entity.addPart("title", new StringBody(title));
if (body != null)
entity.addPart("body", new StringBody(body));
} catch (UnsupportedEncodingException e) {
Log.e(TAG, e.getMessage());
}
HttpResponse response = postEntity(entity);
Log.d(TAG, "Server said: " + response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() != 201) {
ShowNotification("ttTumblr", "Text creation failed", "");
return false;
}
return true;
}
public void postImage(Uri image, String caption, Bundle options) {
MultipartEntity entity = getEntityWithOptions(options);
try {
entity.addPart("type", new StringBody("photo"));
if (caption != null)
entity.addPart("caption", new StringBody(caption));
File f = new File(image.getPath());
entity.addPart("data",new FileBody(f));
} catch (UnsupportedEncodingException e) {
Log.d(TAG, e.getMessage());
}
HttpResponse response = postEntity(entity);
Log.d(TAG, "Server said:" + response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() == 201)
ShowNotification("Image Posted", "", "");
else
ShowNotification("Image upload failed", "", "");
}
public void ShowNotification(String tickerText, String contentTitle,
String contentText) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) context
.getSystemService(ns);
int icon = R.drawable.tumblr24x24;
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, tickerText, when);
notification.flags = Notification.FLAG_AUTO_CANCEL;
Intent notificationIntent = new Intent(context, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText,
contentIntent);
mNotificationManager.notify(1, notification);
}
public void PostYoutubeUrl(String url, String caption, Bundle options)
{
try {
MultipartEntity entity = getEntityWithOptions(options);
entity.addPart("caption", new StringBody(caption));
entity.addPart("type", new StringBody("video"));
entity.addPart("embed ",new StringBody(url));
HttpResponse response = postEntity(entity);
Log.d(TAG, "Server said:" + response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() == 201)
ShowNotification("ttTumblr", "Video Posted", "");
else
ShowNotification("ttTumblr", "Video post failed", "");
} catch (IOException e) {
ShowNotification("ttTumblr", "Video post failed", e.toString());
}
}
public void PostVideo(Uri video, String caption, Bundle options) {
try {
MultipartEntity entity = getEntityWithOptions(options);
entity.addPart("caption", new StringBody(caption));
entity.addPart("type", new StringBody("video"));
File f = new File(video.getPath());
entity.addPart("data",new FileBody(f));
HttpResponse response = postEntity(entity);
Log.d(TAG, "Server said:" + response.getStatusLine().getStatusCode());
if (response.getStatusLine().getStatusCode() == 201)
ShowNotification("ttTumblr", "Video Posted", "");
else
ShowNotification("ttTumblr", "Video upload failed", "");
} catch (IOException e) {
ShowNotification("ttTumblr", "Video upload failed", e.toString());
}
}
public boolean postQuote(String quoteText, String sourceText, Bundle options) {
MultipartEntity entity = getEntityWithOptions(options);
try {
entity.addPart("type", new StringBody("quote"));
entity.addPart("quote", new StringBody(quoteText));
if (sourceText != null)
entity.addPart("source", new StringBody(sourceText));
} catch (UnsupportedEncodingException e) {
Log.e(TAG, e.getMessage());
}
HttpResponse response = postEntity(entity);
if (response.getStatusLine().getStatusCode() != 201) {
ShowNotification("ttTumblr", "Quote creation failed", "");
}
return true;
}
public boolean postUrl(String url, String name, String description,
Bundle options) {
MultipartEntity entity = getEntityWithOptions(options);
try {
entity.addPart("type", new StringBody("link"));
entity.addPart("url", new StringBody(url));
if (name != null)
entity.addPart("name", new StringBody(name));
if (description != null)
entity.addPart("description", new StringBody(description));
} catch (UnsupportedEncodingException e) {
Log.e(TAG, e.getMessage());
}
HttpResponse response = postEntity(entity);
if (response.getStatusLine().getStatusCode() != 201) {
ShowNotification("Link creation failed", "", "");
}
return true;
}
public boolean postConversation(String title, String convo, Bundle options) {
MultipartEntity entity = getEntityWithOptions(options);
try {
entity.addPart("type", new StringBody("conversation"));
if (title != null)
entity.addPart("title", new StringBody(title));
if (convo != null)
entity.addPart("conversation", new StringBody(convo));
} catch (UnsupportedEncodingException e) {
Log.e(TAG, e.getMessage());
}
HttpResponse response = postEntity(entity);
if (response.getStatusLine().getStatusCode() != 201) {
ShowNotification("Post creation failed", "", "");
return false;
}
return true;
}
private void saveBlogList(HttpResponse r, SharedPreferences bloglist) {
bloglist.edit().clear().commit();
try {
XmlPullParser xpp = XmlPullParserFactory.newInstance()
.newPullParser();
xpp.setInput(r.getEntity().getContent(), null);
int eventType = xpp.getEventType();
Log.d("ttT", "starting to loop...");
while (eventType != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG
&& xpp.getName().equals("tumblelog")) {
Log.d("ttT", "found a tumblelog.");
String title = xpp.getAttributeValue(null, "title");
String type = xpp.getAttributeValue(null, "type");
if (type.equals("public")) {
String name = xpp.getAttributeValue(null, "name");
Log.d(TAG, "found public blog named: " + name);
bloglist.edit().putString(title, name).commit();
if (xpp.getAttributeValue(null, "is-primary") != null
&& xpp.getAttributeValue(null, "is-primary")
.equals("yes")) {
// set the primary blog as our default.
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
prefs.edit().putString("default_blog", name)
.commit();
}
}
}
eventType = xpp.next();
}
} catch (XmlPullParserException e) {
Log.e(TAG, "blog list parser failure", e);
} catch (IOException e) {
Log.e(TAG, "i/o error", e);
}
}
/**
* Returns a Bundle with user's preferred default post options. settings are
* read from preferences, and can be overridden.
*/
public static Bundle getDefaultPostOptions(Context context) {
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context);
Bundle postoptions = new Bundle();
if (prefs.getBoolean("twitter", false)) {
postoptions.putString("send-to-twitter", "auto");
} else {
postoptions.putString("send-to-twitter", "no");
}
if (prefs.getBoolean("private", false)) {
postoptions.putString("private", "1");
} else {
postoptions.putString("private", "0");
}
postoptions.putString("format", prefs.getString("text_format",
"Markdown"));
postoptions.putString("group", prefs.getString("default_blog", "")
+ ".tumblr.com");
return postoptions;
}
}
|
package com.xamoom.android.xamoomsdk;
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import com.xamoom.android.xamoomsdk.Enums.ContentFlags;
import com.xamoom.android.xamoomsdk.Enums.ContentSortFlags;
import com.xamoom.android.xamoomsdk.Enums.SpotFlags;
import com.xamoom.android.xamoomsdk.Enums.SpotSortFlags;
import com.xamoom.android.xamoomsdk.Resource.Content;
import com.xamoom.android.xamoomsdk.Resource.ContentBlock;
import com.xamoom.android.xamoomsdk.Resource.Marker;
import com.xamoom.android.xamoomsdk.Resource.Menu;
import com.xamoom.android.xamoomsdk.Resource.Spot;
import com.xamoom.android.xamoomsdk.Resource.Style;
import com.xamoom.android.xamoomsdk.Resource.System;
import com.xamoom.android.xamoomsdk.Resource.SystemSetting;
import com.xamoom.android.xamoomsdk.Utils.JsonListUtil;
import com.xamoom.android.xamoomsdk.Utils.UrlUtil;
import java.io.IOException;
import java.util.EnumSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import at.rags.morpheus.Deserializer;
import at.rags.morpheus.Error;
import at.rags.morpheus.Morpheus;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Retrofit;
/**
* EnduserApi is the main part of the XamoomSDK. You can use it to send api request to
* the xamoom cloud.
*
* Use {@link #EnduserApi(String)} to initialize.
*
* Change the requested language by setting {@link #language}. The users language is saved
* in {@link #systemLanguage}.
*/
public class EnduserApi {
private static final String TAG = EnduserApi.class.getSimpleName();
private static final String API_URL = "https://xamoom-cloud.appspot.com/";
private static EnduserApi sharedInstance;
private EnduserApiInterface enduserApiInterface;
private CallHandler callHandler;
private String language;
private String systemLanguage;
public EnduserApi(final String apikey) {
OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
builder.addInterceptor(new Interceptor() {
@Override
public okhttp3.Response intercept(Chain chain) throws IOException {
Request request = chain.request().newBuilder()
.addHeader("Content-Type", "application/vnd.api+json")
.addHeader("APIKEY", apikey)
.build();
return chain.proceed(request);
}
});
OkHttpClient httpClient = builder.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(API_URL)
.client(httpClient)
.build();
enduserApiInterface = retrofit.create(EnduserApiInterface.class);
initMorpheus();
initVars();
}
public EnduserApi(Retrofit retrofit) {
enduserApiInterface = retrofit.create(EnduserApiInterface.class);
initMorpheus();
initVars();
}
private void initMorpheus() {
Morpheus morpheus = new Morpheus();
callHandler = new CallHandler(morpheus);
Deserializer.registerResourceClass("contents", Content.class);
Deserializer.registerResourceClass("content", Content.class);
Deserializer.registerResourceClass("contentblocks", ContentBlock.class);
Deserializer.registerResourceClass("spots", Spot.class);
Deserializer.registerResourceClass("markers", Marker.class);
Deserializer.registerResourceClass("systems", System.class);
Deserializer.registerResourceClass("menus", Menu.class);
Deserializer.registerResourceClass("settings", SystemSetting.class);
Deserializer.registerResourceClass("styles", Style.class);
}
private void initVars() {
systemLanguage = Locale.getDefault().getLanguage();
language = systemLanguage;
}
/**
* Get a content for a specific contentID.
*
* @param contentID ContentID from xamoom-cloud.
* @param callback {@link APICallback}.
*/
public void getContent(String contentID, APICallback<Content, List<Error>> callback) {
getContent(contentID, null, callback);
}
/**
* Get a content for a specific contentID with possible flags.
*
* @param contentID ContentID from xamoom-cloud.
* @param contentFlags Different flags {@link ContentFlags}.
* @param callback {@link APICallback}.
*/
public void getContent(String contentID, EnumSet<ContentFlags> contentFlags, APICallback<Content,
List<at.rags.morpheus.Error>> callback) {
Map<String, String> params = UrlUtil.addContentParameter(UrlUtil.getUrlParameter(language),
contentFlags);
Call<ResponseBody> call = enduserApiInterface.getContent(contentID, params);
callHandler.enqueCall(call, callback);
}
/**
* Get a content for a specific LocationIdentifier.
*
* @param locationIdentifier LocationIdentifier from QR or NFC.
* @param callback {@link APICallback}.
*/
public void getContentByLocationIdentifier(String locationIdentifier, APICallback<Content,
List<Error>> callback) {
getContentByLocationIdentifier(locationIdentifier, null, callback);
}
/**
* Get a content for a specific LocationIdentifier with flags.
*
* @param locationIdentifier LocationIdentifier from QR or NFC.
* @param contentFlags Different flags {@link ContentFlags}.
* @param callback {@link APICallback}.
*/
public void getContentByLocationIdentifier(String locationIdentifier,
EnumSet<ContentFlags> contentFlags,
APICallback<Content, List<Error>> callback) {
Map<String, String> params = UrlUtil.getUrlParameter(language);
params.put("filter[location-identifier]", locationIdentifier);
params = UrlUtil.addContentParameter(params, contentFlags);
Call<ResponseBody> call = enduserApiInterface.getContents(params);
callHandler.enqueCall(call, callback);
}
/**
* Get content for a specific beacon.
*
* @param major Beacon major ID.
* @param minor Beacon minor ID.
* @param callback {@link APICallback}.
*/
public void getContentByBeacon(int major, int minor, APICallback<Content, List<Error>>
callback) {
getContentByLocationIdentifier(String.format("%s|%s", major, minor), callback);
}
/**
* Get content for a specific beacon.
*
* @param major Beacon major ID.
* @param minor Beacon minor ID.
* @param contentFlags Different flags {@link ContentFlags}.
* @param callback {@link APICallback}.
*/
public void getContentByBeacon(int major, int minor, EnumSet<ContentFlags> contentFlags,
APICallback<Content, List<Error>> callback) {
getContentByLocationIdentifier(String.format("%s|%s", major, minor), contentFlags, callback);
}
/**
* Get list of contents with your location. Geofence radius is 40m.
*
* @param location Users location.
* @param pageSize PageSize for returned contents (max 100).
* @param cursor Cursor for paging.
* @param sortFlags {@link ContentSortFlags} to sort results.
* @param callback {@link APIListCallback}.
*/
public void getContentsByLocation(Location location, int pageSize, @Nullable String cursor,
final EnumSet<ContentSortFlags> sortFlags,
APIListCallback<List<Content>,
List<Error>> callback) {
Map<String, String> params = UrlUtil.addContentSortingParameter(UrlUtil.getUrlParameter(language),
sortFlags);
params = UrlUtil.addPagingToUrl(params, pageSize, cursor);
params.put("filter[lat]", Double.toString(location.getLatitude()));
params.put("filter[lon]", Double.toString(location.getLongitude()));
Call<ResponseBody> call = enduserApiInterface.getContents(params);
callHandler.enqueListCall(call, callback);
}
/**
* Get list of contents with a specific tag.
*
* @param tags List of strings.
* @param pageSize PageSize for returned contents (max 100).
* @param cursor Cursor for paging.
* @param sortFlags {@link ContentSortFlags} to sort results.
* @param callback {@link APIListCallback}.
*/
public void getContentsByTags(List<String> tags, int pageSize, @Nullable String cursor,
EnumSet<ContentSortFlags> sortFlags,
APIListCallback<List<Content>, List<Error>> callback) {
Map<String, String> params = UrlUtil.addContentSortingParameter(UrlUtil.getUrlParameter(language),
sortFlags);
params = UrlUtil.addPagingToUrl(params, pageSize, cursor);
params.put("filter[tags]", JsonListUtil.listToJsonArray(tags, ","));
Call<ResponseBody> call = enduserApiInterface.getContents(params);
callHandler.enqueListCall(call, callback);
}
/**
* Get list of contents with full-text name search.
*
* @param name Name to search for.
* @param pageSize PageSize for returned contents (max 100).
* @param cursor Cursor for paging.
* @param sortFlags {@link ContentSortFlags} to sort results.
* @param callback {@link APIListCallback}.
*/
public void searchContentsByName(String name, int pageSize, @Nullable String cursor,
EnumSet<ContentSortFlags> sortFlags,
APIListCallback<List<Content>, List<Error>> callback) {
Map<String, String> params = UrlUtil.addContentSortingParameter(UrlUtil.getUrlParameter(language),
sortFlags);
params = UrlUtil.addPagingToUrl(params, pageSize, cursor);
params.put("filter[name]", name);
Call<ResponseBody> call = enduserApiInterface.getContents(params);
callHandler.enqueListCall(call, callback);
}
/**
* Get spot with specific id.
*
* @param spotId Id of the spot.
* @param callback {@link APICallback}.
*/
public void getSpot(String spotId, APICallback<Spot, List<Error>> callback) {
getSpot(spotId, null, callback);
}
public void getSpot(String spotId, EnumSet<SpotFlags> spotFlags, APICallback<Spot, List<Error>> callback) {
Map<String, String> params = UrlUtil.getUrlParameter(this.language);
params = UrlUtil.addSpotParameter(params, spotFlags);
Call<ResponseBody> call = enduserApiInterface.getSpot(spotId, params);
callHandler.enqueCall(call, callback);
}
/**
* Get list of spots inside radius of a location.
*
* @param location User location.
* @param radius Radius to search in meter (max 5000).
* @param spotFlags {@link SpotFlags}.
* @param sortFlags {@link SpotSortFlags}
* @param callback {@link APIListCallback}
*/
public void getSpotsByLocation(Location location, int radius, EnumSet<SpotFlags> spotFlags,
@Nullable EnumSet<SpotSortFlags> sortFlags,
APIListCallback<List<Spot>, List<Error>> callback) {
getSpotsByLocation(location, radius, 0, null, spotFlags, sortFlags, callback);
}
/**
* Get list of spots inside radius of a location.
*
* @param location User location.
* @param radius Radius to search in meter (max 5000).
* @param pageSize Size for pages. (max 100)
* @param cursor Cursor of last search.
* @param spotFlags {@link SpotFlags}.
* @param sortFlags {@link SpotSortFlags}
* @param callback {@link APIListCallback}
*/
public void getSpotsByLocation(Location location, int radius, int pageSize, @Nullable String cursor,
@Nullable EnumSet<SpotFlags> spotFlags,
@Nullable EnumSet<SpotSortFlags> sortFlags,
APIListCallback<List<Spot>, List<Error>> callback) {
Map<String, String> params = UrlUtil.addSpotParameter(UrlUtil.getUrlParameter(language),
spotFlags);
params = UrlUtil.addSpotSortingParameter(params, sortFlags);
params = UrlUtil.addPagingToUrl(params, pageSize, cursor);
params.put("filter[lat]", Double.toString(location.getLatitude()));
params.put("filter[lon]", Double.toString(location.getLongitude()));
params.put("filter[radius]", Integer.toString(radius));
Call<ResponseBody> call = enduserApiInterface.getSpots(params);
callHandler.enqueListCall(call, callback);
}
/**
* Get list of spots with tags.
* Or operation used when searching with tags.
*
* @param tags List with tag names
* @param spotFlags {@link SpotFlags}.
* @param sortFlags {@link SpotSortFlags}
* @param callback {@link APIListCallback}
*/
public void getSpotsByTags(List<String> tags, @Nullable EnumSet<SpotFlags> spotFlags,
@Nullable EnumSet<SpotSortFlags> sortFlags,
APIListCallback<List<Spot>, List<Error>> callback) {
getSpotsByTags(tags, 0, null, spotFlags, sortFlags, callback);
}
/**
* Get list of spots with with tags.
* Or operation used when searching with tags.
*
* @param tags List with tag names.
* @param pageSize Size for pages. (max 100)
* @param cursor Cursor of last search.
* @param spotFlags {@link SpotFlags}.
* @param sortFlags {@link SpotSortFlags}
* @param callback {@link APIListCallback}
*/
public void getSpotsByTags(List<String> tags, int pageSize, @Nullable String cursor,
@Nullable EnumSet<SpotFlags> spotFlags,
@Nullable EnumSet<SpotSortFlags> sortFlags,
APIListCallback<List<Spot>, List<Error>> callback) {
Map<String, String> params = UrlUtil.addSpotParameter(UrlUtil.getUrlParameter(language),
spotFlags);
params = UrlUtil.addSpotSortingParameter(params, sortFlags);
params = UrlUtil.addPagingToUrl(params, pageSize, cursor);
params.put("filter[tags]", JsonListUtil.listToJsonArray(tags, ","));
Call<ResponseBody> call = enduserApiInterface.getSpots(params);
callHandler.enqueListCall(call, callback);
}
/**
* Get list of spots with full-text name search.
*
* @param name Name to searchfor.
* @param pageSize Size for pages. (max 100)
* @param cursor Cursor of last search.
* @param spotFlags {@link SpotFlags}.
* @param sortFlags {@link SpotSortFlags}
* @param callback {@link APIListCallback}
*/
public void searchSpotsByName(String name, int pageSize, @Nullable String cursor,
@Nullable EnumSet<SpotFlags> spotFlags,
@Nullable EnumSet<SpotSortFlags> sortFlags,
APIListCallback<List<Spot>, List<Error>> callback) {
Map<String, String> params = UrlUtil.addSpotParameter(UrlUtil.getUrlParameter(language),
spotFlags);
params = UrlUtil.addSpotSortingParameter(params, sortFlags);
params = UrlUtil.addPagingToUrl(params, pageSize, cursor);
params.put("filter[name]", name);
Call<ResponseBody> call = enduserApiInterface.getSpots(params);
callHandler.enqueListCall(call, callback);
}
/**
* Get the system connected to your api key.
*
* @param callback {@link APIListCallback}.
*/
public void getSystem(final APICallback<System, List<Error>> callback) {
Map<String, String> params = UrlUtil.getUrlParameter(language);
Call<ResponseBody> call = enduserApiInterface.getSystem(params);
callHandler.enqueCall(call, callback);
}
/**
* Get the menu to your system.
*
* @param systemId Systems systemId.
* @param callback {@link APIListCallback}.
*/
public void getMenu(String systemId, final APICallback<Menu, List<Error>> callback) {
Map<String, String> params = UrlUtil.getUrlParameter(language);
Call<ResponseBody> call = enduserApiInterface.getMenu(systemId, params);
callHandler.enqueCall(call, callback);
}
/**
* Get the systemSettings to your system.
*
* @param systemId Systems systemId.
* @param callback {@link APIListCallback}.
*/
public void getSystemSetting(String systemId, final APICallback<SystemSetting, List<Error>> callback) {
Map<String, String> params = UrlUtil.getUrlParameter(language);
Call<ResponseBody> call = enduserApiInterface.getSetting(systemId, params);
callHandler.enqueCall(call, callback);
}
/**
* Get the style to your system.
*
* @param systemId Systems systemId.
* @param callback {@link APIListCallback}.
*/
public void getStyle(String systemId, final APICallback<Style, List<Error>> callback) {
Map<String, String> params = UrlUtil.getUrlParameter(language);
Call<ResponseBody> call = enduserApiInterface.getStyle(systemId, params);
callHandler.enqueCall(call, callback);
}
//getters & setters
public String getSystemLanguage() {
return systemLanguage;
}
public String getLanguage() {
return language;
}
public EnduserApiInterface getEnduserApiInterface() {
return enduserApiInterface;
}
public void setLanguage(String language) {
this.language = language;
}
public CallHandler getCallHandler() {
return callHandler;
}
/**
* Use this to get your instance. It will create a new one with your api key, when
* there is no isntance.
*
* @param apikey Your xamoom api key.
* @return EnduserApi instance.
*/
public static EnduserApi getSharedInstance(@NonNull String apikey) {
if (apikey == null) {
throw new NullPointerException("Apikey should not be null.");
}
if (EnduserApi.sharedInstance == null) {
EnduserApi.sharedInstance = new EnduserApi(apikey);
}
return EnduserApi.sharedInstance;
}
/**
* This will you return your current sharedInstance. Even if it is null.
* @return EnduserApi instance.
*/
public static EnduserApi getSharedInstance() {
if (EnduserApi.sharedInstance == null) {
throw new NullPointerException("Instance is null. Please use getSharedInstance(apikey) " +
"or setSharedInstance");
}
return EnduserApi.sharedInstance;
}
/**
* Set your the sharedInstance with your Instance of EnduserApi.
* @param sharedInstance SharedInstance to save.
*/
public static void setSharedInstance(EnduserApi sharedInstance) {
EnduserApi.sharedInstance = sharedInstance;
}
}
|
package org.codehaus.xfire.client;
import java.lang.reflect.Proxy;
import java.net.MalformedURLException;
import java.util.Collection;
import java.util.Iterator;
import org.codehaus.xfire.XFire;
import org.codehaus.xfire.XFireFactory;
import org.codehaus.xfire.XFireRuntimeException;
import org.codehaus.xfire.service.Binding;
import org.codehaus.xfire.service.Endpoint;
import org.codehaus.xfire.service.Service;
import org.codehaus.xfire.transport.Transport;
public class XFireProxyFactory
{
private XFire xfire;
public XFireProxyFactory()
{
this.xfire = XFireFactory.newInstance().getXFire();
}
public XFireProxyFactory(XFire xfire)
{
this.xfire = xfire;
}
public Object create(Service service, String url)
throws MalformedURLException
{
Collection transports = xfire.getTransportManager().getTransportsForUri(url);
if (transports.size() == 0)
throw new XFireRuntimeException("No Transport is available for url " + url);
Binding binding = null;
Transport transport = null;
for (Iterator itr = transports.iterator(); itr.hasNext() && binding == null;)
{
transport = (Transport) itr.next();
for (int i = 0; i < transport.getSupportedBindings().length; i++)
{
binding = service.getBinding(transport.getSupportedBindings()[i]);
if (binding != null)
break;
}
}
Client client = new Client(transport, binding, url);
return create(client);
}
public Object create(Service service, Transport transport, String url)
throws MalformedURLException
{
return create(new Client(transport, service, url));
}
public Object create(Client client)
{
client.setXFire(xfire);
XFireProxy handler = new XFireProxy(client);
Class serviceClass = client.getService().getServiceInfo().getServiceClass();
return Proxy.newProxyInstance(serviceClass.getClassLoader(),
new Class[]{serviceClass},
handler);
}
public Object create(Endpoint endpoint)
throws MalformedURLException
{
Binding binding = endpoint.getBinding();
Transport t = xfire.getTransportManager().getTransport(binding.getBindingId());
if (t == null)
{
throw new XFireRuntimeException("Could not find transport for binding " +
binding.getBindingId());
}
return create(new Client(t, endpoint));
}
public Object create(Binding binding, String address)
throws MalformedURLException
{
Transport t = xfire.getTransportManager().getTransport(binding.getBindingId());
if (t == null)
{
throw new XFireRuntimeException("Could not find transport for binding " +
binding.getBindingId());
}
Client client = new Client(t, binding, address);
return create(client);
}
}
|
package org.yamcs.web.rest;
import java.io.IOException;
import java.io.StringReader;
import java.io.UncheckedIOException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yamcs.ConnectedClient;
import org.yamcs.YamcsServer;
import org.yamcs.YamcsServerInstance;
import org.yamcs.management.ManagementService;
import org.yamcs.protobuf.Rest.CreateInstanceRequest;
import org.yamcs.protobuf.Rest.ListClientsResponse;
import org.yamcs.protobuf.Rest.ListInstancesResponse;
import org.yamcs.protobuf.YamcsManagement.ClientInfo.ClientState;
import org.yamcs.protobuf.YamcsManagement.YamcsInstance;
import org.yamcs.protobuf.YamcsManagement.YamcsInstance.InstanceState;
import org.yamcs.security.SystemPrivilege;
import org.yamcs.utils.ExceptionUtil;
import org.yamcs.utils.parser.FilterParser;
import org.yamcs.utils.parser.FilterParser.Result;
import org.yamcs.utils.parser.ParseException;
import org.yamcs.utils.parser.TokenMgrError;
import org.yamcs.web.BadRequestException;
import org.yamcs.web.HttpException;
import org.yamcs.web.InternalServerErrorException;
import com.google.common.util.concurrent.UncheckedExecutionException;
/**
* Handles incoming requests related to yamcs instances.
*/
public class InstanceRestHandler extends RestHandler {
private static final Logger log = LoggerFactory.getLogger(RestHandler.class);
public static Pattern ALLOWED_INSTANCE_NAMES = Pattern.compile("\\w[\\w\\.-]*");
@Route(path = "/api/instances", method = "GET")
public void listInstances(RestRequest req) throws HttpException {
Predicate<YamcsServerInstance> filter = getFilter(req.getQueryParameterList("filter"));
ListInstancesResponse.Builder instancesb = ListInstancesResponse.newBuilder();
for (YamcsServerInstance instance : YamcsServer.getInstances()) {
if (filter.test(instance)) {
YamcsInstance enriched = YamcsToGpbAssembler.enrichYamcsInstance(req, instance.getInstanceInfo());
instancesb.addInstance(enriched);
}
}
completeOK(req, instancesb.build());
}
@Route(path = "/api/instances/:instance", method = "GET")
public void getInstance(RestRequest req) throws HttpException {
String instanceName = verifyInstance(req, req.getRouteParam("instance"));
YamcsServerInstance instance = yamcsServer.getInstance(instanceName);
YamcsInstance instanceInfo = instance.getInstanceInfo();
YamcsInstance enriched = YamcsToGpbAssembler.enrichYamcsInstance(req, instanceInfo);
completeOK(req, enriched);
}
@Route(path = "/api/instances/:instance/clients", method = "GET")
public void listClientsForInstance(RestRequest req) throws HttpException {
String instance = verifyInstance(req, req.getRouteParam("instance"));
Set<ConnectedClient> clients = ManagementService.getInstance().getClients();
ListClientsResponse.Builder responseb = ListClientsResponse.newBuilder();
for (ConnectedClient client : clients) {
if (client.getProcessor() != null && instance.equals(client.getProcessor().getInstance())) {
responseb.addClient(YamcsToGpbAssembler.toClientInfo(client, ClientState.CONNECTED));
}
}
completeOK(req, responseb.build());
}
@Route(path = "/api/instances/:instance", method = { "PATCH", "PUT", "POST" })
public void editInstance(RestRequest req) throws HttpException {
checkSystemPrivilege(req, SystemPrivilege.ControlServices);
String instance = verifyInstance(req, req.getRouteParam("instance"));
String state;
if (req.hasQueryParameter("state")) {
state = req.getQueryParameter("state");
} else {
throw new BadRequestException("No state specified");
}
CompletableFuture<YamcsServerInstance> cf;
switch (state.toLowerCase()) {
case "stop":
case "stopped":
if (yamcsServer.getInstance(instance) == null) {
throw new BadRequestException("No instance named '" + instance + "'");
}
cf = CompletableFuture.supplyAsync(() -> {
return yamcsServer.stopInstance(instance);
});
break;
case "restarted":
cf = CompletableFuture.supplyAsync(() -> {
try {
return yamcsServer.restartInstance(instance);
} catch (IOException e) {
throw new UncheckedExecutionException(e);
}
});
break;
case "running":
cf = CompletableFuture.supplyAsync(() -> {
log.info("Starting instance {}", instance);
try {
return yamcsServer.startInstance(instance);
} catch (IOException e) {
throw new UncheckedExecutionException(e);
}
});
break;
default:
throw new BadRequestException("Unsupported service state '" + state + "'");
}
cf.whenComplete((v, error) -> {
if (error == null) {
YamcsInstance enriched = YamcsToGpbAssembler.enrichYamcsInstance(req, v.getInstanceInfo());
completeOK(req, enriched);
} else {
Throwable t = ExceptionUtil.unwind(error);
log.error("Error when changing instance state to {}", state, t);
completeWithError(req, new InternalServerErrorException(t));
}
});
}
@Route(path = "/api/instances", method = { "PATCH", "PUT", "POST" })
public void createInstance(RestRequest req) throws HttpException {
checkSystemPrivilege(req, SystemPrivilege.CreateInstances);
CreateInstanceRequest request = req.bodyAsMessage(CreateInstanceRequest.newBuilder()).build();
if (!request.hasName()) {
throw new BadRequestException("No instance name was specified");
}
String instanceName = request.getName();
if (!ALLOWED_INSTANCE_NAMES.matcher(instanceName).matches()) {
throw new BadRequestException("Invalid instance name");
}
if (!request.hasTemplate()) {
throw new BadRequestException("No template was specified");
}
if (yamcsServer.getInstance(instanceName) != null) {
throw new BadRequestException("An instance named '" + instanceName + "' already exists");
}
CompletableFuture<YamcsServerInstance> cf = CompletableFuture.supplyAsync(() -> {
try {
yamcsServer.createInstance(instanceName, request.getTemplate(),
request.getTemplateArgsMap(),
request.getLabelsMap());
return yamcsServer.startInstance(instanceName);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
});
cf.whenComplete((v, error) -> {
if (error == null) {
YamcsInstance instanceInfo = v.getInstanceInfo();
YamcsInstance enriched = YamcsToGpbAssembler.enrichYamcsInstance(req, instanceInfo);
completeOK(req, enriched);
} else {
Throwable t = ExceptionUtil.unwind(error);
log.error("Error when creating instance {}", instanceName, t);
completeWithError(req, new InternalServerErrorException(t));
}
});
}
private Predicate<YamcsServerInstance> getFilter(List<String> flist) throws HttpException {
if (flist == null) {
return ysi -> true;
}
FilterParser fp = new FilterParser((StringReader) null);
Predicate<YamcsServerInstance> pred = ysi -> true;
for (String filter : flist) {
fp.ReInit(new StringReader(filter));
FilterParser.Result pr;
try {
pr = fp.parse();
pred = pred.and(getPredicate(pr));
} catch (ParseException | TokenMgrError e) {
throw new BadRequestException("Cannot parse the filter '" + filter + "': " + e.getMessage());
}
}
return pred;
}
private Predicate<YamcsServerInstance> getPredicate(Result pr) throws HttpException {
if ("state".equals(pr.key)) {
try {
InstanceState state = InstanceState.valueOf(pr.value.toUpperCase());
switch (pr.op) {
case EQUAL:
return ysi -> ysi.state() == state;
case NOT_EQUAL:
return ysi -> ysi.state() != state;
default:
throw new IllegalStateException("Unknown operator " + pr.op);
}
} catch (IllegalArgumentException e) {
throw new BadRequestException(
"Unknown state '" + pr.value + "'. Valid values are: " + Arrays.asList(InstanceState.values()));
}
} else if (pr.key.startsWith("label:")) {
String labelKey = pr.key.substring(6);
return ysi -> {
Map<String, ?> labels = ysi.getLabels();
if (labels == null) {
return false;
}
Object o = labels.get(labelKey);
if (o == null) {
return false;
}
switch (pr.op) {
case EQUAL:
return pr.value.equals(o);
case NOT_EQUAL:
return !pr.value.equals(o);
default:
throw new IllegalStateException("Unknown operator " + pr.op);
}
};
} else {
throw new BadRequestException("Unknown filter key '" + pr.key + "'");
}
}
}
|
package dr.app.tracer.analysis;
import org.virion.jam.framework.AuxilaryFrame;
import org.virion.jam.framework.DocumentFrame;
import dr.util.Variate;
import dr.app.tracer.application.TracerFileMenuHandler;
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.event.ActionEvent;
import java.io.*;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.*;
public class TemporalAnalysisFrame extends AuxilaryFrame implements TracerFileMenuHandler {
private int binCount;
private double minTime;
private double maxTime;
private boolean rangeSet;
TemporalAnalysisPlotPanel temporalAnalysisPlotPanel = null;
public TemporalAnalysisFrame(DocumentFrame frame, String title, int binCount) {
this(frame, title, binCount, 0.0, 0.0);
rangeSet = false;
}
public TemporalAnalysisFrame(DocumentFrame frame, String title, int binCount, double minTime, double maxTime) {
super(frame);
setTitle(title);
this.binCount = binCount;
this.minTime = minTime;
this.maxTime = maxTime;
rangeSet = true;
temporalAnalysisPlotPanel = new TemporalAnalysisPlotPanel(this);
setContentsPanel(temporalAnalysisPlotPanel);
getSaveAction().setEnabled(false);
getSaveAsAction().setEnabled(false);
getCutAction().setEnabled(false);
getCopyAction().setEnabled(true);
getPasteAction().setEnabled(false);
getDeleteAction().setEnabled(false);
getSelectAllAction().setEnabled(false);
getFindAction().setEnabled(false);
getZoomWindowAction().setEnabled(false);
}
public void initializeComponents() {
setSize(new java.awt.Dimension(640, 480));
}
public void addDemographic(String title, Variate xData,
Variate yDataMean, Variate yDataMedian,
Variate yDataUpper, Variate yDataLower,
double timeMean, double timeMedian,
double timeUpper, double timeLower) {
if (!rangeSet) {
throw new RuntimeException("Range not set");
}
if (getTitle().length() == 0) {
setTitle(title);
}
temporalAnalysisPlotPanel.addDemographicPlot(title, xData, yDataMean, yDataMedian, yDataUpper, yDataLower,
timeMean, timeMedian, timeUpper, timeLower);
setVisible(true);
}
public void addDensity(String title, Variate xData, Variate yData) {
if (!rangeSet) {
throw new RuntimeException("Range not set");
}
temporalAnalysisPlotPanel.addDensityPlot(title, xData, yData);
setVisible(true);
}
public boolean useExportAction() { return true; }
public JComponent getExportableComponent() {
return temporalAnalysisPlotPanel.getExportableComponent();
}
public void doCopy() {
java.awt.datatransfer.Clipboard clipboard =
Toolkit.getDefaultToolkit().getSystemClipboard();
java.awt.datatransfer.StringSelection selection =
new java.awt.datatransfer.StringSelection(this.toString());
clipboard.setContents(selection, selection);
}
public int getBinCount() {
return binCount;
}
public double getMinTime() {
if (!rangeSet) {
throw new RuntimeException("Range not set");
}
return minTime;
}
public double getMaxTime() {
if (!rangeSet) {
throw new RuntimeException("Range not set");
}
return maxTime;
}
public void setRange(double minTime, double maxTime) {
if (rangeSet) {
throw new RuntimeException("Range already set");
}
this.minTime = minTime;
this.maxTime = maxTime;
rangeSet = true;
}
public boolean isRangeSet() {
return rangeSet;
}
public final void doExportData() {
FileDialog dialog = new FileDialog(this,
"Export Data...",
FileDialog.SAVE);
dialog.setVisible(true);
if (dialog.getFile() != null) {
File file = new File(dialog.getDirectory(), dialog.getFile());
try {
FileWriter writer = new FileWriter(file);
writer.write(toString());
writer.close();
} catch (IOException ioe) {
JOptionPane.showMessageDialog(this, "Unable to write file: " + ioe,
"Unable to write file",
JOptionPane.ERROR_MESSAGE);
}
}
}
public final void doExportPDF() {
FileDialog dialog = new FileDialog(this,
"Export PDF Image...",
FileDialog.SAVE);
dialog.setVisible(true);
if (dialog.getFile() != null) {
File file = new File(dialog.getDirectory(), dialog.getFile());
Rectangle2D bounds = temporalAnalysisPlotPanel.getExportableComponent().getBounds();
Document document = new Document(new com.lowagie.text.Rectangle((float)bounds.getWidth(), (float)bounds.getHeight()));
try {
// step 2
PdfWriter writer;
writer = PdfWriter.getInstance(document, new FileOutputStream(file));
// step 3
document.open();
// step 4
PdfContentByte cb = writer.getDirectContent();
PdfTemplate tp = cb.createTemplate((float)bounds.getWidth(), (float)bounds.getHeight());
Graphics2D g2d = tp.createGraphics((float)bounds.getWidth(), (float)bounds.getHeight(), new DefaultFontMapper());
temporalAnalysisPlotPanel.getExportableComponent().print(g2d);
g2d.dispose();
cb.addTemplate(tp, 0, 0);
}
catch(DocumentException de) {
JOptionPane.showMessageDialog(this, "Error writing PDF file: " + de,
"Export PDF Error",
JOptionPane.ERROR_MESSAGE);
}
catch (FileNotFoundException e) {
JOptionPane.showMessageDialog(this, "Error writing PDF file: " + e,
"Export PDF Error",
JOptionPane.ERROR_MESSAGE);
}
document.close();
}
}
public String toString() {
StringBuffer buffer = new StringBuffer();
java.util.List<TemporalAnalysisPlotPanel.AnalysisData> analyses = temporalAnalysisPlotPanel.getAnalysisData();
buffer.append("Time");
for (TemporalAnalysisPlotPanel.AnalysisData analysis : analyses) {
if (analysis.isDemographic) {
buffer.append("\t").append(analysis.title).append("\tMedian\tUpper\tLower");
} else {
buffer.append("\t").append(analysis.title);
}
}
buffer.append("\n");
Variate timeScale = temporalAnalysisPlotPanel.getTimeScale();
for (int i = 0; i < timeScale.getCount(); i++) {
buffer.append(String.valueOf(timeScale.get(i)));
for (TemporalAnalysisPlotPanel.AnalysisData analysis : analyses) {
if (analysis.isDemographic) {
buffer.append("\t");
buffer.append(String.valueOf(analysis.yDataMean.get(i)));
buffer.append("\t");
buffer.append(String.valueOf(analysis.yDataMedian.get(i)));
buffer.append("\t");
buffer.append(String.valueOf(analysis.yDataUpper.get(i)));
buffer.append("\t");
buffer.append(String.valueOf(analysis.yDataLower.get(i)));
} else {
buffer.append("\t");
buffer.append(String.valueOf(analysis.yDataMean.get(i)));
}
}
buffer.append("\n");
}
return buffer.toString();
}
public Action getExportDataAction() {
return exportDataAction;
}
public Action getExportPDFAction() {
return exportPDFAction;
}
private AbstractAction exportDataAction = new AbstractAction("Export Data...") {
public void actionPerformed(ActionEvent ae) {
doExportData();
}
};
private AbstractAction exportPDFAction = new AbstractAction("Export PDF...") {
public void actionPerformed(ActionEvent ae) {
doExportPDF();
}
};
}
|
package dr.evomodel.antigenic;
import dr.evolution.util.Taxa;
import dr.evolution.util.Taxon;
import dr.evolution.util.TaxonList;
import dr.inference.model.*;
import dr.math.MathUtils;
import dr.math.distributions.NormalDistribution;
import dr.stats.Regression;
import dr.util.Author;
import dr.util.Citable;
import dr.util.Citation;
import dr.util.DataTable;
import dr.xml.*;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;
/**
* @author Andrew Rambaut
* @author Trevor Bedford
* @author Marc Suchard
* @version $Id$
*/
public class AntigenicDistancePrior extends AbstractModelLikelihood implements Citable {
public final static String ANTIGENIC_DISTANCE_PRIOR = "antigenicDistancePrior";
public AntigenicDistancePrior(
MatrixParameter locationsParameter,
Parameter datesParameter,
Parameter regressionSlopeParameter,
Parameter regressionPrecisionParameter
) {
super(ANTIGENIC_DISTANCE_PRIOR);
this.locationsParameter = locationsParameter;
addVariable(this.locationsParameter);
this.datesParameter = datesParameter;
addVariable(this.datesParameter);
dimension = locationsParameter.getColumnDimension();
count = locationsParameter.getRowDimension();
this.regressionSlopeParameter = regressionSlopeParameter;
addVariable(regressionSlopeParameter);
regressionSlopeParameter.addBounds(new Parameter.DefaultBounds(Double.MAX_VALUE, 0.0, 1));
this.regressionPrecisionParameter = regressionPrecisionParameter;
addVariable(regressionPrecisionParameter);
regressionPrecisionParameter.addBounds(new Parameter.DefaultBounds(Double.MAX_VALUE, 0.0, 1));
likelihoodKnown = false;
earliestDate = datesParameter.getParameterValue(0);
for (int i=0; i<count; i++) {
double date = datesParameter.getParameterValue(i);
if (earliestDate > date) {
earliestDate = date;
}
}
}
@Override
protected void handleModelChangedEvent(Model model, Object object, int index) {
}
@Override
protected void handleVariableChangedEvent(Variable variable, int index, Variable.ChangeType type) {
if (variable == locationsParameter || variable == datesParameter
|| variable == regressionSlopeParameter || variable == regressionPrecisionParameter) {
likelihoodKnown = false;
}
}
@Override
protected void storeState() {
storedLogLikelihood = logLikelihood;
}
@Override
protected void restoreState() {
logLikelihood = storedLogLikelihood;
likelihoodKnown = false;
}
@Override
protected void acceptState() {
}
@Override
public Model getModel() {
return this;
}
@Override
public double getLogLikelihood() {
if (!likelihoodKnown) {
logLikelihood = computeLogLikelihood();
}
return logLikelihood;
}
private double computeLogLikelihood() {
double precision = regressionPrecisionParameter.getParameterValue(0);
double logLikelihood = (0.5 * Math.log(precision) * count) - (0.5 * precision * sumOfSquaredResiduals());
likelihoodKnown = true;
return logLikelihood;
}
// go through each location and compute sum of squared residuals
// distance from origin increases linearly with time
protected double sumOfSquaredResiduals() {
double ssr = 0.0;
for (int i=0; i < count; i++) {
// expectation of distance with time
double date = datesParameter.getParameterValue(i);
double time = (date-earliestDate);
double beta = regressionSlopeParameter.getParameterValue(0);
double expectedDistance = time * beta;
// observed Euclidean distance from origin
Parameter loc = locationsParameter.getParameter(i);
double observedDistance = 0;
for (int j=0; j < dimension; j++) {
double x = loc.getParameterValue(j);
observedDistance += x * x;
}
observedDistance = Math.sqrt(observedDistance);
ssr += (expectedDistance - observedDistance) * (expectedDistance - observedDistance);
}
return ssr;
}
protected double computeDistance(int rowStrain, int columnStrain) {
if (rowStrain == columnStrain) {
return 0.0;
}
Parameter X = locationsParameter.getParameter(rowStrain);
Parameter Y = locationsParameter.getParameter(columnStrain);
double sum = 0.0;
for (int i = 0; i < dimension; i++) {
double difference = X.getParameterValue(i) - Y.getParameterValue(i);
sum += difference * difference;
}
return Math.sqrt(sum);
}
@Override
public void makeDirty() {
likelihoodKnown = false;
}
private final int dimension;
private final int count;
private final Parameter datesParameter;
private final MatrixParameter locationsParameter;
private final Parameter regressionSlopeParameter;
private final Parameter regressionPrecisionParameter;
private double earliestDate;
private double logLikelihood = 0.0;
private double storedLogLikelihood = 0.0;
private boolean likelihoodKnown = false;
// XMLObjectParser
public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
public final static String LOCATIONS = "locations";
public final static String DATES = "dates";
public final static String REGRESSIONSLOPE = "regressionSlope";
public final static String REGRESSIONPRECISION = "regressionPrecision";
public String getParserName() {
return ANTIGENIC_DISTANCE_PRIOR;
}
public Object parseXMLObject(XMLObject xo) throws XMLParseException {
MatrixParameter locationsParameter = (MatrixParameter) xo.getElementFirstChild(LOCATIONS);
Parameter datesParameter = (Parameter) xo.getElementFirstChild(DATES);
Parameter regressionSlopeParameter = (Parameter) xo.getElementFirstChild(REGRESSIONSLOPE);
Parameter regressionPrecisionParameter = (Parameter) xo.getElementFirstChild(REGRESSIONPRECISION);
AntigenicDistancePrior AGDP = new AntigenicDistancePrior(
locationsParameter,
datesParameter,
regressionSlopeParameter,
regressionPrecisionParameter);
// Logger.getLogger("dr.evomodel").info("Using EvolutionaryCartography model. Please cite:\n" + Utils.getCitationString(AGL));
return AGDP;
}
|
package dr.inference.operators;
import dr.evomodel.continuous.LatentFactorModel;
import dr.inference.distribution.DistributionLikelihood;
import dr.inference.model.MatrixParameter;
import dr.inference.model.Parameter;
import dr.math.distributions.MultivariateNormalDistribution;
import dr.math.distributions.NormalDistribution;
import dr.math.matrixAlgebra.SymmetricMatrix;
import java.util.ArrayList;
import java.util.ListIterator;
public class LoadingsGibbsOperator extends SimpleMCMCOperator implements GibbsOperator{
NormalDistribution prior;
LatentFactorModel LFM;
ArrayList<double[][]> precisionArray;
ArrayList<double[]> meanMidArray;
ArrayList<double[]> meanArray;
MatrixParameter[] vectorProductAnswer;
MatrixParameter[] priorMeanVector;
double priorPrecision;
double priorMeanPrecision;
public LoadingsGibbsOperator(LatentFactorModel LFM, DistributionLikelihood prior, double weight){
setWeight(weight);
this.prior=(NormalDistribution) prior.getDistribution();
this.LFM=LFM;
precisionArray=new ArrayList<double[][]>();
double[][] temp;
for (int i = 0; i < LFM.getFactorDimension() ; i++) {
temp=new double[i+1][i+1];
precisionArray.add(temp);
}
meanArray=new ArrayList<double[]>();
meanMidArray=new ArrayList<double[]>();
double[] tempMean;
for (int i = 0; i < LFM.getFactorDimension() ; i++) {
tempMean=new double[i+1];
meanArray.add(tempMean);
}
for (int i = 0; i < LFM.getFactorDimension() ; i++) {
tempMean=new double[i+1];
meanMidArray.add(tempMean);
}
vectorProductAnswer=new MatrixParameter[LFM.getLoadings().getRowDimension()];
for (int i = 0; i <vectorProductAnswer.length ; i++) {
vectorProductAnswer[i]=new MatrixParameter(null);
vectorProductAnswer[i].setDimensions(i+1, 1);
}
priorMeanVector=new MatrixParameter[LFM.getLoadings().getRowDimension()];
for (int i = 0; i <priorMeanVector.length ; i++) {
priorMeanVector[i]=new MatrixParameter(null, i+1, 1, this.prior.getMean()/(this.prior.getSD()*this.prior.getSD()));
}
priorPrecision= 1/(this.prior.getSD()*this.prior.getSD());
priorMeanPrecision=this.prior.getMean()*priorPrecision;
}
private void getPrecisionOfTruncated(MatrixParameter full, int newRowDimension, double[][] answer){
// MatrixParameter answer=new MatrixParameter(null);
// answer.setDimensions(this.getRowDimension(), Right.getRowDimension());
// System.out.println(answer.getRowDimension());
// System.out.println(answer.getColumnDimension());
int p = full.getColumnDimension();
for (int i = 0; i < newRowDimension; i++) {
for (int j = i; j < newRowDimension; j++) {
double sum = 0;
for (int k = 0; k < p; k++)
sum += full.getParameterValue(i, k) * full.getParameterValue(j,k);
answer[i][j]=sum*LFM.getColumnPrecision().getParameterValue(newRowDimension,newRowDimension);
if(i==j) {
answer[i][j] += priorPrecision;
}
else{
answer[j][i]=answer[i][j];
}
}
}
}
private void getTruncatedMean(int newRowDimension, int dataColumn, double[][] variance, double[] midMean, double[] mean){
// MatrixParameter answer=new MatrixParameter(null);
// answer.setDimensions(this.getRowDimension(), Right.getRowDimension());
// System.out.println(answer.getRowDimension());
// System.out.println(answer.getColumnDimension());
MatrixParameter data=LFM.getScaledData();
MatrixParameter Left=LFM.getFactors();
int p = Left.getColumnDimension();
for (int i = 0; i < newRowDimension; i++) {
double sum = 0;
for (int k = 0; k < p; k++)
sum += Left.getParameterValue(i, k) * data.getParameterValue(dataColumn, k);
sum=sum*LFM.getColumnPrecision().getParameterValue(i,i);
sum+=priorMeanPrecision;
midMean[i]=sum;
}
for (int i = 0; i < newRowDimension; i++) {
double sum = 0;
for (int k = 0; k < newRowDimension; k++)
sum += variance[i][k] * midMean[k];
mean[i]=sum;
}
}
private void getPrecision(int i, double[][] answer){
int size=LFM.getFactorDimension();
if(i<size){
getPrecisionOfTruncated(LFM.getFactors(), i + 1, answer);
}
else{
getPrecisionOfTruncated(LFM.getFactors(), size, answer);
}
}
private void getMean(int i, double[][] variance, double[] midMean, double[] mean){
// Matrix factors=null;
int size=LFM.getFactorDimension();
// double[] scaledDataColumn=LFM.getScaledData().getRowValues(i);
// Vector dataColumn=null;
// Vector priorVector=null;
// Vector temp=null;
// Matrix data=new Matrix(LFM.getScaledData().getParameterAsMatrix());
if(i<size){
getTruncatedMean(i + 1, i, variance, midMean, mean);
// dataColumn=new Vector(data.toComponents()[i]);
// try {
// answer=precision.inverse().product(new Matrix(priorMeanVector[i].add(vectorProductAnswer[i]).getParameterAsMatrix()));
}
else{
getTruncatedMean(size, i, variance, midMean, mean);
// dataColumn=new Vector(data.toComponents()[i]);
// try {
// answer=precision.inverse().product(new Matrix(priorMeanVector[size-1].add(vectorProductAnswer[size-1]).getParameterAsMatrix()));
}
}
private void copy(int i, double[] random){
Parameter changing=LFM.getLoadings().getParameter(i);
for (int j = 0; j <random.length ; j++) {
changing.setParameterValueQuietly(j,random[j]);
}
}
@Override
public int getStepCount() {
return 0; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public String getPerformanceSuggestion() {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public String getOperatorName() {
return "loadingsGibbsOperator"; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public double doOperation() throws OperatorFailedException {
ListIterator<double[][]> currentPrecision=precisionArray.listIterator();
ListIterator<double[]> currentMidMean=meanMidArray.listIterator();
ListIterator<double[]> currentMean=meanArray.listIterator();
double[] draws;
double[][] precision=null;
double[][] variance;
double[] midMean=null;
double[] mean=null;
int size = LFM.getLoadings().getColumnDimension();
for (int i = 0; i < size; i++) {
if(currentPrecision.hasNext()){
precision=currentPrecision.next();}
if(currentMidMean.hasNext())
{midMean=currentMidMean.next();
}
if(currentMean.hasNext()){
mean=currentMean.next();
}
getPrecision(i, precision);
variance=(new SymmetricMatrix(precision)).inverse().toComponents();
getMean(i, variance, mean, midMean);
draws= MultivariateNormalDistribution.nextMultivariateNormalVariance(mean, variance);
if(i<draws.length){
while(draws[i]<0){
draws= MultivariateNormalDistribution.nextMultivariateNormalVariance(mean, variance);
}
}
copy(i, draws);
}
LFM.getLoadings().fireParameterChangedEvent();
return 0; //To change body of implemented methods use File | Settings | File Templates.
}
}
|
package edu.cmu.cs.diamond.opendiamond;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.*;
/**
* Factory to create one or more {@link Search} instances. Instances of this
* class can also be used to generate a <code>Result</code> from an
* <code>ObjectIdentifier</code>.
*
*/
public class SearchFactory {
private final ExecutorService executor = new ThreadPoolExecutor(0,
Integer.MAX_VALUE, 1, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>());
/**
* The maximum length of an attribute name.
*/
public static final int MAX_ATTRIBUTE_NAME = 256;
private final List<Filter> filters;
private final CookieMap cookieMap;
/**
* Constructs a search factory from a collection of filters and a
* cookie map.
*
* @param filters
* a collection of filters to run during a search
* @param cookieMap
* the cookie map to use to look up servers and authenticate
* against
*/
public SearchFactory(Collection<Filter> filters, CookieMap cookieMap) {
this.filters = new ArrayList<Filter>(filters);
this.cookieMap = cookieMap;
}
private static Set<String> copyAndValidateAttributes(Set<String> attributes) {
Set<String> copyOfAttributes = new HashSet<String>(attributes);
for (String string : copyOfAttributes) {
if (string.length() > MAX_ATTRIBUTE_NAME) {
throw new IllegalArgumentException("\"" + string
+ "\" length is greater than MAX_ATTRIBUTE_NAME");
}
}
return copyOfAttributes;
}
@Override
public String toString() {
return filters.toString();
}
/**
* Creates a search from the parameters given when constructing the
* <code>SearchFactory</code>.
*
* @param desiredAttributes
* a set of attribute names to specify which attributes to appear
* in results. May be <code>null</code>, in which case all
* attributes will be included.
* @return a running <code>Search</code>
* @throws IOException
* if an IO error occurs
* @throws InterruptedException
* if the thread is interrupted
*/
public Search createSearch(Set<String> desiredAttributes)
throws IOException, InterruptedException {
final Set<String> pushAttributes;
LoggingFramework logging = LoggingFramework
.createLoggingFramework("createSearch");
logging.saveSearchFactory(this, desiredAttributes);
if (desiredAttributes == null) {
// no filtering requested
pushAttributes = null;
} else {
pushAttributes = copyAndValidateAttributes(desiredAttributes);
}
List<Future<Connection>> futures = new ArrayList<Future<Connection>>();
CompletionService<Connection> connectService = new ExecutorCompletionService<Connection>(
executor);
for (Map.Entry<String, List<Cookie>> e : cookieMap.entrySet()) {
final String hostname = e.getKey();
final List<Cookie> cookieList = e.getValue();
futures.add(connectService.submit(new Callable<Connection>() {
public Connection call() throws Exception {
return Connection.createConnection(hostname, cookieList,
filters);
}
}));
}
// with the connectionCreator, we want to close everything if
// anything failed: we'll need to catch and cleanup for exceptions
InterruptedException ie = null;
IOException ioe = null;
Set<Connection> connections = new HashSet<Connection>();
try {
for (int i = 0; i < futures.size(); i++) {
Future<Connection> f = connectService.take();
// System.out.println(f);
connections.add(f.get());
}
} catch (ExecutionException e1) {
Throwable cause = e1.getCause();
if (cause instanceof IOException) {
IOException e = (IOException) cause;
ioe = new IOException();
ioe.initCause(e);
}
} catch (InterruptedException e2) {
ie = e2;
}
if (ie != null) {
cleanup(futures);
throw ie;
}
if (ioe != null) {
cleanup(futures);
throw ioe;
}
// we're safe
ConnectionSet cs = new ConnectionSet(executor, connections);
Search search = new Search(cs, pushAttributes, logging);
search.start();
return search;
}
private static void cleanup(List<Future<Connection>> futures)
throws InterruptedException {
// System.out.println("cleanup of " + futures);
InterruptedException ie = null;
for (Future<Connection> future : futures) {
try {
// System.out.println(" cleanup ");
Connection c = future.get();
c.close();
} catch (ExecutionException e) {
// e.printStackTrace();
} catch (InterruptedException e) {
ie = e;
}
}
if (ie != null) {
throw ie;
}
}
/**
* Generates a <code>Result</code> from an object identifier.
*
* @param identifier
* the identifier representing the object to evaluate
* @param desiredAttributes
* a set of attribute names to specify which attributes to
* appear. If null, all attributes are returned. For backward
* compatibility, if the set is empty, all attributes are
* returned.
* @return a new result
* @throws IOException
* if an IO error occurs
*/
public Result generateResult(ObjectIdentifier identifier,
Set<String> desiredAttributes) throws IOException {
Set<String> attributes = copyAndValidateAttributes(desiredAttributes);
String host = identifier.getHostname();
String objID = identifier.getObjectID();
List<Cookie> c = cookieMap.get(host);
LoggingFramework logging = LoggingFramework
.createLoggingFramework("generateResult");
logging.saveSearchFactory(this, desiredAttributes);
if (c == null) {
throw new IOException("No cookie found for host " + host);
}
Connection conn = Connection.createConnection(host, c, filters);
Result newResult = reexecute(conn, objID, attributes);
conn.close();
return newResult;
}
/**
* Generates a <code>Result</code> from object data.
*
* @param data
* the data to evaluate
* @param desiredAttributes
* a set of attribute names to specify which attributes to
* appear. If null, all attributes are returned. For backward
* compatibility, if the set is empty, all attributes are
* returned.
* @return a new result
* @throws IOException
* if an IO error occurs
*/
public Result generateResult(byte[] data, Set<String> desiredAttributes)
throws IOException {
Set<String> attributes = copyAndValidateAttributes(desiredAttributes);
Signature signature = new Signature(data);
String objID = signature.asURI().toString();
// pick a host based on the hash code of the signature
String[] hosts = cookieMap.getHosts();
String host = hosts[Math.abs(signature.hashCode()) % hosts.length];
List<Cookie> c = cookieMap.get(host);
LoggingFramework logging = LoggingFramework
.createLoggingFramework("generateResult");
logging.saveSearchFactory(this, desiredAttributes);
// prestart
Connection conn = Connection.createConnection(host, c, filters);
// send eval
Result newResult;
try {
newResult = reexecute(conn, objID, attributes);
} catch (CacheMissException e) {
// send blob
List<byte[]> blobs = new ArrayList<byte[]>();
blobs.add(data);
conn.sendBlobs(blobs);
// retry reexecution
newResult = reexecute(conn, objID, attributes);
}
// close
conn.close();
return newResult;
}
private class CacheMissException extends IOException {}
private Result reexecute(Connection conn, String objID,
Set<String> attributes) throws IOException {
if (attributes != null && attributes.isEmpty()) {
attributes = null;
}
byte reexec[] = new XDR_reexecute(objID, attributes).encode();
// reexecute = 30
MiniRPCReply reply = new RPC(conn, conn.getHostname(), 30, reexec)
.doRPC();
// read reply
if (reply.getMessage().getStatus() == RPC.DIAMOND_FCACHEMISS) {
throw new CacheMissException();
}
reply.checkStatus();
Map<String, byte[]> resultAttributes = new XDR_attr_list(reply
.getMessage().getData()).createMap();
// create result
return new Result(resultAttributes, conn.getHostname());
}
List<Filter> getFilters() {
return filters;
}
CookieMap getCookieMap() {
return cookieMap;
}
}
|
package edu.kaist.mrlab.srdf.modules;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
import edu.kaist.mrlab.srdf.data.Chunk;
import edu.kaist.mrlab.srdf.data.Triple;
public class TripleGenerator {
ArrayList<Chunk> NPChunks;
ArrayList<Chunk> VPChunks;
ArrayList<Triple> triples = new ArrayList<Triple>();
public ArrayList<Triple> getTriples() {
return triples;
}
public void generate() {
Chunk SBJChk = null;
Chunk SBJRELChk = null;
String sbj = "";
String rel = "";
String obj = "";
int SBJID = -1;
boolean isNoSBJ = true;
// NPChunks VPChunks
Collections.sort(NPChunks, new Comparator<Chunk>() {
public int compare(Chunk obj1, Chunk obj2) {
// TODO Auto-generated method stub
return (obj1.getID() < obj2.getID()) ? -1 : (obj1.getID() > obj2.getID()) ? 1 : 0;
}
});
Collections.sort(VPChunks, new Comparator<Chunk>() {
public int compare(Chunk obj1, Chunk obj2) {
// TODO Auto-generated method stub
return (obj1.getID() < obj2.getID()) ? -1 : (obj1.getID() > obj2.getID()) ? 1 : 0;
}
});
if(NPChunks.size() == 0 || VPChunks.size() == 0){
return;
}
// 1. NP_SBJ
// 2. NP_SBJ 2 ID . ,
for (int i = 0; i < NPChunks.size(); i++) {
Chunk tempChk;
if ((tempChk = NPChunks.get(i)).getLabel().equals("NP_SBJ")) {
SBJChk = tempChk;
isNoSBJ = false;
break;
}
}
int fNPID = NPChunks.get(0).getID();
int fVPID = VPChunks.get(0).getID();
int fID = -1;
if (fNPID <= fVPID) {
fID = fNPID;
} else {
fID = fVPID;
}
if (isNoSBJ) {
return;
}
sbj = SBJChk.getChunk();
SBJID = SBJChk.getID();
// relation.
SBJRELChk = VPChunks.get(VPChunks.size() - 1);
rel = SBJRELChk.getChunk() + "
Set<Integer> modArr = new HashSet<Integer>(SBJRELChk.getMod());
if(modArr.size() == 0){
return;
}
int maxMod = Collections.max(modArr);
Chunk tempChk = getChunkByMod(maxMod);
String before = "SBJ";
while (modArr.size() > 0 || maxMod == fID) {
if (tempChk.getLabel().contains("VP")) {
if (before.equals("SBJ")) {
obj = "ANONYMOUS";
// System.out.println(sbj + ", " + rel + ", " + obj);
triples.add(new Triple(sbj, rel, obj));
sbj = rel;
} else if (before.equals("VP")) {
sbj = rel;
rel = tempChk.getChunk() + "
} else {
if (modArr.size() == 1) {
sbj = rel;
rel = tempChk.getChunk() + "
obj = "ANONYMOUS";
// System.out.println(sbj + ", " + rel + ", " + obj);
triples.add(new Triple(sbj, rel, obj));
} else {
rel = tempChk.getChunk() + "
}
}
if (modArr.size() == 0) {
break;
}
maxMod = Collections.max(modArr);
modArr.remove((Object) maxMod);
tempChk = getChunkByMod(maxMod);
if (tempChk.getLabel().contains("VP")) {
modArr.addAll(tempChk.getMod());
}
before = "VP";
} else if (tempChk.getLabel().contains("NP")) {
if (before.contains("SBJ")) {
if (rel.equals("")) {
obj = tempChk.getChunk();
// System.out.println(sbj + ", " + rel + ", " + obj);
triples.add(new Triple(sbj, rel, obj));
modArr.remove((Object) maxMod);
} else {
if (tempChk.getPostposition().equals("") || tempChk.getPostposition().equals("")) {
obj = tempChk.getChunk();
// System.out.println(sbj + ", " + rel + ", " +
// obj);
triples.add(new Triple(sbj, rel, obj));
modArr.remove((Object) maxMod);
sbj = rel;
} else {
obj = "ANONYMOUS";
// System.out.println(sbj + ", " + rel + ", " +
// obj);
triples.add(new Triple(sbj, rel, obj));
sbj = rel;
}
}
} else {
if (maxMod == SBJID) {
if (maxMod == 0 || modArr.size() == 0) {
break;
}
maxMod = Collections.max(modArr);
modArr.remove((Object) maxMod);
tempChk = getChunkByMod(maxMod);
if (tempChk.getLabel().contains("VP")) {
modArr.addAll(tempChk.getMod());
}
continue;
}
if (tempChk.getPostposition().equals("") || tempChk.getPostposition().equals("")) {
obj = tempChk.getChunk();
// System.out.println(sbj + ", " + rel + ", " + obj);
triples.add(new Triple(sbj, rel, obj));
} else {
if (before.contains("VP")) {
obj = "ANONYMOUS";
// System.out.println(sbj + ", " + rel + ", " +
// obj);
triples.add(new Triple(sbj, rel, obj));
sbj = rel;
}
rel = tempChk.getPostposition();
if (rel.equals("")) {
rel = "JOSA";
}
obj = tempChk.getChunk();
// System.out.println(sbj + ", " + rel + ", " + obj);
triples.add(new Triple(sbj, rel, obj));
}
}
if (modArr.size() == 0) {
break;
}
maxMod = Collections.max(modArr);
modArr.remove((Object) maxMod);
tempChk = getChunkByMod(maxMod);
if (tempChk.getLabel().contains("VP")) {
modArr.addAll(tempChk.getMod());
}
before = "NP";
}
}
}
public Chunk getChunkByMod(int mod) {
Chunk c = null;
for (int i = 0; i < NPChunks.size(); i++) {
if ((c = NPChunks.get(i)).getID() == mod) {
return c;
}
}
for (int i = 0; i < VPChunks.size(); i++) {
if ((c = VPChunks.get(i)).getID() == mod) {
return c;
}
}
return c;
}
public TripleGenerator(ArrayList<Chunk> NPChunks, ArrayList<Chunk> VPChunks) {
this.NPChunks = NPChunks;
this.VPChunks = VPChunks;
}
}
|
package edu.nyu.cs.omnidroid.ui;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import edu.nyu.cs.omnidroid.util.AGParser;
import edu.nyu.cs.omnidroid.util.UGParser;
/**
* Presents a list of possible actions that the selected <code>ActionThrower</code> could
* throw as it's action to perform for that OmniHandler.
*
* @author acase
*/
public class ActionThrowerActions extends ListActivity {
private static AGParser ag;
private String eventApp = null;
private String eventName = null;
private String throwerApp = null;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
// Android Boilerplate
super.onCreate(savedInstanceState);
// Initialize our AGParser
ag = new AGParser(getApplicationContext());
// See what application we want to handle events for from the
// intent data passed to us.
Intent i = getIntent();
Bundle extras = i.getExtras();
if (extras != null) {
eventApp = extras.getString(AGParser.KEY_APPLICATION);
eventName = extras.getString(UGParser.KEY_EventApp);
throwerApp = extras.getString(UGParser.KEY_ActionApp);
} else {
// TODO (acase): Throw exception
}
// Getting the Events from AppConfig
ArrayList<HashMap<String, String>> eventList = ag.readEvents(throwerApp);
Iterator<HashMap<String, String>> i1 = eventList.iterator();
ArrayList<String> values = new ArrayList<String>();
while (i1.hasNext()) {
HashMap<String, String> HM1 = i1.next();
Toast.makeText(getBaseContext(), HM1.toString(), 5).show();
// TODO (acase): We need a better way then accessing a hashmap
values.addAll(HM1.values());
//values.add(HM1.get("SMS_Received"));
//values.add(HM1.get("SMS_Sent"));
}
if (values == null)
{
// TODO (acase): Throw exception
}
Iterator<String> iter = values.iterator();
while (iter.hasNext()) {
String eventName = iter.next();
Toast.makeText(getBaseContext(), "List includes = " + eventName, 4).show();
}
/*
setListAdapter(new ArrayAdapter<HashMap<String, String>>(this,
android.R.layout.simple_list_item_1, eventList));
*/
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(arrayAdapter);
getListView().setTextFilterEnabled(true);
Log.i(this.getLocalClassName(), "onCreate exit");
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Intent i = new Intent();
// TODO (acase): Choose Filter page
i.setClass(this.getApplicationContext(), edu.nyu.cs.omnidroid.ui.ActionThrowerData.class);
TextView tv = (TextView) v;
// EventCatcherApp
i.putExtra(AGParser.KEY_APPLICATION, eventApp);
// EventCatcherAction
i.putExtra(AGParser.KEY_EventName, eventName);
// ActionThrowerApp
i.putExtra(AGParser.KEY_APPLICATION, throwerApp);
// ActionThrowerAction
i.putExtra(AGParser.KEY_ActionName, tv.getText());
startActivity(i);
}
}
|
package edu.wheaton.simulator.gui.screen;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.JButton;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import edu.wheaton.simulator.gui.Gui;
import edu.wheaton.simulator.gui.GuiConstants;
import edu.wheaton.simulator.gui.PrefSize;
import edu.wheaton.simulator.gui.SimulatorFacade;
public class LayerScreen extends Screen {
private static final long serialVersionUID = -3839942858274589928L;
private JComboBox agentComboBox;
private JComboBox layerComboBox;
private String[] entities;
private JPanel agentsCBpanel;
private JPanel fieldsCBpanel;
private GridBagConstraints c;
public LayerScreen(SimulatorFacade guiManager) {
super(guiManager);
this.setLayout(new GridBagLayout());
entities = new String[0];
JLabel agents = new JLabel("Agents");
agentComboBox = Gui.makeComboBox(null, null);
agentComboBox.setMinimumSize(GuiConstants.minComboBoxSize);
JLabel layers = new JLabel("Fields");
layerComboBox = Gui.makeComboBox(null, null);
layerComboBox.setMinimumSize(GuiConstants.minComboBoxSize);
final JColorChooser colorTool = Gui.makeColorChooser();
JButton apply = Gui.makeButton("Apply", PrefSize.NULL,
new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
gm.displayLayer(layerComboBox.getSelectedItem().toString(), colorTool.getColor());
gm.getGridPanel().validate();
}
});
JButton clear = Gui.makeButton("Clear", PrefSize.NULL,
new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
//gm.getGridPanel().setLayers(true);
gm.getGridPanel().validate();
gm.getGridPanel().repaint();
}
});
agentsCBpanel = new JPanel();
fieldsCBpanel = new JPanel();
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 0;
c.insets = new Insets(2,5,2,5);
this.add(agents,c);
agentsCBpanel.add(agentComboBox);
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 1;
c.insets = new Insets(2,5,2,5);
this.add(layers,c);
fieldsCBpanel.add(layerComboBox);
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 0;
c.gridy = 2;
c.insets = new Insets(2,5,2,5);
this.add(apply,c);
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 2;
c.insets = new Insets(2,5,2,5);
this.add(clear,c);
JPanel colorPanel = Gui.makeColorChooserPanel(colorTool);
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 0;
c.insets = new Insets(2,5,2,5);
this.add(agentsCBpanel, c);
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridx = 1;
c.gridy = 1;
c.insets = new Insets(2,5,2,5);
this.add(fieldsCBpanel, c);
c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.gridy = 3;
c.insets = new Insets(10,10,10,10);
c.gridwidth = 4;
this.add(colorPanel, c);
this.validate();
}
@Override
public void load() {
entities = new String[0];
entities = gm.getPrototypeNames().toArray(entities);
agentComboBox = new JComboBox(entities);
agentComboBox.setMinimumSize(GuiConstants.minComboBoxSize);
agentComboBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
// To ensure type safety with the "String" combo box, we need
// to convert the objects to strings.
String[] fields = new String[0];
fields = gm
.getPrototype(
agentComboBox.getSelectedItem().toString())
.getCustomFieldMap().keySet().toArray(fields);
layerComboBox = new JComboBox(fields);
layerComboBox.setMinimumSize(GuiConstants.minComboBoxSize);
fieldsCBpanel.removeAll();
fieldsCBpanel.add(layerComboBox);
validate();
repaint();
}
});
if (agentComboBox.getSelectedItem() != null) {
// To ensure type safety with the "String" combo box, we need to
// convert the objects to strings.
String[] fields = new String[0];
fields = gm
.getPrototype(
agentComboBox.getSelectedItem().toString())
.getCustomFieldMap().keySet().toArray(fields);
layerComboBox = new JComboBox(fields);
layerComboBox.setMinimumSize(GuiConstants.minComboBoxSize);
fieldsCBpanel.removeAll();
fieldsCBpanel.add(layerComboBox);
}
else{
layerComboBox.removeAllItems();
}
agentsCBpanel.removeAll();
agentsCBpanel.add(agentComboBox);
}
}
|
package eu.mihosoft.vrl.v3d.ext.org.poly2tri;
import static eu.mihosoft.vrl.v3d.ext.org.poly2tri.TriangulationUtil.EPSILON;
import static eu.mihosoft.vrl.v3d.ext.org.poly2tri.TriangulationUtil.inScanArea;
import static eu.mihosoft.vrl.v3d.ext.org.poly2tri.TriangulationUtil.orient2d;
import static eu.mihosoft.vrl.v3d.ext.org.poly2tri.TriangulationUtil.smartIncircle;
import java.util.List;
import eu.mihosoft.vrl.v3d.ext.org.poly2tri.TriangulationUtil.Orientation;
class DTSweep {
private final static double PI_div2 = Math.PI / 2;
private final static double PI_3div4 = 3 * Math.PI / 4;
public DTSweep() {}
/**
* Triangulate simple polygon with holes *
*/
public static void triangulate(DTSweepContext tcx) {
tcx.createAdvancingFront();
sweep(tcx);
if (tcx.getTriangulationMode() == TriangulationMode.POLYGON) {
finalizationPolygon(tcx);
} else {
finalizationConvexHull(tcx);
}
tcx.done();
}
/**
* Start sweeping the Y-sorted point set from bottom to top
*
* @param tcx
*/
private static void sweep(DTSweepContext tcx) {
List<TriangulationPoint> points;
TriangulationPoint point;
AdvancingFrontNode node;
points = tcx.getPoints();
for (int i = 1; i < points.size(); i++) {
point = points.get(i);
node = pointEvent(tcx, point);
if (point.hasEdges()) {
for (DTSweepConstraint e : point.getEdges()) {
if (tcx.isDebugEnabled()) {
tcx.getDebugContext().setActiveConstraint(e);
}
edgeEvent(tcx, e, node);
}
}
tcx.update(null);
}
}
/**
* If this is a Delaunay Triangulation of a pointset we need to fill so the
* triangle mesh gets a ConvexHull
*
* @param tcx
*/
private static void finalizationConvexHull(DTSweepContext tcx) {
AdvancingFrontNode n1, n2;
DelaunayTriangle t1, t2;
TriangulationPoint first, p1;
n1 = tcx.aFront.head.next;
n2 = n1.next;
first = n1.point;
turnAdvancingFrontConvex(tcx, n1, n2);
// TODO: implement ConvexHull for lower right and left boundary
// Lets remove triangles connected to the two "algorithm" points
// XXX: When the first the nodes are points in a triangle we need to do a
// flip before
// removing triangles or we will lose a valid triangle.
// Same for last three nodes!
// !!! If I implement ConvexHull for lower right and left boundary this fix
// should not be
// needed and the removed triangles will be added again by default
n1 = tcx.aFront.tail.prev;
if (n1.triangle.contains(n1.next.point) && n1.triangle.contains(n1.prev.point)) {
t1 = n1.triangle.neighborAcross(n1.point);
rotateTrianglePair(n1.triangle, n1.point, t1, t1.oppositePoint(n1.triangle, n1.point));
tcx.mapTriangleToNodes(n1.triangle);
tcx.mapTriangleToNodes(t1);
}
n1 = tcx.aFront.head.next;
if (n1.triangle.contains(n1.prev.point) && n1.triangle.contains(n1.next.point)) {
t1 = n1.triangle.neighborAcross(n1.point);
rotateTrianglePair(n1.triangle, n1.point, t1, t1.oppositePoint(n1.triangle, n1.point));
tcx.mapTriangleToNodes(n1.triangle);
tcx.mapTriangleToNodes(t1);
}
// Lower right boundary
first = tcx.aFront.head.point;
n2 = tcx.aFront.tail.prev;
t1 = n2.triangle;
p1 = n2.point;
n2.triangle = null;
do {
tcx.removeFromList(t1);
p1 = t1.pointCCW(p1);
if (p1 == first) {
break;
}
t2 = t1.neighborCCW(p1);
t1.clear();
t1 = t2;
} while (true);
// Lower left boundary
first = tcx.aFront.head.next.point;
p1 = t1.pointCW(tcx.aFront.head.point);
t2 = t1.neighborCW(tcx.aFront.head.point);
t1.clear();
t1 = t2;
while (p1 != first) {
tcx.removeFromList(t1);
p1 = t1.pointCCW(p1);
t2 = t1.neighborCCW(p1);
t1.clear();
t1 = t2;
}
// Remove current head and tail node now that we have removed all triangles
// attached
// to them. Then set new head and tail node points
tcx.aFront.head = tcx.aFront.head.next;
tcx.aFront.head.prev = null;
tcx.aFront.tail = tcx.aFront.tail.prev;
tcx.aFront.tail.next = null;
tcx.finalizeTriangulation();
}
/**
* We will traverse the entire advancing front and fill it to form a convex
* hull.<br>
*/
private static void turnAdvancingFrontConvex(DTSweepContext tcx,
AdvancingFrontNode b,
AdvancingFrontNode c) {
AdvancingFrontNode first = b;
while (c != tcx.aFront.tail) {
if (tcx.isDebugEnabled()) {
tcx.getDebugContext().setActiveNode(c);
}
if (orient2d(b.point, c.point, c.next.point) == Orientation.CCW) {
// [b,c,d] Concave - fill around c
fill(tcx, c);
c = c.next;
} else {
// [b,c,d] Convex
if (b != first && orient2d(b.prev.point, b.point, c.point) == Orientation.CCW) {
// [a,b,c] Concave - fill around b
fill(tcx, b);
b = b.prev;
} else {
// [a,b,c] Convex - nothing to fill
b = c;
c = c.next;
}
}
}
}
private static void finalizationPolygon(DTSweepContext tcx) {
// Get an Internal triangle to start with
DelaunayTriangle t = tcx.aFront.head.next.triangle;
TriangulationPoint p = tcx.aFront.head.next.point;
while (!t.getConstrainedEdgeCW(p)) {
t = t.neighborCCW(p);
}
// Collect interior triangles constrained by edges
tcx.meshClean(t);
}
/**
* Find closes node to the left of the new point and create a new triangle. If
* needed new holes and basins will be filled to.
*
* @param tcx
* @param point
* @return
*/
private static AdvancingFrontNode pointEvent(DTSweepContext tcx,
TriangulationPoint point) {
AdvancingFrontNode node, newNode;
node = tcx.locateNode(point);
if (tcx.isDebugEnabled()) {
tcx.getDebugContext().setActiveNode(node);
}
newNode = newFrontTriangle(tcx, point, node);
// Only need to check +epsilon since point never have smaller
// x value than node due to how we fetch nodes from the front
if (point.getX() <= node.point.getX() + EPSILON) {
fill(tcx, node);
}
tcx.addNode(newNode);
fillAdvancingFront(tcx, newNode);
return newNode;
}
private static AdvancingFrontNode newFrontTriangle(DTSweepContext tcx,
TriangulationPoint point,
AdvancingFrontNode node) {
AdvancingFrontNode newNode;
DelaunayTriangle triangle;
triangle = new DelaunayTriangle(point, node.point, node.next.point);
triangle.markNeighbor(node.triangle);
tcx.addToList(triangle);
newNode = new AdvancingFrontNode(point);
newNode.next = node.next;
newNode.prev = node;
node.next.prev = newNode;
node.next = newNode;
tcx.addNode(newNode); // XXX: BST
if (tcx.isDebugEnabled()) {
tcx.getDebugContext().setActiveNode(newNode);
}
if (!legalize(tcx, triangle)) {
tcx.mapTriangleToNodes(triangle);
}
return newNode;
}
/**
*
*
* @param tcx
* @param edge
* @param node
*/
private static void edgeEvent(DTSweepContext tcx,
DTSweepConstraint edge,
AdvancingFrontNode node) {
try {
tcx.edgeEvent.constrainedEdge = edge;
tcx.edgeEvent.right = edge.p.getX() > edge.q.getX();
if (tcx.isDebugEnabled()) {
tcx.getDebugContext().setPrimaryTriangle(node.triangle);
}
if (isEdgeSideOfTriangle(node.triangle, edge.p, edge.q)) {
return;
}
// For now we will do all needed filling
// TODO: integrate with flip process might give some better performance
// but for now this avoid the issue with cases that needs both flips and
// fills
fillEdgeEvent(tcx, edge, node);
edgeEvent(tcx, edge.p, edge.q, node.triangle, edge.q);
} catch (PointOnEdgeException e) {
System.out.println("Skipping edge: {}" + e.getMessage());
}
}
private static void fillEdgeEvent(DTSweepContext tcx, DTSweepConstraint edge,
AdvancingFrontNode node) {
if (tcx.edgeEvent.right) {
fillRightAboveEdgeEvent(tcx, edge, node);
} else {
fillLeftAboveEdgeEvent(tcx, edge, node);
}
}
private static void fillRightConcaveEdgeEvent(DTSweepContext tcx, DTSweepConstraint edge,
AdvancingFrontNode node) {
fill(tcx, node.next);
if (node.next.point != edge.p) {
// Next above or below edge?
if (orient2d(edge.q, node.next.point, edge.p) == Orientation.CCW) {
// Below
if (orient2d(node.point, node.next.point, node.next.next.point) == Orientation.CCW) {
// Next is concave
fillRightConcaveEdgeEvent(tcx, edge, node);
} else {
// Next is convex
}
}
}
}
private static void fillRightConvexEdgeEvent(DTSweepContext tcx, DTSweepConstraint edge,
AdvancingFrontNode node) {
// Next concave or convex?
if (orient2d(node.next.point, node.next.next.point,
node.next.next.next.point) == Orientation.CCW) {
// Concave
fillRightConcaveEdgeEvent(tcx, edge, node.next);
} else {
// Convex
// Next above or below edge?
if (orient2d(edge.q, node.next.next.point, edge.p) == Orientation.CCW) {
// Below
fillRightConvexEdgeEvent(tcx, edge, node.next);
} else {
// Above
}
}
}
private static void fillRightBelowEdgeEvent(DTSweepContext tcx, DTSweepConstraint edge,
AdvancingFrontNode node) {
if (tcx.isDebugEnabled()) {
tcx.getDebugContext().setActiveNode(node);
}
if (node.point.getX() < edge.p.getX()) // needed?
{
if (orient2d(node.point, node.next.point, node.next.next.point) == Orientation.CCW) {
// Concave
fillRightConcaveEdgeEvent(tcx, edge, node);
} else {
// Convex
fillRightConvexEdgeEvent(tcx, edge, node);
// Retry this one
fillRightBelowEdgeEvent(tcx, edge, node);
}
}
}
private static void fillRightAboveEdgeEvent(DTSweepContext tcx, DTSweepConstraint edge,
AdvancingFrontNode node) {
while (node.next.point.getX() < edge.p.getX()) {
if (tcx.isDebugEnabled()) {
tcx.getDebugContext().setActiveNode(node);
}
// Check if next node is below the edge
Orientation o1 = orient2d(edge.q, node.next.point, edge.p);
if (o1 == Orientation.CCW) {
fillRightBelowEdgeEvent(tcx, edge, node);
} else {
node = node.next;
}
}
}
private static void fillLeftConvexEdgeEvent(DTSweepContext tcx, DTSweepConstraint edge,
AdvancingFrontNode node) {
// Next concave or convex?
if (orient2d(node.prev.point, node.prev.prev.point,
node.prev.prev.prev.point) == Orientation.CW) {
// Concave
fillLeftConcaveEdgeEvent(tcx, edge, node.prev);
} else {
// Convex
// Next above or below edge?
if (orient2d(edge.q, node.prev.prev.point, edge.p) == Orientation.CW) {
// Below
fillLeftConvexEdgeEvent(tcx, edge, node.prev);
} else {
// Above
}
}
}
private static void fillLeftConcaveEdgeEvent(DTSweepContext tcx, DTSweepConstraint edge,
AdvancingFrontNode node) {
fill(tcx, node.prev);
if (node.prev.point != edge.p) {
// Next above or below edge?
if (orient2d(edge.q, node.prev.point, edge.p) == Orientation.CW) {
// Below
if (orient2d(node.point, node.prev.point, node.prev.prev.point) == Orientation.CW) {
// Next is concave
fillLeftConcaveEdgeEvent(tcx, edge, node);
} else {
// Next is convex
}
}
}
}
private static void fillLeftBelowEdgeEvent(DTSweepContext tcx, DTSweepConstraint edge,
AdvancingFrontNode node) {
if (tcx.isDebugEnabled()) {
tcx.getDebugContext().setActiveNode(node);
}
if (node.point.getX() > edge.p.getX()) {
if (orient2d(node.point, node.prev.point, node.prev.prev.point) == Orientation.CW) {
// Concave
fillLeftConcaveEdgeEvent(tcx, edge, node);
} else {
// Convex
fillLeftConvexEdgeEvent(tcx, edge, node);
// Retry this one
fillLeftBelowEdgeEvent(tcx, edge, node);
}
}
}
private static void fillLeftAboveEdgeEvent(DTSweepContext tcx, DTSweepConstraint edge,
AdvancingFrontNode node) {
while (node.prev.point.getX() > edge.p.getX()) {
if (tcx.isDebugEnabled()) {
tcx.getDebugContext().setActiveNode(node);
}
// Check if next node is below the edge
Orientation o1 = orient2d(edge.q, node.prev.point, edge.p);
if (o1 == Orientation.CW) {
fillLeftBelowEdgeEvent(tcx, edge, node);
} else {
node = node.prev;
}
}
}
private static boolean isEdgeSideOfTriangle(DelaunayTriangle triangle,
TriangulationPoint ep,
TriangulationPoint eq) {
int index;
index = triangle.edgeIndex(ep, eq);
if (index != -1) {
triangle.markConstrainedEdge(index);
triangle = triangle.neighbors[index];
if (triangle != null) {
triangle.markConstrainedEdge(ep, eq);
}
return true;
}
return false;
}
private static void edgeEvent(DTSweepContext tcx,
TriangulationPoint ep,
TriangulationPoint eq,
DelaunayTriangle triangle,
TriangulationPoint point) {
TriangulationPoint p1, p2;
if (tcx.isDebugEnabled()) {
tcx.getDebugContext().setPrimaryTriangle(triangle);
}
if (isEdgeSideOfTriangle(triangle, ep, eq)) {
return;
}
p1 = triangle.pointCCW(point);
Orientation o1 = orient2d(eq, p1, ep);
if (o1 == Orientation.Collinear) {
if (triangle.contains(eq, p1)) {
triangle.markConstrainedEdge(eq, p1);
// We are modifying the constraint maybe it would be better to
// not change the given constraint and just keep a variable for the new
// constraint
tcx.edgeEvent.constrainedEdge.q = p1;
triangle = triangle.neighborAcross(point);
edgeEvent(tcx, ep, p1, triangle, p1);
} else {
throw new PointOnEdgeException("EdgeEvent - Point on constrained edge not supported yet");
}
if (tcx.isDebugEnabled()) {
System.out.println("EdgeEvent - Point on constrained edge");
}
return;
}
p2 = triangle.pointCW(point);
Orientation o2 = orient2d(eq, p2, ep);
if (o2 == Orientation.Collinear) {
if (triangle.contains(eq, p2)) {
triangle.markConstrainedEdge(eq, p2);
// We are modifying the constraint maybe it would be better to
// not change the given constraint and just keep a variable for the new
// constraint
tcx.edgeEvent.constrainedEdge.q = p2;
triangle = triangle.neighborAcross(point);
edgeEvent(tcx, ep, p2, triangle, p2);
} else {
throw new PointOnEdgeException("EdgeEvent - Point on constrained edge not supported yet");
}
if (tcx.isDebugEnabled()) {
System.out.println("EdgeEvent - Point on constrained edge");
}
return;
}
if (o1 == o2) {
// Need to decide if we are rotating CW or CCW to get to a triangle
// that will cross edge
if (o1 == Orientation.CW) {
triangle = triangle.neighborCCW(point);
} else {
triangle = triangle.neighborCW(point);
}
edgeEvent(tcx, ep, eq, triangle, point);
} else {
// This triangle crosses constraint so lets flippin start!
flipEdgeEvent(tcx, ep, eq, triangle, point);
}
}
private static void flipEdgeEvent(DTSweepContext tcx,
TriangulationPoint ep,
TriangulationPoint eq,
DelaunayTriangle t,
TriangulationPoint p) {
TriangulationPoint op, newP;
DelaunayTriangle ot;
boolean inScanArea;
ot = t.neighborAcross(p);
op = ot.oppositePoint(t, p);
if (t.getConstrainedEdgeAcross(p)) {
throw new RuntimeException("Intersecting Constraints");
}
if (tcx.isDebugEnabled()) {
tcx.getDebugContext().setPrimaryTriangle(t);
tcx.getDebugContext().setSecondaryTriangle(ot);
} // TODO: remove
inScanArea = inScanArea(p,
t.pointCCW(p),
t.pointCW(p),
op);
if (inScanArea) {
// Lets rotate shared edge one vertex CW
rotateTrianglePair(t, p, ot, op);
tcx.mapTriangleToNodes(t);
tcx.mapTriangleToNodes(ot);
if (p == eq && op == ep) {
if (eq == tcx.edgeEvent.constrainedEdge.q
&& ep == tcx.edgeEvent.constrainedEdge.p) {
if (tcx.isDebugEnabled()) {
System.out.println("[FLIP] - constrained edge done");
} // TODO: remove
t.markConstrainedEdge(ep, eq);
ot.markConstrainedEdge(ep, eq);
legalize(tcx, t);
legalize(tcx, ot);
} else {
if (tcx.isDebugEnabled()) {
System.out.println("[FLIP] - subedge done");
} // TODO: remove
}
} else {
if (tcx.isDebugEnabled()) {
System.out.println("[FLIP] - flipping and continuing with triangle still crossing edge");
} // TODO: remove
Orientation o = orient2d(eq, op, ep);
t = nextFlipTriangle(tcx, o, t, ot, p, op);
flipEdgeEvent(tcx, ep, eq, t, p);
}
} else {
newP = nextFlipPoint(ep, eq, ot, op);
flipScanEdgeEvent(tcx, ep, eq, t, ot, newP);
edgeEvent(tcx, ep, eq, t, p);
}
}
/**
* When we need to traverse from one triangle to the next we need the point in
* current triangle that is the opposite point to the next triangle.
*
* @param ep
* @param eq
* @param ot
* @param op
* @return
*/
private static TriangulationPoint nextFlipPoint(TriangulationPoint ep,
TriangulationPoint eq,
DelaunayTriangle ot,
TriangulationPoint op) {
Orientation o2d = orient2d(eq, op, ep);
if (o2d == Orientation.CW) {
// Right
return ot.pointCCW(op);
} else if (o2d == Orientation.CCW) {
// Left
return ot.pointCW(op);
} else {
// TODO: implement support for point on constraint edge
throw new PointOnEdgeException("Point on constrained edge not supported yet");
}
}
private static DelaunayTriangle nextFlipTriangle(DTSweepContext tcx,
Orientation o,
DelaunayTriangle t,
DelaunayTriangle ot,
TriangulationPoint p,
TriangulationPoint op) {
int edgeIndex;
if (o == Orientation.CCW) {
// ot is not crossing edge after flip
edgeIndex = ot.edgeIndex(p, op);
ot.dEdge[edgeIndex] = true;
legalize(tcx, ot);
ot.clearDelunayEdges();
return t;
}
// t is not crossing edge after flip
edgeIndex = t.edgeIndex(p, op);
t.dEdge[edgeIndex] = true;
legalize(tcx, t);
t.clearDelunayEdges();
return ot;
}
/**
* Scan part of the FlipScan algorithm<br>
* When a triangle pair isn't flippable we will scan for the next point that
* is inside the flip triangle scan area. When found we generate a new
* flipEdgeEvent
*
* @param tcx
* @param ep
* - last point on the edge we are traversing
* @param eq
* - first point on the edge we are traversing
* @param flipTriangle
* - the current triangle sharing the point eq with edge
* @param t
* @param p
*/
private static void flipScanEdgeEvent(DTSweepContext tcx,
TriangulationPoint ep,
TriangulationPoint eq,
DelaunayTriangle flipTriangle,
DelaunayTriangle t,
TriangulationPoint p) {
DelaunayTriangle ot;
TriangulationPoint op, newP;
boolean inScanArea;
ot = t.neighborAcross(p);
op = ot.oppositePoint(t, p);
if (tcx.isDebugEnabled()) {
System.out.println("[FLIP:SCAN] - scan next point"); // TODO: remove
tcx.getDebugContext().setPrimaryTriangle(t);
tcx.getDebugContext().setSecondaryTriangle(ot);
}
inScanArea = inScanArea(eq,
flipTriangle.pointCCW(eq),
flipTriangle.pointCW(eq),
op);
if (inScanArea) {
// flip with new edge op->eq
flipEdgeEvent(tcx, eq, op, ot, op);
// TODO: Actually I just figured out that it should be possible to
// improve this by getting the next ot and op before the the above
// flip and continue the flipScanEdgeEvent here
// set new ot and op here and loop back to inScanArea test
// also need to set a new flipTriangle first
// Turns out at first glance that this is somewhat complicated
// so it will have to wait.
} else {
newP = nextFlipPoint(ep, eq, ot, op);
flipScanEdgeEvent(tcx, ep, eq, flipTriangle, ot, newP);
}
}
/**
* Fills holes in the Advancing Front
*
*
* @param tcx
* @param n
*/
private static void fillAdvancingFront(DTSweepContext tcx, AdvancingFrontNode n) {
AdvancingFrontNode node;
double angle;
// Fill right holes
node = n.next;
while (node.hasNext()) {
if (isLargeHole(node)) {
break;
}
fill(tcx, node);
node = node.next;
}
// Fill left holes
node = n.prev;
while (node.hasPrevious()) {
if (isLargeHole(node)) {
break;
}
fill(tcx, node);
node = node.prev;
}
// Fill right basins
if (n.hasNext() && n.next.hasNext()) {
angle = basinAngle(n);
if (angle < PI_3div4) {
fillBasin(tcx, n);
}
}
}
/**
* @param node
* @return true if hole angle exceeds 90 degrees
*/
private static boolean isLargeHole(AdvancingFrontNode node) {
double angle = angle(node.point, node.next.point, node.prev.point);
// XXX: don't see angle being in range [-pi/2,0] due to how advancing front
// works
// return (angle > PI_div2) || (angle < -PI_div2);
return (angle > PI_div2) || (angle < 0);
// TODO: Adding this fix suggested in issues 48 caused some
// triangulations to fail so commented it out for now.
// Also haven't been able to produce a triangulation that gives the
// problem described in issue 48.
// AdvancingFrontNode nextNode = node.next;
// AdvancingFrontNode prevNode = node.prev;
// if( !AngleExceeds90Degrees(node.point,
// nextNode.point,
// prevNode.point))
// return false;
// // Check additional points on front.
// AdvancingFrontNode next2Node = nextNode.next;
// // "..Plus.." because only want angles on same side as point being added.
// if( (next2Node != null)
// && !AngleExceedsPlus90DegreesOrIsNegative(node.point,
// next2Node.point,
// prevNode.point))
// return false;
// AdvancingFrontNode prev2Node = prevNode.prev;
// // "..Plus.." because only want angles on same side as point being added.
// if( (prev2Node != null)
// && !AngleExceedsPlus90DegreesOrIsNegative(node.point,
// nextNode.point,
// prev2Node.point))
// return false;
// return true;
}
// private static boolean AngleExceeds90Degrees
// TriangulationPoint origin,
// TriangulationPoint pa,
// TriangulationPoint pb
// double angle = angle(origin, pa, pb);
// return (angle > PI_div2) || (angle < -PI_div2);
// private static boolean AngleExceedsPlus90DegreesOrIsNegative
// TriangulationPoint origin,
// TriangulationPoint pa,
// TriangulationPoint pb
// double angle = angle(origin, pa, pb);
// return (angle > PI_div2) || (angle < 0);
/**
* Fills a basin that has formed on the Advancing Front to the right of given
* node.<br>
* First we decide a left,bottom and right node that forms the boundaries of
* the basin. Then we do a reqursive fill.
*
* @param tcx
* @param node
* - starting node, this or next node will be left node
*/
private static void fillBasin(DTSweepContext tcx, AdvancingFrontNode node) {
if (orient2d(node.point, node.next.point, node.next.next.point) == Orientation.CCW) {
tcx.basin.leftNode = node;
} else {
tcx.basin.leftNode = node.next;
}
// Find the bottom and right node
tcx.basin.bottomNode = tcx.basin.leftNode;
while (tcx.basin.bottomNode.hasNext()
&& tcx.basin.bottomNode.point.getY() >= tcx.basin.bottomNode.next.point.getY()) {
tcx.basin.bottomNode = tcx.basin.bottomNode.next;
}
if (tcx.basin.bottomNode == tcx.basin.leftNode) {
// No valid basin
return;
}
tcx.basin.rightNode = tcx.basin.bottomNode;
while (tcx.basin.rightNode.hasNext()
&& tcx.basin.rightNode.point.getY() < tcx.basin.rightNode.next.point.getY()) {
tcx.basin.rightNode = tcx.basin.rightNode.next;
}
if (tcx.basin.rightNode == tcx.basin.bottomNode) {
// No valid basins
return;
}
tcx.basin.width = tcx.basin.rightNode.getPoint().getX() - tcx.basin.leftNode.getPoint().getX();
tcx.basin.leftHighest = tcx.basin.leftNode.getPoint().getY() > tcx.basin.rightNode.getPoint()
.getY();
fillBasinReq(tcx, tcx.basin.bottomNode);
}
/**
* Recursive algorithm to fill a Basin with triangles
*
* @param tcx
* @param node
* - bottomNode
* @param cnt
* - counter used to alternate on even and odd numbers
*/
private static void fillBasinReq(DTSweepContext tcx, AdvancingFrontNode node) {
// if shallow stop filling
if (isShallow(tcx, node)) {
return;
}
fill(tcx, node);
if (node.prev == tcx.basin.leftNode && node.next == tcx.basin.rightNode) {
return;
} else if (node.prev == tcx.basin.leftNode) {
Orientation o = orient2d(node.point, node.next.point, node.next.next.point);
if (o == Orientation.CW) {
return;
}
node = node.next;
} else if (node.next == tcx.basin.rightNode) {
Orientation o = orient2d(node.point, node.prev.point, node.prev.prev.point);
if (o == Orientation.CCW) {
return;
}
node = node.prev;
} else {
// Continue with the neighbor node with lowest Y value
if (node.prev.point.getY() < node.next.point.getY()) {
node = node.prev;
} else {
node = node.next;
}
}
fillBasinReq(tcx, node);
}
private static boolean isShallow(DTSweepContext tcx, AdvancingFrontNode node) {
double height;
if (tcx.basin.leftHighest) {
height = tcx.basin.leftNode.getPoint().getY() - node.getPoint().getY();
} else {
height = tcx.basin.rightNode.getPoint().getY() - node.getPoint().getY();
}
if (tcx.basin.width > height) {
return true;
}
return false;
}
/**
*
* @param node
* - middle node
* @return the angle between p-a and p-b in range [-pi,pi]
*/
private static double angle(TriangulationPoint p,
TriangulationPoint a,
TriangulationPoint b) {
// XXX: do we really need a signed angle for holeAngle?
// could possible save some cycles here
/*
* Complex plane ab = cosA +i*sinA ab = (ax + ay*i)(bx + by*i) = (ax*bx +
* ay*by) + i(ax*by-ay*bx) atan2(y,x) computes the principal value of the
* argument function applied to the complex number x+iy Where x = ax*bx +
* ay*by y = ax*by - ay*bx
*/
final double px = p.getX();
final double py = p.getY();
final double ax = a.getX() - px;
final double ay = a.getY() - py;
final double bx = b.getX() - px;
final double by = b.getY() - py;
return Math.atan2(ax * by - ay * bx, ax * bx + ay * by);
}
/**
* The basin angle is decided against the horizontal line [1,0]
*/
private static double basinAngle(AdvancingFrontNode node) {
double ax = node.point.getX() - node.next.next.point.getX();
double ay = node.point.getY() - node.next.next.point.getY();
return Math.atan2(ay, ax);
}
/**
* Adds a triangle to the advancing front to fill a hole.
*
* @param tcx
* @param node
* - middle node, that is the bottom of the hole
*/
private static void fill(DTSweepContext tcx, AdvancingFrontNode node) {
DelaunayTriangle triangle = new DelaunayTriangle(node.prev.point,
node.point,
node.next.point);
// TODO: should copy the cEdge value from neighbor triangles
triangle.markNeighbor(node.prev.triangle);
triangle.markNeighbor(node.triangle);
tcx.addToList(triangle);
// Update the advancing front
node.prev.next = node.next;
node.next.prev = node.prev;
tcx.removeNode(node);
if (!legalize(tcx, triangle)) {
tcx.mapTriangleToNodes(triangle);
}
}
private static boolean legalize(DTSweepContext tcx,
DelaunayTriangle t) {
int oi;
boolean inside;
TriangulationPoint p, op;
DelaunayTriangle ot;
// violate the Delaunay condition
for (int i = 0; i < 3; i++) {
// TODO: fix so that cEdge is always valid when creating new triangles
// then we can check it here
// instead of below with ot
if (t.dEdge[i]) {
continue;
}
ot = t.neighbors[i];
if (ot != null) {
p = t.points[i];
op = ot.oppositePoint(t, p);
oi = ot.index(op);
// If this is a Constrained Edge or a Delaunay Edge(only during
if (ot.cEdge[oi] || ot.dEdge[oi]) {
t.cEdge[i] = ot.cEdge[oi]; // XXX: have no good way of setting this
// property when creating new triangles so
// lets set it here
continue;
}
inside = smartIncircle(p,
t.pointCCW(p),
t.pointCW(p),
op);
if (inside) {
boolean notLegalized;
// Lets mark this shared edge as Delaunay
t.dEdge[i] = true;
ot.dEdge[oi] = true;
rotateTrianglePair(t, p, ot, op);
// We now got one valid Delaunay Edge shared by two triangles
// This gives us 4 new edges to check for Delaunay
// Make sure that triangle to node mapping is done only one time for a
// specific triangle
notLegalized = !legalize(tcx, t);
if (notLegalized) {
tcx.mapTriangleToNodes(t);
}
notLegalized = !legalize(tcx, ot);
if (notLegalized) {
tcx.mapTriangleToNodes(ot);
}
// Reset the Delaunay edges, since they only are valid Delaunay edges
// until we add a new triangle or point.
// XXX: need to think about this. Can these edges be tried after we
// return to previous recursive level?
t.dEdge[i] = false;
ot.dEdge[oi] = false;
// since
return true;
}
}
}
return false;
}
private static void rotateTrianglePair(DelaunayTriangle t,
TriangulationPoint p,
DelaunayTriangle ot,
TriangulationPoint op) {
DelaunayTriangle n1, n2, n3, n4;
n1 = t.neighborCCW(p);
n2 = t.neighborCW(p);
n3 = ot.neighborCCW(op);
n4 = ot.neighborCW(op);
boolean ce1, ce2, ce3, ce4;
ce1 = t.getConstrainedEdgeCCW(p);
ce2 = t.getConstrainedEdgeCW(p);
ce3 = ot.getConstrainedEdgeCCW(op);
ce4 = ot.getConstrainedEdgeCW(op);
boolean de1, de2, de3, de4;
de1 = t.getDelunayEdgeCCW(p);
de2 = t.getDelunayEdgeCW(p);
de3 = ot.getDelunayEdgeCCW(op);
de4 = ot.getDelunayEdgeCW(op);
t.legalize(p, op);
ot.legalize(op, p);
// Remap dEdge
ot.setDelunayEdgeCCW(p, de1);
t.setDelunayEdgeCW(p, de2);
t.setDelunayEdgeCCW(op, de3);
ot.setDelunayEdgeCW(op, de4);
// Remap cEdge
ot.setConstrainedEdgeCCW(p, ce1);
t.setConstrainedEdgeCW(p, ce2);
t.setConstrainedEdgeCCW(op, ce3);
ot.setConstrainedEdgeCW(op, ce4);
// Remap neighbors
// XXX: might optimize the markNeighbor by keeping track of
// what side should be assigned to what neighbor after the
// rotation. Now mark neighbor does lots of testing to find
// the right side.
t.clearNeighbors();
ot.clearNeighbors();
if (n1 != null) {
ot.markNeighbor(n1);
}
if (n2 != null) {
t.markNeighbor(n2);
}
if (n3 != null) {
t.markNeighbor(n3);
}
if (n4 != null) {
ot.markNeighbor(n4);
}
t.markNeighbor(ot);
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package eu.seebetter.ini.chips.sbret10;
import ch.unizh.ini.jaer.config.MuxControlPanel;
import ch.unizh.ini.jaer.config.OutputMap;
import ch.unizh.ini.jaer.config.boards.LatticeMachFX2config;
import ch.unizh.ini.jaer.config.cpld.CPLDBit;
import ch.unizh.ini.jaer.config.cpld.CPLDConfigValue;
import ch.unizh.ini.jaer.config.cpld.CPLDInt;
import ch.unizh.ini.jaer.config.fx2.PortBit;
import ch.unizh.ini.jaer.config.fx2.TriStateablePortBit;
import ch.unizh.ini.jaer.config.onchip.ChipConfigChain;
import ch.unizh.ini.jaer.config.onchip.OnchipConfigBit;
import ch.unizh.ini.jaer.config.onchip.OutputMux;
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.beans.PropertyChangeSupport;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Observable;
import java.util.Observer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import net.sf.jaer.biasgen.*;
import net.sf.jaer.biasgen.VDAC.VPot;
import net.sf.jaer.biasgen.coarsefine.ShiftedSourceBiasCF;
import net.sf.jaer.biasgen.coarsefine.ShiftedSourceControlsCF;
import net.sf.jaer.chip.AEChip;
import net.sf.jaer.chip.Chip;
import net.sf.jaer.config.ApsDvsConfig;
import net.sf.jaer.hardwareinterface.HardwareInterfaceException;
import net.sf.jaer.util.ParameterControlPanel;
/**
*
* @author Christian
*/
public class SBret10config extends LatticeMachFX2config implements ApsDvsConfig{
protected ShiftedSourceBiasCF ssn, ssp;
JPanel configPanel;
JTabbedPane configTabbedPane;
/** Bias generator power down bit */
/** Creates a new instance of SeeBetterConfig for cDVSTest with a given hardware interface
*@param chip the chip this biasgen belongs to
*/
public SBret10config(Chip chip) {
super(chip);
this.chip = (AEChip)chip;
setName("SBret10 Configuration");
// port bits
addConfigValue(nChipReset);
addConfigValue(powerDown);
addConfigValue(runAdc);
addConfigValue(runCpld);
addConfigValue(extTrigger);
// cpld shift register stuff
addConfigValue(exposureB);
addConfigValue(exposureC);
addConfigValue(resSettle);
addConfigValue(rowSettle);
addConfigValue(colSettle);
addConfigValue(frameDelay);
addConfigValue(padding);
addConfigValue(testPixAPSread);
addConfigValue(useC);
// masterbias
getMasterbias().setKPrimeNFet(55e-3f); // estimated from tox=42A, mu_n=670 cm^2/Vs // TODO fix for UMC18 process
getMasterbias().setMultiplier(4); // =45 correct for dvs320
getMasterbias().setWOverL(4.8f / 2.4f); // masterbias has nfet with w/l=2 at output
getMasterbias().addObserver(this); // changes to masterbias come back to update() here
// shifted sources (not used on SeeBetter10/11)
ssn = new ShiftedSourceBiasCF(this);
ssn.setSex(Pot.Sex.N);
ssn.setName("SSN");
ssn.setTooltipString("n-type shifted source that generates a regulated voltage near ground");
ssn.addObserver(this);
ssn.setAddress(21);
ssp = new ShiftedSourceBiasCF(this);
ssp.setSex(Pot.Sex.P);
ssp.setName("SSP");
ssp.setTooltipString("p-type shifted source that generates a regulated voltage near Vdd");
ssp.addObserver(this);
ssp.setAddress(20);
ssBiases[1] = ssn;
ssBiases[0] = ssp;
setPotArray(new AddressedIPotArray(this));
try {
addAIPot("DiffBn,n,normal,differencing amp");
addAIPot("OnBn,n,normal,DVS brighter threshold");
addAIPot("OffBn,n,normal,DVS darker threshold");
addAIPot("ApsCasEpc,p,cascode,cascode between APS und DVS");
addAIPot("DiffCasBnc,n,cascode,differentiator cascode bias");
addAIPot("ApsROSFBn,n,normal,APS readout source follower bias");
addAIPot("LocalBufBn,n,normal,Local buffer bias"); // TODO what's this?
addAIPot("PixInvBn,n,normal,Pixel request inversion static inverter bias");
addAIPot("PrBp,p,normal,Photoreceptor bias current");
addAIPot("PrSFBp,p,normal,Photoreceptor follower bias current (when used in pixel type)");
addAIPot("RefrBp,p,normal,DVS refractory period current");
addAIPot("AEPdBn,n,normal,Request encoder pulldown static current");
addAIPot("LcolTimeoutBn,n,normal,No column request timeout");
addAIPot("AEPuXBp,p,normal,AER column pullup");
addAIPot("AEPuYBp,p,normal,AER row pullup");
addAIPot("IFThrBn,n,normal,Integrate and fire intensity neuron threshold");
addAIPot("IFRefrBn,n,normal,Integrate and fire intensity neuron refractory period bias current");
addAIPot("PadFollBn,n,normal,Follower-pad buffer bias current");
addAIPot("apsOverflowLevel,n,normal,special overflow level bias ");
addAIPot("biasBuffer,n,normal,special buffer bias ");
} catch (Exception e) {
throw new Error(e.toString());
}
//graphicOptions
videoControl = new VideoControl();
videoControl.addObserver(this);
// on-chip configuration chain
chipConfigChain = new SBRet10ChipConfigChain(chip);
chipConfigChain.addObserver(this);
// control of log readout
apsReadoutControl = new ApsReadoutControl();
setBatchEditOccurring(true);
loadPreference();
setBatchEditOccurring(false);
try {
sendConfiguration(this);
} catch (HardwareInterfaceException ex) {
Logger.getLogger(SBret10.class.getName()).log(Level.SEVERE, null, ex);
}
}
/** Momentarily puts the pixels and on-chip AER logic in reset and then releases the reset.
*
*/
protected void resetChip() {
log.info("resetting AER communication");
nChipReset.set(false);
nChipReset.set(true);
}
/**
*
* Overrides the default method to addConfigValue the custom control panel for configuring the SBret10 output muxes
* and many other chip and board controls.
*
* @return a new panel for controlling this chip and board configuration
*/
@Override
public JPanel buildControlPanel() {
// if(displayControlPanel!=null) return displayControlPanel;
configPanel = new JPanel();
configPanel.setLayout(new BorderLayout());
// add a reset button on top of everything
final Action resetChipAction = new AbstractAction("Reset chip") {
{putValue(Action.SHORT_DESCRIPTION, "Resets the pixels and the AER logic momentarily");}
@Override
public void actionPerformed(ActionEvent evt) {
resetChip();
}
};
JPanel specialButtons = new JPanel();
specialButtons.setLayout(new BoxLayout(specialButtons, BoxLayout.X_AXIS));
specialButtons.add(new JButton(resetChipAction));
configPanel.add(specialButtons, BorderLayout.NORTH);
configTabbedPane = new JTabbedPane();
setBatchEditOccurring(true); // stop updates on building panel
//graphics
JPanel videoControlPanel = new JPanel();
videoControlPanel.setLayout(new BoxLayout(videoControlPanel, BoxLayout.Y_AXIS));
configTabbedPane.add("Video Control", videoControlPanel);
videoControlPanel.add(new ParameterControlPanel(videoControl));
//biasgen
JPanel combinedBiasShiftedSourcePanel = new JPanel();
combinedBiasShiftedSourcePanel.setLayout(new BoxLayout(combinedBiasShiftedSourcePanel, BoxLayout.Y_AXIS));
combinedBiasShiftedSourcePanel.add(super.buildControlPanel());
combinedBiasShiftedSourcePanel.add(new ShiftedSourceControlsCF(ssn));
combinedBiasShiftedSourcePanel.add(new ShiftedSourceControlsCF(ssp));
configTabbedPane.addTab("Bias Current Control", combinedBiasShiftedSourcePanel);
//muxes
configTabbedPane.addTab("Debug Output MUX control", chipConfigChain.buildMuxControlPanel());
//aps readout
JPanel apsReadoutPanel = new JPanel();
apsReadoutPanel.setLayout(new BoxLayout(apsReadoutPanel, BoxLayout.Y_AXIS));
configTabbedPane.add("APS Readout Control", apsReadoutPanel);
apsReadoutPanel.add(new ParameterControlPanel(apsReadoutControl));
//chip config
JPanel chipConfigPanel = chipConfigChain.getChipConfigPanel();
configTabbedPane.addTab("Chip configuration", chipConfigPanel);
configPanel.add(configTabbedPane, BorderLayout.CENTER);
// only select panel after all added
try {
configTabbedPane.setSelectedIndex(chip.getPrefs().getInt("SBret10.bgTabbedPaneSelectedIndex", 0));
} catch (IndexOutOfBoundsException e) {
configTabbedPane.setSelectedIndex(0);
}
// add listener to store last selected tab
configTabbedPane.addMouseListener(
new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent evt) {
tabbedPaneMouseClicked(evt);
}
});
setBatchEditOccurring(false);
return configPanel;
}
/** The central point for communication with HW from biasgen. All objects in SeeBetterConfig are Observables
* and addConfigValue SeeBetterConfig.this as Observer. They then call notifyObservers when their state changes.
* Objects such as ADC store preferences for ADC, and update should update the hardware registers accordingly.
* @param observable IPot, Scanner, etc
* @param object notifyChange - not used at present
*/
@Override
synchronized public void update(Observable observable, Object object) { // thread safe to ensure gui cannot retrigger this while it is sending something
// sends a vendor request depending on type of update
// vendor request is always VR_CONFIG
// value is the type of update
// index is sometimes used for 16 bitmask updates
// bytes are the rest of data
if (isBatchEditOccurring()) {
return;
}
// log.info("update with " + observable);
try {
if (observable instanceof IPot || observable instanceof VPot) { // must send all of the onchip shift register values to replace shift register contents
sendOnChipConfig();
} else if (observable instanceof OutputMux || observable instanceof OnchipConfigBit) {
sendOnChipConfigChain();
} else if (observable instanceof SBRet10ChipConfigChain) {
sendOnChipConfigChain();
} else if (observable instanceof Masterbias) {
powerDown.set(getMasterbias().isPowerDownEnabled());
} else if (observable instanceof TriStateablePortBit) { // tristateable should come first before configbit since it is subclass
TriStateablePortBit b = (TriStateablePortBit) observable;
byte[] bytes = {(byte) ((b.isSet() ? (byte) 1 : (byte) 0) | (b.isHiZ() ? (byte) 2 : (byte) 0))};
sendFx2ConfigCommand(CMD_SETBIT, b.getPortbit(), bytes); // sends value=CMD_SETBIT, index=portbit with (port(b=0,d=1,e=2)<<8)|bitmask(e.g. 00001000) in MSB/LSB, byte[0]= OR of value (1,0), hiZ=2/0, bit is set if tristate, unset if driving port
} else if (observable instanceof PortBit) {
PortBit b = (PortBit) observable;
byte[] bytes = {b.isSet() ? (byte) 1 : (byte) 0};
sendFx2ConfigCommand(CMD_SETBIT, b.getPortbit(), bytes); // sends value=CMD_SETBIT, index=portbit with (port(b=0,d=1,e=2)<<8)|bitmask(e.g. 00001000) in MSB/LSB, byte[0]=value (1,0)
} else if (observable instanceof CPLDConfigValue) {
sendCPLDConfig();
} else if (observable instanceof AddressedIPot) {
sendAIPot((AddressedIPot)observable);
} else {
super.update(observable, object); // super (SeeBetterConfig) handles others, e.g. masterbias
}
} catch (HardwareInterfaceException e) {
log.warning("On update() caught " + e.toString());
}
}
private void tabbedPaneMouseClicked(java.awt.event.MouseEvent evt) {
chip.getPrefs().putInt("SBret10.bgTabbedPaneSelectedIndex", configTabbedPane.getSelectedIndex());
}
/** Controls the APS intensity readout by wrapping the relevant bits */
public class ApsReadoutControl implements Observer {
int channel = chip.getPrefs().getInt("ADC.channel", 3);
public final String EVENT_ADC_ENABLED = "adcEnabled", EVENT_ADC_CHANNEL = "adcChannel";
private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
public final String EVENT_TESTPIXEL = "testpixelEnabled";
public ApsReadoutControl() {
rowSettle.addObserver(this);
colSettle.addObserver(this);
exposureB.addObserver(this);
exposureC.addObserver(this);
resSettle.addObserver(this);
frameDelay.addObserver(this);
testPixAPSread.addObserver(this);
useC.addObserver(this);
}
public boolean isAdcEnabled() {
return runAdc.isSet();
}
public void setAdcEnabled(boolean yes) {
runAdc.set(yes);
}
public void setColSettleCC(int cc) {
colSettle.set(cc);
}
public void setRowSettleCC(int cc) {
rowSettle.set(cc);
}
public void setResSettleCC(int cc) {
resSettle.set(cc);
}
public void setFrameDelayCC(int cc){
frameDelay.set(cc);
}
public void setExposureBDelayCC(int cc){
exposureB.set(cc);
}
public void setExposureCDelayCC(int cc){
exposureC.set(cc);
}
public boolean isTestpixelEnabled() {
SBRet10ChipConfigChain sbcc = (SBRet10ChipConfigChain) chipConfigChain;
return !sbcc.resetTestpixel.isSet();
}
public void setTestpixelEnabled(boolean testpixel) {
SBRet10ChipConfigChain sbcc = (SBRet10ChipConfigChain) chipConfigChain;
sbcc.resetTestpixel.set(testpixel);
}
public boolean isUseC() {
return useC.isSet();
}
public void setUseC(boolean doUseC) {
useC.set(doUseC);
}
public int getColSettleCC() {
return colSettle.get();
}
public int getRowSettleCC() {
return rowSettle.get();
}
public int getResSettleCC() {
return resSettle.get();
}
public int getFrameDelayCC() {
return frameDelay.get();
}
public int getExposureBDelayCC() {
return exposureB.get();
}
public int getExposureCDelayCC() {
return exposureC.get();
}
@Override
public void update(Observable o, Object arg) {
if (o == runAdc) {
propertyChangeSupport.firePropertyChange(EVENT_ADC_ENABLED, null, runAdc.isSet());
} // TODO
}
/**
* @return the propertyChangeSupport
*/
public PropertyChangeSupport getPropertyChangeSupport() {
return propertyChangeSupport;
}
}
public class VideoControl extends Observable implements Observer, HasPreference {
private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
public boolean displayEvents = chip.getPrefs().getBoolean("VideoControl.displayEvents", true);
public boolean displayFrames = chip.getPrefs().getBoolean("VideoControl.displayFrames", true);
public boolean useAutoContrast = chip.getPrefs().getBoolean("VideoControl.useAutoContrast", false);
public float contrast = chip.getPrefs().getFloat("VideoControl.contrast", 1.0f);
public float brightness = chip.getPrefs().getFloat("VideoControl.brightness", 0.0f);
public VideoControl() {
hasPreferenceList.add(this);
}
/**
* @return the displayFrames
*/
public boolean isDisplayFrames() {
return displayFrames;
}
/**
* @param displayFrames the displayFrames to set
*/
public void setDisplayFrames(boolean displayFrames) {
this.displayFrames = displayFrames;
chip.getPrefs().putBoolean("VideoControl.displayFrames", displayFrames);
chip.getAeViewer().interruptViewloop();
}
/**
* @return the displayEvents
*/
public boolean isDisplayEvents() {
return displayEvents;
}
/**
* @param displayEvents the displayEvents to set
*/
public void setDisplayEvents(boolean displayEvents) {
this.displayEvents = displayEvents;
chip.getPrefs().putBoolean("VideoControl.displayEvents", displayEvents);
chip.getAeViewer().interruptViewloop();
}
/**
* @return the displayEvents
*/
public boolean isUseAutoContrast() {
return useAutoContrast;
}
/**
* @param displayEvents the displayEvents to set
*/
public void setUseAutoContrast(boolean useAutoContrast) {
this.useAutoContrast = useAutoContrast;
chip.getPrefs().putBoolean("VideoControl.useAutoContrast", useAutoContrast);
chip.getAeViewer().interruptViewloop();
}
/**
* @return the contrast
*/
public float getContrast() {
return contrast;
}
/**
* @param contrast the contrast to set
*/
public void setContrast(float contrast) {
this.contrast = contrast;
chip.getPrefs().putFloat("VideoControl.contrast", contrast);
chip.getAeViewer().interruptViewloop();
}
/**
* @return the brightness
*/
public float getBrightness() {
return brightness;
}
/**
* @param brightness the brightness to set
*/
public void setBrightness(float brightness) {
this.brightness = brightness;
chip.getPrefs().putFloat("VideoControl.brightness", brightness);
chip.getAeViewer().interruptViewloop();
}
@Override
public void update(Observable o, Object arg) {
setChanged();
notifyObservers(arg);
// if (o == ) {
// propertyChangeSupport.firePropertyChange(EVENT_GRAPHICS_DISPLAY_INTENSITY, null, runAdc.isSet());
// } // TODO
}
/**
* @return the propertyChangeSupport
*/
public PropertyChangeSupport getPropertyChangeSupport() {
return propertyChangeSupport;
}
@Override
public void loadPreference() {
displayFrames = chip.getPrefs().getBoolean("VideoControl.displayFrames", true);
displayEvents = chip.getPrefs().getBoolean("VideoControl.displayEvents", true);
useAutoContrast = chip.getPrefs().getBoolean("VideoControl.useAutoContrast", false);
contrast = chip.getPrefs().getFloat("VideoControl.contrast", 1.0f);
brightness = chip.getPrefs().getFloat("VideoControl.brightness", 0.0f);
}
@Override
public void storePreference() {
chip.getPrefs().putBoolean("VideoControl.displayEvents", displayEvents);
chip.getPrefs().putBoolean("VideoControl.displayFrames", displayFrames);
chip.getPrefs().putBoolean("VideoControl.useAutoContrast", useAutoContrast);
chip.getPrefs().putFloat("VideoControl.contrast", contrast);
chip.getPrefs().putFloat("VideoControl.brightness", brightness);
}
}
@Override
public boolean isDisplayFrames() {
return videoControl.isDisplayFrames();
}
@Override
public void setDisplayFrames(boolean displayFrames) {
videoControl.setDisplayFrames(displayFrames);
}
@Override
public boolean isDisplayEvents() {
return videoControl.isDisplayEvents();
}
@Override
public void setDisplayEvents(boolean displayEvents) {
videoControl.setDisplayEvents(displayEvents);
}
@Override
public boolean isUseAutoContrast(){
return videoControl.isUseAutoContrast();
}
@Override
public void setUseAutoContrast(boolean useAutoContrast){
videoControl.setUseAutoContrast(useAutoContrast);
}
@Override
public float getContrast(){
return videoControl.getContrast();
}
@Override
public void setContrast(float contrast){
videoControl.setContrast(contrast);
}
@Override
public float getBrightness(){
return videoControl.getBrightness();
}
@Override
public void setBrightness(float brightness){
videoControl.setBrightness(brightness);
}
/**
* Formats bits represented in a string as '0' or '1' as a byte array to be sent over the interface to the firmware, for loading
* in big endian bit order, in order of the bytes sent starting with byte 0.
* <p>
* Because the firmware writes integral bytes it is important that the
* bytes sent to the device are padded with leading bits
* (at msbs of first byte) that are finally shifted out of the on-chip shift register.
*
* Therefore <code>bitString2Bytes</code> should only be called ONCE, after the complete bit string has been assembled, unless it is known
* the other bits are an integral number of bytes.
*
* @param bitString in msb to lsb order from left end, where msb will be in msb of first output byte
* @return array of bytes to send
*/
public class SBRet10ChipConfigChain extends ChipConfigChain {
//Config Bits
OnchipConfigBit resetCalib = new OnchipConfigBit(chip, "resetCalib", 0, "turn the calibration neuron off", true),
typeNCalib = new OnchipConfigBit(chip, "typeNCalib", 1, "make the calibration neuron N type", false),
resetTestpixel = new OnchipConfigBit(chip, "resetTestpixel", 2, "keeps the testpixel in reset", true),
hotPixelSuppression = new OnchipConfigBit(chip, "hotPixelSuppression", 3, "turns on the hot pixel suppression", false),
nArow = new OnchipConfigBit(chip, "nArow", 4, "use nArow in the AER state machine", false),
useAout = new OnchipConfigBit(chip, "useAout", 5, "turn the pads for the analog MUX outputs on", true)
;
//Muxes
OutputMux[] amuxes = {new AnalogOutputMux(1), new AnalogOutputMux(2), new AnalogOutputMux(3)};
OutputMux[] dmuxes = {new DigitalOutputMux(1), new DigitalOutputMux(2), new DigitalOutputMux(3), new DigitalOutputMux(4)};
OutputMux[] bmuxes = {new DigitalOutputMux(0)};
ArrayList<OutputMux> muxes = new ArrayList();
MuxControlPanel controlPanel = null;
public SBRet10ChipConfigChain(Chip chip){
super(chip);
this.sbChip = chip;
TOTAL_CONFIG_BITS = 24;
hasPreferenceList.add(this);
configBits = new OnchipConfigBit[6];
configBits[0] = resetCalib;
configBits[1] = typeNCalib;
configBits[2] = resetTestpixel;
configBits[3] = hotPixelSuppression;
configBits[4] = nArow;
configBits[5] = useAout;
for (OnchipConfigBit b : configBits) {
b.addObserver(this);
}
muxes.addAll(Arrays.asList(bmuxes));
muxes.addAll(Arrays.asList(dmuxes)); // 4 digital muxes, first in list since at end of chain - bits must be sent first, before any biasgen bits
muxes.addAll(Arrays.asList(amuxes)); // finally send the 3 voltage muxes
for (OutputMux m : muxes) {
m.addObserver(this);
m.setChip(chip);
}
bmuxes[0].setName("BiasOutMux");
bmuxes[0].put(0,"IFThrBn");
bmuxes[0].put(1,"AEPuYBp");
bmuxes[0].put(2,"AEPuXBp");
bmuxes[0].put(3,"LColTimeout");
bmuxes[0].put(4,"AEPdBn");
bmuxes[0].put(5,"RefrBp");
bmuxes[0].put(6,"PrSFBp");
bmuxes[0].put(7,"PrBp");
bmuxes[0].put(8,"PixInvBn");
bmuxes[0].put(9,"LocalBufBn");
bmuxes[0].put(10,"ApsROSFBn");
bmuxes[0].put(11,"DiffCasBnc");
bmuxes[0].put(12,"ApsCasBpc");
bmuxes[0].put(13,"OffBn");
bmuxes[0].put(14,"OnBn");
bmuxes[0].put(15,"DiffBn");
dmuxes[0].setName("DigMux3");
dmuxes[1].setName("DigMux2");
dmuxes[2].setName("DigMux1");
dmuxes[3].setName("DigMux0");
for (int i = 0; i < 4; i++) {
dmuxes[i].put(0, "AY179right");
dmuxes[i].put(1, "Acol");
dmuxes[i].put(2, "ColArbTopA");
dmuxes[i].put(3, "ColArbTopR");
dmuxes[i].put(4, "FF1");
dmuxes[i].put(5, "FF2");
dmuxes[i].put(6, "Rcarb");
dmuxes[i].put(7, "Rcol");
dmuxes[i].put(8, "Rrow");
dmuxes[i].put(9, "RxarbE");
dmuxes[i].put(10, "nAX0");
dmuxes[i].put(11, "nArowBottom");
dmuxes[i].put(12, "nArowTop");
dmuxes[i].put(13, "nRxOn");
}
dmuxes[3].put(14, "AY179");
dmuxes[3].put(15, "RY179");
dmuxes[2].put(14, "AY179");
dmuxes[2].put(15, "RY179");
dmuxes[1].put(14, "biasCalibSpike");
dmuxes[1].put(15, "nRY179right");
dmuxes[0].put(14, "nResetRxCol");
dmuxes[0].put(15, "nRYtestpixel");
amuxes[0].setName("AnaMux2");
amuxes[1].setName("AnaMux1");
amuxes[2].setName("AnaMux0");
for (int i = 0; i < 3; i++) {
amuxes[i].put(0, "on");
amuxes[i].put(1, "off");
amuxes[i].put(2, "vdiff");
amuxes[i].put(3, "nResetPixel");
amuxes[i].put(4, "pr");
amuxes[i].put(5, "pd");
}
amuxes[0].put(6, "calibNeuron");
amuxes[0].put(7, "nTimeout_AI");
amuxes[1].put(6, "apsgate");
amuxes[1].put(7, "apsout");
amuxes[2].put(6, "apsgate");
amuxes[2].put(7, "apsout");
}
class VoltageOutputMap extends OutputMap {
final void put(int k, int v) {
put(k, v, "Voltage " + k);
}
VoltageOutputMap() {
put(0, 1);
put(1, 3);
put(2, 5);
put(3, 7);
put(4, 9);
put(5, 11);
put(6, 13);
put(7, 15);
}
}
class DigitalOutputMap extends OutputMap {
DigitalOutputMap() {
for (int i = 0; i < 16; i++) {
put(i, i, "DigOut " + i);
}
}
}
class AnalogOutputMux extends OutputMux {
AnalogOutputMux(int n) {
super(sbChip, 4, 8, (OutputMap)(new VoltageOutputMap()));
setName("Voltages" + n);
}
}
class DigitalOutputMux extends OutputMux {
DigitalOutputMux(int n) {
super(sbChip, 4, 16, (OutputMap)(new DigitalOutputMap()));
setName("LogicSignals" + n);
}
}
@Override
public String getBitString(){
//System.out.print("dig muxes ");
String dMuxBits = getMuxBitString(dmuxes);
//System.out.print("config bits ");
String configBits = getConfigBitString();
//System.out.print("analog muxes ");
String aMuxBits = getMuxBitString(amuxes);
//System.out.print("bias muxes ");
String bMuxBits = getMuxBitString(bmuxes);
String chipConfigChain = (dMuxBits + configBits + aMuxBits + bMuxBits);
//System.out.println("On chip config chain: "+chipConfigChain);
return chipConfigChain; // returns bytes padded at end
}
String getMuxBitString(OutputMux[] muxs){
StringBuilder s = new StringBuilder();
for (OutputMux m : muxs) {
s.append(m.getBitString());
}
//System.out.println(s);
return s.toString();
}
String getConfigBitString() {
StringBuilder s = new StringBuilder();
for (int i = 0; i < TOTAL_CONFIG_BITS - configBits.length; i++) {
s.append("0");
}
for (int i = configBits.length - 1; i >= 0; i
s.append(configBits[i].isSet() ? "1" : "0");
}
//System.out.println(s);
return s.toString();
}
@Override
public MuxControlPanel buildMuxControlPanel() {
return new MuxControlPanel(muxes);
}
@Override
public JPanel getChipConfigPanel(){
JPanel chipConfigPanel = new JPanel(new BorderLayout());
//On-Chip config bits
JPanel extraPanel = new JPanel();
extraPanel.setLayout(new BoxLayout(extraPanel, BoxLayout.Y_AXIS));
for (OnchipConfigBit b : configBits) {
extraPanel.add(new JRadioButton(b.getAction()));
}
extraPanel.setBorder(new TitledBorder("Extra on-chip bits"));
chipConfigPanel.add(extraPanel, BorderLayout.NORTH);
//FX2 port bits
JPanel portBitsPanel = new JPanel();
portBitsPanel.setLayout(new BoxLayout(portBitsPanel, BoxLayout.Y_AXIS));
for (PortBit p : portBits) {
portBitsPanel.add(new JRadioButton(p.getAction()));
}
portBitsPanel.setBorder(new TitledBorder("Cypress FX2 port bits"));
chipConfigPanel.add(portBitsPanel, BorderLayout.CENTER);
return chipConfigPanel;
}
}
}
|
/**
*
* $Id: SubmitAction.java,v 1.13 2005-12-02 16:17:09 georgeda Exp $
*
* $Log: not supported by cvs2svn $
* Revision 1.12 2005/10/24 13:28:17 georgeda
* Cleanup changes
*
* Revision 1.11 2005/09/22 18:56:37 georgeda
* Get coordinator from user in properties file
*
* Revision 1.10 2005/09/22 15:18:43 georgeda
* More changes
*
* Revision 1.9 2005/09/16 15:52:55 georgeda
* Changes due to manager re-write
*
*
*/
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.service.AnimalModelManager;
import gov.nih.nci.camod.webapp.form.AnimalModelStateForm;
import java.util.ResourceBundle;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.*;
public class SubmitAction extends BaseAction {
/**
* called from SubmitModels.jsp from list of models links
*
*/
public ActionForward setModelConstants(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
System.out.println("<SubmitAction setModelConstants> modelID="
+ request.getParameter(Constants.Parameters.MODELID));
String modelID = request.getParameter(Constants.Parameters.MODELID);
AnimalModelManager animalModelManager = (AnimalModelManager) getBean("animalModelManager");
String theForward = "AnimalModelTreePopulateAction";
try {
AnimalModel am = animalModelManager.get(modelID);
request.getSession().setAttribute(Constants.MODELID, am.getId().toString());
request.getSession().setAttribute(Constants.MODELDESCRIPTOR, am.getModelDescriptor());
request.getSession().setAttribute(Constants.MODELSTATUS, am.getState());
AnimalModelStateForm theForm = new AnimalModelStateForm();
theForm.setModelId(am.getId().toString());
// Get the coordinator
ResourceBundle theBundle = ResourceBundle.getBundle(Constants.CAMOD_BUNDLE);
String theCoordinator = theBundle.getString(Constants.BundleKeys.COORDINATOR_USERNAME_KEY);
theForm.setAssignedTo(theCoordinator);
request.getSession().setAttribute(Constants.FORMDATA, theForm);
} catch (Exception e) {
log.error("Exception occurred in setModelConstants", e);
// Encountered an error saving the model.
// created a new model successfully
ActionMessages theMsg = new ActionMessages();
theMsg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("errors.admin.message"));
saveErrors(request, theMsg);
theForward = "failure";
}
return mapping.findForward(theForward);
}
}
|
// $Id: LogonPanel.java 4158 2006-05-30 22:12:15Z mdb $
// Narya library - tools for developing networked games
// This library is free software; you can redistribute it and/or modify it
// (at your option) any later version.
// This library is distributed in the hope that it will be useful,
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// You should have received a copy of the GNU Lesser General Public
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
package com.threerings.micasa.client;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import com.samskivert.swing.GroupLayout;
import com.samskivert.swing.HGroupLayout;
import com.samskivert.swing.VGroupLayout;
import com.threerings.util.MessageBundle;
import com.threerings.util.Name;
import com.threerings.presents.client.Client;
import com.threerings.presents.client.ClientObserver;
import com.threerings.presents.client.LogonException;
import com.threerings.presents.net.Credentials;
import com.threerings.presents.net.UsernamePasswordCreds;
import com.threerings.micasa.util.MiCasaContext;
public class LogonPanel extends JPanel
implements ActionListener, ClientObserver
{
public LogonPanel (MiCasaContext ctx)
{
// keep these around for later
_ctx = ctx;
_msgs = _ctx.getMessageManager().getBundle("micasa");
setLayout(new VGroupLayout());
// stick the logon components into a panel that will stretch them
// to a sensible width
JPanel box = new JPanel(
new VGroupLayout(VGroupLayout.NONE, VGroupLayout.STRETCH,
5, VGroupLayout.CENTER)) {
public Dimension getPreferredSize () {
Dimension psize = super.getPreferredSize();
psize.width = Math.max(psize.width, 300);
return psize;
}
};
add(box);
// try obtaining our title text from a system property
String tstr = null;
try {
tstr = System.getProperty("logon.title");
} catch (Throwable t) {
}
if (tstr == null) {
tstr = "Mi Casa!";
}
// create a big fat label
JLabel title = new JLabel(tstr, JLabel.CENTER);
title.setFont(new Font("Helvetica", Font.BOLD, 24));
box.add(title);
// create the username bar
JPanel bar = new JPanel(new HGroupLayout(GroupLayout.STRETCH));
bar.add(new JLabel(_msgs.get("m.username")), GroupLayout.FIXED);
_username = new JTextField();
_username.setActionCommand("skipToPassword");
_username.addActionListener(this);
bar.add(_username);
box.add(bar);
// create the password bar
bar = new JPanel(new HGroupLayout(GroupLayout.STRETCH));
bar.add(new JLabel(_msgs.get("m.password")), GroupLayout.FIXED);
_password = new JPasswordField();
_password.setActionCommand("logon");
_password.addActionListener(this);
bar.add(_password);
box.add(bar);
// create the logon button bar
HGroupLayout gl = new HGroupLayout(GroupLayout.NONE);
gl.setJustification(GroupLayout.RIGHT);
bar = new JPanel(gl);
_logon = new JButton(_msgs.get("m.logon"));
_logon.setActionCommand("logon");
_logon.addActionListener(this);
bar.add(_logon);
box.add(bar);
box.add(new JLabel(_msgs.get("m.status")));
_status = new JTextArea() {
public Dimension getPreferredScrollableViewportSize ()
{
return new Dimension(10, 100);
}
};
_status.setEditable(false);
JScrollPane scroller = new JScrollPane(_status);
box.add(scroller);
// we'll want to listen for logon failure
_ctx.getClient().addClientObserver(this);
// start with focus in the username field
_username.requestFocusInWindow();
}
public void actionPerformed (ActionEvent e)
{
String cmd = e.getActionCommand();
if (cmd.equals("skipToPassword")) {
_password.requestFocusInWindow();
} else if (cmd.equals("logon")) {
logon();
} else {
System.out.println("Unknown action event: " + cmd);
}
}
// documentation inherited from interface
public void clientDidLogon (Client client)
{
_status.append(_msgs.get("m.logon_success") + "\n");
}
// documentation inherited from interface
public void clientDidLogoff (Client client)
{
_status.append(_msgs.get("m.logged_off") + "\n");
setLogonEnabled(true);
}
// documentation inherited from interface
public void clientDidClear (Client client)
{
}
// documentation inherited from interface
public void clientFailedToLogon (Client client, Exception cause)
{
String msg;
if (cause instanceof LogonException) {
msg = MessageBundle.compose("m.logon_failed", cause.getMessage());
} else {
msg = MessageBundle.tcompose("m.logon_failed", cause.getMessage());
}
_status.append(_msgs.xlate(msg) + "\n");
setLogonEnabled(true);
}
// documentation inherited from interface
public void clientObjectDidChange (Client client)
{
// nothing we can do here...
}
// documentation inherited from interface
public void clientConnectionFailed (Client client, Exception cause)
{
String msg = MessageBundle.tcompose("m.connection_failed",
cause.getMessage());
_status.append(_msgs.xlate(msg) + "\n");
setLogonEnabled(true);
}
// documentation inherited from interface
public boolean clientWillLogoff (Client client)
{
// no vetoing here
return true;
}
protected void logon ()
{
// disable further logon attempts until we hear back
setLogonEnabled(false);
Name username = new Name(_username.getText().trim());
String password = new String(_password.getPassword()).trim();
String server = _ctx.getClient().getHostname();
int port = _ctx.getClient().getPorts()[0];
String msg = MessageBundle.tcompose("m.logging_on",
server, String.valueOf(port));
_status.append(_msgs.xlate(msg) + "\n");
// configure the client with some credentials and logon
Credentials creds = new UsernamePasswordCreds(username, password);
Client client = _ctx.getClient();
client.setCredentials(creds);
client.logon();
}
protected void setLogonEnabled (boolean enabled)
{
_username.setEnabled(enabled);
_password.setEnabled(enabled);
_logon.setEnabled(enabled);
}
protected MiCasaContext _ctx;
protected MessageBundle _msgs;
protected JTextField _username;
protected JPasswordField _password;
protected JButton _logon;
protected JTextArea _status;
}
|
// $Id: IsoSceneView.java,v 1.16 2001/07/27 17:54:08 shaper Exp $
package com.threerings.miso.scene;
import com.threerings.miso.Log;
import com.threerings.miso.tile.Tile;
import com.threerings.miso.tile.TileManager;
import com.threerings.miso.util.MathUtil;
import java.awt.*;
import java.awt.image.*;
/**
* The IsoSceneView provides an isometric graphics view of a
* particular scene.
*/
public class IsoSceneView implements EditableSceneView
{
/**
* Construct an IsoSceneView object and initialize it with the
* given tile manager.
*
* @param tmgr the tile manager.
*/
public IsoSceneView (TileManager tmgr)
{
_tmgr = tmgr;
_bounds = new Rectangle(0, 0, DEF_BOUNDS_WIDTH, DEF_BOUNDS_HEIGHT);
_htile = new Point();
_htile.x = _htile.y = -1;
_font = new Font("Arial", Font.PLAIN, 7);
_lineX = new Point[2];
_lineY = new Point[2];
for (int ii = 0; ii < 2; ii++) {
_lineX[ii] = new Point();
_lineY[ii] = new Point();
}
// pre-calculate the unchanging X-axis line
calculateXAxis();
_showCoords = false;
}
/**
* Paint the scene view and any highlighted tiles to the given
* graphics context.
*
* @param g the graphics context.
*/
public void paint (Graphics g)
{
Graphics2D gfx = (Graphics2D)g;
// clip the drawing region to our desired bounds since we
// currently draw tiles willy-nilly in undesirable areas.
Shape oldclip = gfx.getClip();
gfx.setClip(0, 0, _bounds.width, _bounds.height);
// draw the full scene into the offscreen image buffer
renderScene(gfx);
// draw an outline around the highlighted tile
paintHighlightedTile(gfx, _htile.x, _htile.y);
// draw lines illustrating tracking of the mouse position
paintMouseLines(gfx);
// restore the original clipping region
gfx.setClip(oldclip);
}
/**
* Render the scene to the given graphics context.
*
* @param gfx the graphics context.
*/
protected void renderScene (Graphics2D gfx)
{
int mx = 1;
int my = 0;
int screenY = DEF_CENTER_Y;
for (int ii = 0; ii < TILE_RENDER_ROWS; ii++) {
// determine starting tile coordinates
int tx = (ii < Scene.TILE_HEIGHT) ? 0 : mx++;
int ty = my;
// determine number of tiles in this row
int length = (ty - tx) + 1;
// determine starting screen x-position
int screenX = DEF_CENTER_X - ((length) * Tile.HALF_WIDTH);
for (int jj = 0; jj < length; jj++) {
for (int kk = 0; kk < Scene.NUM_LAYERS; kk++) {
// grab the tile we're rendering
Tile tile = _scene.tiles[tx][ty][kk];
if (tile == null) continue;
// determine screen y-position, accounting for
// tile image height
int ypos = screenY - (tile.height - Tile.HEIGHT);
// draw the tile image at the appropriate screen position
gfx.drawImage(tile.img, screenX, ypos, null);
}
// draw tile coordinates in each tile
if (_showCoords) paintCoords(gfx, tx, ty, screenX, screenY);
// each tile is one tile-width to the right of the previous
screenX += Tile.WIDTH;
// advance tile x and decrement tile y as we move to
// the right drawing the row
tx++;
ty
}
// each row is a half-tile-height away from the previous row
screenY += Tile.HALF_HEIGHT;
// advance starting y-axis coordinate unless we've hit bottom
if ((++my) > Scene.TILE_HEIGHT - 1) my = Scene.TILE_HEIGHT - 1;
}
}
/**
* Paint lines showing the most recently calculated x- and y-axis
* mouse position tracking lines, and the mouse position itself.
*
* @param gfx the graphics context.
*/
protected void paintMouseLines (Graphics2D gfx)
{
// draw the baseline x-axis line
gfx.setColor(Color.red);
gfx.drawLine(_lineX[0].x, _lineX[0].y, _lineX[1].x, _lineX[1].y);
// draw line from last mouse pos to baseline
gfx.setColor(Color.yellow);
gfx.drawLine(_lineY[0].x, _lineY[0].y, _lineY[1].x, _lineY[1].y);
// draw the most recent mouse cursor position
gfx.setColor(Color.green);
gfx.fillRect(_lineY[0].x, _lineY[0].y, 2, 2);
gfx.setColor(Color.red);
gfx.drawRect(_lineY[0].x - 1, _lineY[0].y - 1, 3, 3);
}
/**
* Paint the tile coordinate numbers in tile (x, y) whose top-left
* corner is at screen pixel coordinates (sx, sy).
*
* @param gfx the graphics context.
* @param x the tile x-position coordinate.
* @param y the tile y-position coordinate.
* @param sx the screen x-position pixel coordinate.
* @param sy the screen y-position pixel coordinate.
*/
protected void paintCoords (Graphics2D gfx, int x, int y, int sx, int sy)
{
gfx.setFont(_font);
gfx.setColor(Color.white);
gfx.drawString(""+x, sx+Tile.HALF_WIDTH-2, sy+Tile.HALF_HEIGHT-2);
gfx.drawString(""+y, sx+Tile.HALF_WIDTH-2, sy+Tile.HEIGHT-2);
}
/**
* Paint a highlight around the tile at screen pixel coordinates
* (sx, sy).
*
* @param gfx the graphics context.
* @param x the tile x-position coordinate.
* @param y the tile y-position coordinate.
*/
protected void paintHighlightedTile (Graphics2D gfx, int x, int y)
{
Point spos = new Point();
tileToScreen(x, y, spos);
// set the desired stroke and color
Stroke ostroke = gfx.getStroke();
gfx.setStroke(HLT_STROKE);
gfx.setColor(HLT_COLOR);
// draw the tile outline
gfx.drawLine(spos.x, spos.y + Tile.HALF_HEIGHT,
spos.x + Tile.HALF_WIDTH, spos.y);
gfx.drawLine(spos.x + Tile.HALF_WIDTH, spos.y,
spos.x + Tile.WIDTH, spos.y + Tile.HALF_HEIGHT);
gfx.drawLine(spos.x + Tile.WIDTH, spos.y + Tile.HALF_HEIGHT,
spos.x + Tile.HALF_WIDTH, spos.y + Tile.HEIGHT);
gfx.drawLine(spos.x + Tile.HALF_WIDTH, spos.y + Tile.HEIGHT,
spos.x, spos.y + Tile.HALF_HEIGHT);
// restore the original stroke
gfx.setStroke(ostroke);
}
/**
* Highlight the tile at the specified pixel coordinates the next
* time the scene is re-rendered.
*
* @param sx the screen x-position pixel coordinate.
* @param sy the screen y-position pixel coordinate.
*/
public void setHighlightedTile (int sx, int sy)
{
screenToTile(sx, sy, _htile);
}
/**
* Pre-calculate the x-axis line (from tile origin to right end of
* x-axis) for later use in converting tile and screen
* coordinates.
*/
protected void calculateXAxis ()
{
// determine the starting point
_lineX[0].x = DEF_CENTER_X;
_bX = (int)-(SLOPE_X * _lineX[0].x);
_lineX[0].y = DEF_CENTER_Y;
// determine the ending point
_lineX[1].x = _lineX[0].x + (Tile.HALF_WIDTH * Scene.TILE_WIDTH);
_lineX[1].y = _lineX[0].y + (int)((SLOPE_X * _lineX[1].x) + _bX);
}
/**
* Convert the given screen-based pixel coordinates to their
* corresponding tile-based coordinates. Converted coordinates
* are placed in the given point object.
*
* @param sx the screen x-position pixel coordinate.
* @param sy the screen y-position pixel coordinate.
* @param tpos the point object to place coordinates in.
*/
protected void screenToTile (int sx, int sy, Point tpos)
{
// calculate line parallel to the y-axis (from mouse pos to x-axis)
_lineY[0].x = sx;
_lineY[0].y = sy;
int bY = (int)(sy - (SLOPE_Y * sx));
// determine intersection of x- and y-axis lines
_lineY[1].x = (int)((bY - (_bX + DEF_CENTER_Y)) / (SLOPE_X - SLOPE_Y));
_lineY[1].y = (int)((SLOPE_Y * _lineY[1].x) + bY);
// determine distance of mouse pos along the x axis
int xdist = (int) MathUtil.distance(
_lineX[0].x, _lineX[0].y, _lineY[1].x, _lineY[1].y);
tpos.x = (int)(xdist / TILE_EDGE_LENGTH);
// determine distance of mouse pos along the y-axis
int ydist = (int) MathUtil.distance(
_lineY[0].x, _lineY[0].y, _lineY[1].x, _lineY[1].y);
tpos.y = (int)(ydist / TILE_EDGE_LENGTH);
}
/**
* Convert the given tile-based coordinates to their corresponding
* screen-based pixel coordinates. Converted coordinates are
* placed in the given point object.
*
* @param x the tile x-position coordinate.
* @param y the tile y-position coordinate.
* @param spos the point object to place coordinates in.
*/
protected void tileToScreen (int x, int y, Point spos)
{
spos.x = _lineX[0].x + ((x - y - 1) * Tile.HALF_WIDTH);
spos.y = _lineX[0].y + ((x + y) * Tile.HALF_HEIGHT);
}
public void setScene (Scene scene)
{
_scene = scene;
}
public void setShowCoordinates (boolean show)
{
_showCoords = show;
}
public void setTile (int x, int y, int lnum, Tile tile)
{
Point tpos = new Point();
screenToTile(x, y, tpos);
_scene.tiles[tpos.x][tpos.y][lnum] = tile;
}
/** The default width of a scene in pixels. */
protected static final int DEF_BOUNDS_WIDTH = 18 * Tile.WIDTH;
/** The default height of a scene in pixels. */
protected static final int DEF_BOUNDS_HEIGHT = 37 * Tile.HEIGHT;
/** The total number of tile rows to render the full scene view. */
protected static final int TILE_RENDER_ROWS =
(Scene.TILE_WIDTH * Scene.TILE_HEIGHT) - 1;
/** The starting x-position to render the view. */
protected static final int DEF_CENTER_X = DEF_BOUNDS_WIDTH / 2;
/** The starting y-position to render the view. */
protected static final int DEF_CENTER_Y = -(9 * Tile.HEIGHT);
/** The length of a tile edge in pixels from an isometric perspective. */
protected static final float TILE_EDGE_LENGTH = (float)
Math.sqrt((Tile.HALF_WIDTH * Tile.HALF_WIDTH) +
(Tile.HALF_HEIGHT * Tile.HALF_HEIGHT));
/** The color to draw the highlighted tile. */
protected static final Color HLT_COLOR = Color.green;
/** The stroke object used to draw the highlighted tile. */
protected static final Stroke HLT_STROKE = new BasicStroke(3);
/** The slope of the x-axis line. */
protected float SLOPE_X = 0.5f;
/** The slope of the y-axis line. */
protected float SLOPE_Y = -0.5f;
/** The y-intercept of the x-axis line. */
protected int _bX;
/** The last calculated x- and y-axis mouse position tracking lines. */
protected Point _lineX[], _lineY[];
/** The bounds rectangle for the view. */
protected Rectangle _bounds;
/** The currently highlighted tile. */
protected Point _htile;
/** The font to draw tile coordinates. */
protected Font _font;
/** Whether tile coordinates should be drawn. */
protected boolean _showCoords;
/** The scene object to be displayed. */
protected Scene _scene;
/** The tile manager. */
protected TileManager _tmgr;
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package frontend.view.endpoint;
import com.hp.hpl.jena.query.ResultSetRewindable;
import frontend.controller.resource.endpoint.EndpointResource;
import frontend.view.FrontEndView;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import model.SDB;
import view.QueryResult;
import view.QueryStringBuilder;
import view.XMLSerializer;
/**
*
* @author Pumba
*/
public class EndpointReadView extends FrontEndView
{
public EndpointReadView(EndpointResource resource) throws MalformedURLException, TransformerConfigurationException, URISyntaxException
{
super(resource);
setStyleSheet(getController().getServletContext().getResource(XSLT_PATH + "endpoint/" + getClass().getSimpleName() + ".xsl").toURI().toString());
}
@Override
public EndpointResource getResource()
{
return (EndpointResource)super.getResource();
}
@Override
public void display(HttpServletRequest request, HttpServletResponse response) throws IOException, TransformerException, ParserConfigurationException
{
setEndpoint(QueryResult.select(SDB.getDataset(), QueryStringBuilder.build(getController().getServletContext().getResourceAsStream("/WEB-INF/sparql/endpoint/read/endpoint.rq"), getResource().getEndpoint().getURI())));
String queryString = QueryStringBuilder.build(getController().getServletContext().getResourceAsStream("/WEB-INF/sparql/endpoint/read/reports.rq"), getResource().getEndpoint().getURI().toString(), "dateCreated", 0, 20); // QUIRK!!!
setReports(QueryResult.select(SDB.getDataset(), queryString));
super.display(request, response);
}
private void setEndpoint(ResultSetRewindable endpoint)
{
setDocument(XMLSerializer.serialize(endpoint));
}
protected void setReports(ResultSetRewindable reports)
{
getResolver().setArgument("reports", XMLSerializer.serialize(reports));
}
}
|
package org.jaxen.saxpath.base;
import java.util.LinkedList;
import org.jaxen.saxpath.Axis;
import org.jaxen.saxpath.Operator;
import org.jaxen.saxpath.XPathHandler;
import org.jaxen.saxpath.XPathSyntaxException;
import org.jaxen.saxpath.helpers.DefaultXPathHandler;
/** Implementation of SAXPath's <code>XPathReader</code> which
* generates callbacks to an <code>XPathHandler</code>.
*
* @author bob mcwhirter (bob@werken.com)
*/
public class XPathReader extends TokenTypes implements org.jaxen.saxpath.XPathReader
{
private LinkedList tokens;
private XPathLexer lexer;
private XPathHandler handler;
private static XPathHandler defaultHandler = new DefaultXPathHandler();
/**
* Create a new <code>XPathReader</code> with a do-nothing
* <code>XPathHandler</code>.
*/
public XPathReader()
{
setXPathHandler( defaultHandler );
}
public void setXPathHandler(XPathHandler handler)
{
this.handler = handler;
}
public XPathHandler getXPathHandler()
{
return this.handler;
}
public void parse(String xpath) throws org.jaxen.saxpath.SAXPathException
{
setUpParse( xpath );
getXPathHandler().startXPath();
expr();
getXPathHandler().endXPath();
if ( LA(1) != EOF )
{
throwUnexpected();
}
lexer = null;
tokens = null;
}
void setUpParse(String xpath)
{
this.tokens = new LinkedList();
this.lexer = new XPathLexer( xpath );
}
void pathExpr() throws org.jaxen.saxpath.SAXPathException
{
getXPathHandler().startPathExpr();
switch ( LA(1) )
{
case INTEGER:
case DOUBLE:
case LITERAL:
// FIXME parentheses should be allowed when content of parentheses evaluates to a node-set
case LEFT_PAREN:
// case DOLLAR:
{
filterExpr();
if ( LA(1) == SLASH || LA(1) == DOUBLE_SLASH )
{
XPathSyntaxException ex = this.createSyntaxException("Node-set expected");
throw ex;
}
break;
}
case DOLLAR:
{
filterExpr();
if ( LA(1) == SLASH || LA(1) == DOUBLE_SLASH)
{
locationPath( false );
}
break;
}
case IDENTIFIER:
{
if ( ( LA(2) == LEFT_PAREN
&&
! isNodeTypeName( LT(1) ) )
||
( LA(2) == COLON
&&
LA(4) == LEFT_PAREN) )
{
filterExpr();
if ( LA(1) == SLASH || LA(1) == DOUBLE_SLASH)
{
locationPath( false );
}
}
else
{
locationPath( false );
}
break;
}
case DOT:
case DOT_DOT:
case STAR:
case AT:
{
locationPath( false );
break;
}
case SLASH:
case DOUBLE_SLASH:
{
locationPath( true );
break;
}
default:
{
throwUnexpected();
}
}
getXPathHandler().endPathExpr();
}
void numberDouble() throws org.jaxen.saxpath.SAXPathException
{
Token token = match( DOUBLE );
getXPathHandler().number( Double.parseDouble( token.getTokenText() ) );
}
void numberInteger() throws org.jaxen.saxpath.SAXPathException
{
Token token = match( INTEGER );
String text = token.getTokenText();
try {
getXPathHandler().number( Integer.parseInt( text ) );
}
catch (NumberFormatException ex) {
getXPathHandler().number( Double.parseDouble( text ) );
}
}
void literal() throws org.jaxen.saxpath.SAXPathException
{
Token token = match( LITERAL );
getXPathHandler().literal( token.getTokenText() );
}
void functionCall() throws org.jaxen.saxpath.SAXPathException
{
String prefix = null;
String functionName = null;
if ( LA(2) == COLON )
{
prefix = match( IDENTIFIER ).getTokenText();
match( COLON );
}
else
{
prefix = "";
}
functionName = match( IDENTIFIER ).getTokenText();
getXPathHandler().startFunction( prefix,
functionName );
match ( LEFT_PAREN );
arguments();
match ( RIGHT_PAREN );
getXPathHandler().endFunction();
}
void arguments() throws org.jaxen.saxpath.SAXPathException
{
while ( LA(1) != RIGHT_PAREN )
{
expr();
if ( LA(1) == COMMA )
{
match( COMMA );
}
else
{
break;
}
}
}
void filterExpr() throws org.jaxen.saxpath.SAXPathException
{
getXPathHandler().startFilterExpr();
switch ( LA(1) )
{
case INTEGER:
{
numberInteger();
break;
}
case DOUBLE:
{
numberDouble();
break;
}
case LITERAL:
{
literal();
break;
}
case LEFT_PAREN:
{
match( LEFT_PAREN );
expr();
match( RIGHT_PAREN );
break;
}
case IDENTIFIER:
{
functionCall();
break;
}
case DOLLAR:
{
variableReference();
break;
}
}
predicates();
getXPathHandler().endFilterExpr();
}
void variableReference() throws org.jaxen.saxpath.SAXPathException
{
match( DOLLAR );
String prefix = null;
String variableName = null;
if ( LA(2) == COLON )
{
prefix = match( IDENTIFIER ).getTokenText();
match( COLON );
}
else
{
prefix = "";
}
variableName = match( IDENTIFIER ).getTokenText();
getXPathHandler().variableReference( prefix,
variableName );
}
void locationPath(boolean isAbsolute) throws org.jaxen.saxpath.SAXPathException
{
switch ( LA(1) )
{
case SLASH:
case DOUBLE_SLASH:
{
if ( isAbsolute )
{
absoluteLocationPath();
}
else
{
relativeLocationPath();
}
break;
}
case AT:
case IDENTIFIER:
case DOT:
case DOT_DOT:
case STAR:
{
relativeLocationPath();
break;
}
default:
{
throwUnexpected();
break;
}
}
}
void absoluteLocationPath() throws org.jaxen.saxpath.SAXPathException
{
getXPathHandler().startAbsoluteLocationPath();
switch ( LA(1) )
{
case SLASH:
{
match( SLASH );
switch ( LA(1) )
{
case DOT:
case DOT_DOT:
case AT:
case IDENTIFIER:
case STAR:
{
steps();
break;
}
}
break;
}
case DOUBLE_SLASH:
{
getXPathHandler().startAllNodeStep( Axis.DESCENDANT_OR_SELF );
getXPathHandler().endAllNodeStep();
match( DOUBLE_SLASH );
switch ( LA(1) )
{
case DOT:
case DOT_DOT:
case AT:
case IDENTIFIER:
case STAR:
{
steps();
break;
}
default:
XPathSyntaxException ex = this.createSyntaxException("Location path cannot end with
throw ex;
}
break;
}
}
getXPathHandler().endAbsoluteLocationPath();
}
void relativeLocationPath() throws org.jaxen.saxpath.SAXPathException
{
getXPathHandler().startRelativeLocationPath();
switch ( LA(1) )
{
case SLASH:
{
match( SLASH );
break;
}
case DOUBLE_SLASH:
{
getXPathHandler().startAllNodeStep( Axis.DESCENDANT_OR_SELF );
getXPathHandler().endAllNodeStep();
match( DOUBLE_SLASH );
break;
}
}
steps();
getXPathHandler().endRelativeLocationPath();
}
void steps() throws org.jaxen.saxpath.SAXPathException
{
switch ( LA(1) )
{
case DOT:
case DOT_DOT:
case AT:
case IDENTIFIER:
case STAR:
{
step();
break;
}
case EOF:
{
return;
}
default:
{
throw createSyntaxException( "Expected one of '.', '..', '@', '*', <QName>" );
}
}
do
{
if ( ( LA(1) == SLASH)
||
( LA(1) == DOUBLE_SLASH ) )
{
switch ( LA(1) )
{
case SLASH:
{
match( SLASH );
break;
}
case DOUBLE_SLASH:
{
getXPathHandler().startAllNodeStep( Axis.DESCENDANT_OR_SELF );
getXPathHandler().endAllNodeStep();
match( DOUBLE_SLASH );
break;
}
}
}
else
{
return;
}
switch ( LA(1) )
{
case DOT:
case DOT_DOT:
case AT:
case IDENTIFIER:
case STAR:
{
step();
break;
}
default:
{
throw createSyntaxException( "Expected one of '.', '..', '@', '*', <QName>" );
}
}
} while ( true );
}
void step() throws org.jaxen.saxpath.SAXPathException
{
int axis = 0;
switch ( LA(1) )
{
case DOT:
case DOT_DOT:
{
abbrStep();
return;
}
case AT:
{
axis = axisSpecifier();
break;
}
case IDENTIFIER:
{
if ( LA(2) == DOUBLE_COLON )
{
axis = axisSpecifier();
}
else
{
axis = Axis.CHILD;
}
break;
}
case STAR:
{
axis = Axis.CHILD;
break;
}
}
nodeTest( axis );
}
int axisSpecifier() throws org.jaxen.saxpath.SAXPathException
{
int axis = 0;
switch ( LA(1) )
{
case AT:
{
match( AT );
axis = Axis.ATTRIBUTE;
break;
}
case IDENTIFIER:
{
Token token = LT( 1 );
axis = Axis.lookup( token.getTokenText() );
if ( axis == Axis.INVALID_AXIS )
{
throwInvalidAxis( token.getTokenText() );
}
match( IDENTIFIER );
match( DOUBLE_COLON );
break;
}
}
return axis;
}
void nodeTest(int axis) throws org.jaxen.saxpath.SAXPathException
{
switch ( LA(1) )
{
case IDENTIFIER:
{
switch ( LA(2) )
{
case LEFT_PAREN:
{
nodeTypeTest( axis );
break;
}
default:
{
nameTest( axis );
break;
}
}
break;
}
case STAR:
{
nameTest( axis );
break;
}
default:
throw createSyntaxException("Expected <QName> or *");
}
}
void nodeTypeTest(int axis) throws org.jaxen.saxpath.SAXPathException
{
Token nodeTypeToken = match( IDENTIFIER );
String nodeType = nodeTypeToken.getTokenText();
match( LEFT_PAREN );
if ( "processing-instruction".equals( nodeType ) )
{
String piName = "";
if ( LA(1) == LITERAL )
{
piName = match( LITERAL ).getTokenText();
}
match( RIGHT_PAREN );
getXPathHandler().startProcessingInstructionNodeStep( axis,
piName );
predicates();
getXPathHandler().endProcessingInstructionNodeStep();
}
else if ( "node".equals( nodeType ) )
{
match( RIGHT_PAREN );
getXPathHandler().startAllNodeStep( axis );
predicates();
getXPathHandler().endAllNodeStep();
}
else if ( "text".equals( nodeType ) )
{
match( RIGHT_PAREN );
getXPathHandler().startTextNodeStep( axis );
predicates();
getXPathHandler().endTextNodeStep();
}
else if ( "comment".equals( nodeType ) )
{
match( RIGHT_PAREN );
getXPathHandler().startCommentNodeStep( axis );
predicates();
getXPathHandler().endCommentNodeStep();
}
else
{
throw createSyntaxException( "Expected node-type" );
}
}
void nameTest(int axis) throws org.jaxen.saxpath.SAXPathException
{
String prefix = null;
String localName = null;
switch ( LA(2) )
{
case COLON:
{
switch ( LA(1) )
{
case IDENTIFIER:
{
prefix = match( IDENTIFIER ).getTokenText();
match( COLON );
break;
}
}
break;
}
}
switch ( LA(1) )
{
case IDENTIFIER:
{
localName = match( IDENTIFIER ).getTokenText();
break;
}
case STAR:
{
match( STAR );
localName = "*";
break;
}
}
if ( prefix == null )
{
prefix = "";
}
getXPathHandler().startNameStep( axis,
prefix,
localName );
predicates();
getXPathHandler().endNameStep();
}
void abbrStep() throws org.jaxen.saxpath.SAXPathException
{
switch ( LA(1) )
{
case DOT:
{
match( DOT );
getXPathHandler().startAllNodeStep( Axis.SELF );
predicates();
getXPathHandler().endAllNodeStep();
break;
}
case DOT_DOT:
{
match( DOT_DOT );
getXPathHandler().startAllNodeStep( Axis.PARENT );
predicates();
getXPathHandler().endAllNodeStep();
break;
}
}
}
void predicates() throws org.jaxen.saxpath.SAXPathException
{
while (true )
{
if ( LA(1) == LEFT_BRACKET )
{
predicate();
}
else
{
break;
}
}
}
void predicate() throws org.jaxen.saxpath.SAXPathException
{
getXPathHandler().startPredicate();
match( LEFT_BRACKET );
predicateExpr();
match( RIGHT_BRACKET );
getXPathHandler().endPredicate();
}
void predicateExpr() throws org.jaxen.saxpath.SAXPathException
{
expr();
}
void expr() throws org.jaxen.saxpath.SAXPathException
{
orExpr();
}
void orExpr() throws org.jaxen.saxpath.SAXPathException
{
getXPathHandler().startOrExpr();
andExpr();
boolean create = false;
switch ( LA(1) )
{
case OR:
{
create = true;
match( OR );
orExpr();
break;
}
}
getXPathHandler().endOrExpr( create );
}
void andExpr() throws org.jaxen.saxpath.SAXPathException
{
getXPathHandler().startAndExpr();
equalityExpr();
boolean create = false;
switch ( LA(1) )
{
case AND:
{
create = true;
match( AND );
andExpr();
break;
}
}
getXPathHandler().endAndExpr( create );
}
void equalityExpr() throws org.jaxen.saxpath.SAXPathException
{
getXPathHandler().startEqualityExpr();
getXPathHandler().startEqualityExpr();
relationalExpr();
int operator = Operator.NO_OP;
switch ( LA(1) )
{
case EQUALS:
{
match( EQUALS );
relationalExpr();
operator = Operator.EQUALS;
break;
}
case NOT_EQUALS:
{
match( NOT_EQUALS );
relationalExpr();
operator = Operator.NOT_EQUALS;
break;
}
}
getXPathHandler().endEqualityExpr( operator );
operator = Operator.NO_OP;
switch ( LA(1) )
{
case EQUALS:
{
match( EQUALS );
equalityExpr();
operator = Operator.EQUALS;
break;
}
case NOT_EQUALS:
{
match( NOT_EQUALS );
equalityExpr();
operator = Operator.NOT_EQUALS;
break;
}
}
getXPathHandler().endEqualityExpr( operator );
}
void relationalExpr() throws org.jaxen.saxpath.SAXPathException
{
getXPathHandler().startRelationalExpr();
getXPathHandler().startRelationalExpr();
additiveExpr();
int operator = Operator.NO_OP;
switch ( LA(1) )
{
case LESS_THAN:
{
match( LESS_THAN );
additiveExpr();
operator = Operator.LESS_THAN;
break;
}
case GREATER_THAN:
{
match( GREATER_THAN );
additiveExpr();
operator = Operator.GREATER_THAN;
break;
}
case LESS_THAN_EQUALS:
{
match( LESS_THAN_EQUALS );
additiveExpr();
operator = Operator.LESS_THAN_EQUALS;
break;
}
case GREATER_THAN_EQUALS:
{
match( GREATER_THAN_EQUALS );
additiveExpr();
operator = Operator.GREATER_THAN_EQUALS;
break;
}
}
getXPathHandler().endRelationalExpr( operator );
operator = Operator.NO_OP;
switch ( LA(1) )
{
case LESS_THAN:
{
match( LESS_THAN );
relationalExpr();
operator = Operator.LESS_THAN;
break;
}
case GREATER_THAN:
{
match( GREATER_THAN );
relationalExpr();
operator = Operator.GREATER_THAN;
break;
}
case LESS_THAN_EQUALS:
{
match( LESS_THAN_EQUALS );
relationalExpr();
operator = Operator.LESS_THAN_EQUALS;
break;
}
case GREATER_THAN_EQUALS:
{
match( GREATER_THAN_EQUALS );
relationalExpr();
operator = Operator.GREATER_THAN_EQUALS;
break;
}
}
getXPathHandler().endRelationalExpr( operator );
}
void additiveExpr() throws org.jaxen.saxpath.SAXPathException
{
getXPathHandler().startAdditiveExpr();
getXPathHandler().startAdditiveExpr();
multiplicativeExpr();
int operator = Operator.NO_OP;
switch ( LA(1) )
{
case PLUS:
{
match( PLUS );
operator = Operator.ADD;
multiplicativeExpr();
break;
}
case MINUS:
{
match( MINUS );
operator = Operator.SUBTRACT;
multiplicativeExpr();
break;
}
}
getXPathHandler().endAdditiveExpr( operator );
operator = Operator.NO_OP;
switch ( LA(1) )
{
case PLUS:
{
match( PLUS );
operator = Operator.ADD;
additiveExpr();
break;
}
case MINUS:
{
match( MINUS );
operator = Operator.SUBTRACT;
additiveExpr();
break;
}
default:
{
operator = Operator.NO_OP;
break;
}
}
getXPathHandler().endAdditiveExpr( operator );
}
void multiplicativeExpr() throws org.jaxen.saxpath.SAXPathException
{
getXPathHandler().startMultiplicativeExpr();
getXPathHandler().startMultiplicativeExpr();
unaryExpr();
int operator = Operator.NO_OP;
switch ( LA(1) )
{
case STAR:
{
match( STAR );
unaryExpr();
operator = Operator.MULTIPLY;
break;
}
case DIV:
{
match( DIV );
unaryExpr();
operator = Operator.DIV;
break;
}
case MOD:
{
match( MOD );
unaryExpr();
operator = Operator.MOD;
break;
}
}
getXPathHandler().endMultiplicativeExpr( operator );
operator = Operator.NO_OP;
switch ( LA(1) )
{
case STAR:
{
match( STAR );
multiplicativeExpr();
operator = Operator.MULTIPLY;
break;
}
case DIV:
{
match( DIV );
multiplicativeExpr();
operator = Operator.DIV;
break;
}
case MOD:
{
match( MOD );
multiplicativeExpr();
operator = Operator.MOD;
break;
}
}
getXPathHandler().endMultiplicativeExpr( operator );
}
void unaryExpr() throws org.jaxen.saxpath.SAXPathException
{
getXPathHandler().startUnaryExpr();
int operator = Operator.NO_OP;
switch ( LA(1) )
{
case MINUS:
{
match( MINUS );
operator = Operator.NEGATIVE;
unaryExpr();
break;
}
default:
{
unionExpr();
break;
}
}
getXPathHandler().endUnaryExpr( operator );
}
void unionExpr() throws org.jaxen.saxpath.SAXPathException
{
getXPathHandler().startUnionExpr();
pathExpr();
boolean create = false;
switch ( LA(1) )
{
case PIPE:
{
match( PIPE );
create = true;
expr();
break;
}
}
getXPathHandler().endUnionExpr( create );
}
Token match(int tokenType) throws XPathSyntaxException
{
LT(1);
Token token = (Token) tokens.get( 0 );
if ( token.getTokenType() == tokenType )
{
tokens.removeFirst();
return token;
}
throw createSyntaxException( "Expected: " + getTokenText( tokenType ) );
}
int LA(int position)
{
return LT(position).getTokenType();
}
Token LT(int position)
{
if ( tokens.size() <= ( position - 1 ) )
{
for ( int i = 0 ; i < position ; ++i )
{
tokens.add( lexer.nextToken() );
}
}
return (Token) tokens.get( position - 1 );
}
boolean isNodeTypeName(Token name)
{
String text = name.getTokenText();
if ( "node".equals( text )
||
"comment".equals( text )
||
"text".equals( text )
||
"processing-instruction".equals( text ) )
{
return true;
}
return false;
}
XPathSyntaxException createSyntaxException(String message)
{
String xpath = this.lexer.getXPath();
int position = LT(1).getTokenBegin();
return new XPathSyntaxException( xpath,
position,
message );
}
void throwInvalidAxis(String invalidAxis) throws org.jaxen.saxpath.SAXPathException
{
String xpath = this.lexer.getXPath();
int position = LT(1).getTokenBegin();
String message = "Expected valid axis name instead of [" + invalidAxis + "]";
throw new XPathSyntaxException( xpath,
position,
message );
}
void throwUnexpected() throws org.jaxen.saxpath.SAXPathException
{
throw createSyntaxException( "Unexpected '" + LT(1).getTokenText() + "'" );
}
}
|
package org.apache.james.smtpserver;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.InterruptedIOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.SequenceInputStream;
import java.net.Socket;
import java.net.SocketException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Random;
import java.util.StringTokenizer;
import javax.mail.MessagingException;
import org.apache.avalon.cornerstone.services.connection.ConnectionHandler;
import org.apache.avalon.excalibur.pool.Poolable;
import org.apache.avalon.framework.activity.Disposable;
import org.apache.avalon.framework.logger.AbstractLogEnabled;
import org.apache.james.Constants;
import org.apache.james.core.MailHeaders;
import org.apache.james.core.MailImpl;
import org.apache.james.util.Base64;
import org.apache.james.util.CharTerminatedInputStream;
import org.apache.james.util.InternetPrintWriter;
import org.apache.james.util.watchdog.BytesReadResetInputStream;
import org.apache.james.util.watchdog.Watchdog;
import org.apache.james.util.watchdog.WatchdogTarget;
import org.apache.mailet.MailAddress;
import org.apache.mailet.RFC2822Headers;
import org.apache.mailet.dates.RFC822DateFormat;
/**
* Provides SMTP functionality by carrying out the server side of the SMTP
* interaction.
*
* @author Serge Knystautas <sergek@lokitech.com>
* @author Federico Barbieri <scoobie@systemy.it>
* @author Jason Borden <jborden@javasense.com>
* @author Matthew Pangaro <mattp@lokitech.com>
* @author Danny Angus <danny@thought.co.uk>
* @author Peter M. Goldstein <farsight@alum.mit.edu>
*
* @version This is $Revision: 1.39 $
*/
public class SMTPHandler
extends AbstractLogEnabled
implements ConnectionHandler, Poolable {
/**
* SMTP Server identification string used in SMTP headers
*/
private final static String SOFTWARE_TYPE = "JAMES SMTP Server "
+ Constants.SOFTWARE_VERSION;
// Keys used to store/lookup data in the internal state hash map
private final static String CURRENT_HELO_MODE = "CURRENT_HELO_MODE"; // HELO or EHLO
private final static String SENDER = "SENDER_ADDRESS"; // Sender's email address
private final static String MESG_FAILED = "MESG_FAILED"; // Message failed flag
private final static String MESG_SIZE = "MESG_SIZE"; // The size of the message
private final static String RCPT_LIST = "RCPT_LIST"; // The message recipients
/**
* The character array that indicates termination of an SMTP connection
*/
private final static char[] SMTPTerminator = { '\r', '\n', '.', '\r', '\n' };
/**
* Static Random instance used to generate SMTP ids
*/
private final static Random random = new Random();
/**
* Static RFC822DateFormat used to generate date headers
*/
private final static RFC822DateFormat rfc822DateFormat = new RFC822DateFormat();
/**
* The text string for the SMTP HELO command.
*/
private final static String COMMAND_HELO = "HELO";
/**
* The text string for the SMTP EHLO command.
*/
private final static String COMMAND_EHLO = "EHLO";
/**
* The text string for the SMTP AUTH command.
*/
private final static String COMMAND_AUTH = "AUTH";
/**
* The text string for the SMTP MAIL command.
*/
private final static String COMMAND_MAIL = "MAIL";
/**
* The text string for the SMTP RCPT command.
*/
private final static String COMMAND_RCPT = "RCPT";
/**
* The text string for the SMTP NOOP command.
*/
private final static String COMMAND_NOOP = "NOOP";
/**
* The text string for the SMTP RSET command.
*/
private final static String COMMAND_RSET = "RSET";
/**
* The text string for the SMTP DATA command.
*/
private final static String COMMAND_DATA = "DATA";
/**
* The text string for the SMTP QUIT command.
*/
private final static String COMMAND_QUIT = "QUIT";
/**
* The text string for the SMTP HELP command.
*/
private final static String COMMAND_HELP = "HELP";
/**
* The text string for the SMTP VRFY command.
*/
private final static String COMMAND_VRFY = "VRFY";
/**
* The text string for the SMTP EXPN command.
*/
private final static String COMMAND_EXPN = "EXPN";
/**
* The text string for the SMTP AUTH type PLAIN.
*/
private final static String AUTH_TYPE_PLAIN = "PLAIN";
/**
* The text string for the SMTP AUTH type LOGIN.
*/
private final static String AUTH_TYPE_LOGIN = "LOGIN";
/**
* The text string for the SMTP MAIL command SIZE option.
*/
private final static String MAIL_OPTION_SIZE = "SIZE";
/**
* The thread executing this handler
*/
private Thread handlerThread;
/**
* The TCP/IP socket over which the SMTP
* dialogue is occurring.
*/
private Socket socket;
/**
* The incoming stream of bytes coming from the socket.
*/
private InputStream in;
/**
* The writer to which outgoing messages are written.
*/
private PrintWriter out;
/**
* The remote host name obtained by lookup on the socket.
*/
private String remoteHost;
/**
* The remote IP address of the socket.
*/
private String remoteIP;
/**
* The user name of the authenticated user associated with this SMTP transaction.
*/
private String authenticatedUser;
/**
* The id associated with this particular SMTP interaction.
*/
private String smtpID;
/**
* The per-service configuration data that applies to all handlers
*/
private SMTPHandlerConfigurationData theConfigData;
/**
* The hash map that holds variables for the SMTP message transfer in progress.
*
* This hash map should only be used to store variable set in a particular
* set of sequential MAIL-RCPT-DATA commands, as described in RFC 2821. Per
* connection values should be stored as member variables in this class.
*/
private HashMap state = new HashMap();
/**
* The watchdog being used by this handler to deal with idle timeouts.
*/
Watchdog theWatchdog;
/**
* The watchdog target that idles out this handler.
*/
WatchdogTarget theWatchdogTarget = new SMTPWatchdogTarget();
/**
* The per-handler response buffer used to marshal responses.
*/
StringBuffer responseBuffer = new StringBuffer(256);
/**
* Set the configuration data for the handler
*
* @param theData the per-service configuration data for this handler
*/
void setConfigurationData(SMTPHandlerConfigurationData theData) {
theConfigData = theData;
}
/**
* Set the Watchdog for use by this handler.
*
* @param theWatchdog the watchdog
*/
void setWatchdog(Watchdog theWatchdog) {
this.theWatchdog = theWatchdog;
}
/**
* Gets the Watchdog Target that should be used by Watchdogs managing
* this connection.
*
* @return the WatchdogTarget
*/
WatchdogTarget getWatchdogTarget() {
return theWatchdogTarget;
}
/**
* Idle out this connection
*/
void idleClose() {
if (getLogger() != null) {
getLogger().error("SMTP Connection has idled out.");
}
try {
if (socket != null) {
socket.close();
}
} catch (Exception e) {
// ignored
}
synchronized (this) {
// Interrupt the thread to recover from internal hangs
if (handlerThread != null) {
handlerThread.interrupt();
}
}
}
/**
* @see org.apache.avalon.cornerstone.services.connection.ConnectionHandler#handleConnection(Socket)
*/
public void handleConnection(Socket connection) throws IOException {
try {
this.socket = connection;
synchronized (this) {
handlerThread = Thread.currentThread();
}
in = new BufferedInputStream(socket.getInputStream(), 1024);
remoteIP = socket.getInetAddress().getHostAddress();
remoteHost = socket.getInetAddress().getHostName();
smtpID = random.nextInt(1024) + "";
resetState();
} catch (Exception e) {
StringBuffer exceptionBuffer =
new StringBuffer(256)
.append("Cannot open connection from ")
.append(remoteHost)
.append(" (")
.append(remoteIP)
.append("): ")
.append(e.getMessage());
String exceptionString = exceptionBuffer.toString();
getLogger().error(exceptionString, e );
throw new RuntimeException(exceptionString);
}
if (getLogger().isInfoEnabled()) {
StringBuffer infoBuffer =
new StringBuffer(128)
.append("Connection from ")
.append(remoteHost)
.append(" (")
.append(remoteIP)
.append(")");
getLogger().info(infoBuffer.toString());
}
try {
out = new InternetPrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()), 1024), false);
// Initially greet the connector
// Format is: Sat, 24 Jan 1998 13:16:09 -0500
responseBuffer.append("220 ")
.append(theConfigData.getHelloName())
.append(" SMTP Server (")
.append(SOFTWARE_TYPE)
.append(") ready ")
.append(rfc822DateFormat.format(new Date()));
String responseString = clearResponseBuffer();
writeLoggedFlushedResponse(responseString);
theWatchdog.start();
while (parseCommand(readCommandLine())) {
theWatchdog.reset();
}
theWatchdog.stop();
getLogger().debug("Closing socket.");
} catch (SocketException se) {
if (getLogger().isDebugEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(64)
.append("Socket to ")
.append(remoteHost)
.append(" (")
.append(remoteIP)
.append(") closed remotely.");
getLogger().debug(errorBuffer.toString(), se );
}
} catch ( InterruptedIOException iioe ) {
if (getLogger().isDebugEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(64)
.append("Socket to ")
.append(remoteHost)
.append(" (")
.append(remoteIP)
.append(") timeout.");
getLogger().debug( errorBuffer.toString(), iioe );
}
} catch ( IOException ioe ) {
if (getLogger().isDebugEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(256)
.append("Exception handling socket to ")
.append(remoteHost)
.append(" (")
.append(remoteIP)
.append(") : ")
.append(ioe.getMessage());
getLogger().debug( errorBuffer.toString(), ioe );
}
} catch (Exception e) {
if (getLogger().isDebugEnabled()) {
getLogger().debug( "Exception opening socket: "
+ e.getMessage(), e );
}
} finally {
resetHandler();
}
}
/**
* Resets the handler data to a basic state.
*/
private void resetHandler() {
resetState();
clearResponseBuffer();
in = null;
out = null;
remoteHost = null;
remoteIP = null;
authenticatedUser = null;
smtpID = null;
if (theWatchdog != null) {
if (theWatchdog instanceof Disposable) {
((Disposable)theWatchdog).dispose();
}
theWatchdog = null;
}
try {
if (socket != null) {
socket.close();
}
} catch (IOException e) {
if (getLogger().isErrorEnabled()) {
getLogger().error("Exception closing socket: "
+ e.getMessage());
}
} finally {
socket = null;
}
synchronized (this) {
handlerThread = null;
}
}
/**
* Clears the response buffer, returning the String of characters in the buffer.
*
* @return the data in the response buffer
*/
private String clearResponseBuffer() {
String responseString = responseBuffer.toString();
responseBuffer.delete(0,responseBuffer.length());
return responseString;
}
/**
* This method logs at a "DEBUG" level the response string that
* was sent to the SMTP client. The method is provided largely
* as syntactic sugar to neaten up the code base. It is declared
* private and final to encourage compiler inlining.
*
* @param responseString the response string sent to the client
*/
private final void logResponseString(String responseString) {
if (getLogger().isDebugEnabled()) {
getLogger().debug("Sent: " + responseString);
}
}
/**
* Write and flush a response string. The response is also logged.
* Should be used for the last line of a multi-line response or
* for a single line response.
*
* @param responseString the response string sent to the client
*/
final void writeLoggedFlushedResponse(String responseString) {
out.println(responseString);
out.flush();
logResponseString(responseString);
}
/**
* Write a response string. The response is also logged.
* Used for multi-line responses.
*
* @param responseString the response string sent to the client
*/
final void writeLoggedResponse(String responseString) {
out.println(responseString);
logResponseString(responseString);
}
/**
* Reads a line of characters off the command line.
*
* @return the trimmed input line
* @throws IOException if an exception is generated reading in the input characters
*/
final String readCommandLine() throws IOException {
//Read through for \r or \n
ByteArrayOutputStream bout = new ByteArrayOutputStream();
byte b = -1;
while (true) {
in.mark(1);
b = (byte) in.read();
if (b == 13) {
//We're done, but we want to see if \n is next
b = (byte) in.read();
if (b != 10) {
in.reset();
}
break;
} else if (b == 10) {
//We're done
break;
} else if (b == -1) {
break;
}
bout.write(b);
}
// An ASCII encoding can be used because all transmissions other
// that those in the DATA command are guaranteed
// to be ASCII
return bout.toString("ASCII").trim();
}
/**
* Sets the user name associated with this SMTP interaction.
*
* @param userID the user name
*/
private void setUser(String userID) {
authenticatedUser = userID;
}
/**
* Returns the user name associated with this SMTP interaction.
*
* @return the user name
*/
private String getUser() {
return authenticatedUser;
}
/**
* Resets message-specific, but not authenticated user, state.
*
*/
private void resetState() {
ArrayList recipients = (ArrayList)state.get(RCPT_LIST);
if (recipients != null) {
recipients.clear();
}
state.clear();
}
/**
* This method parses SMTP commands read off the wire in handleConnection.
* Actual processing of the command (possibly including additional back and
* forth communication with the client) is delegated to one of a number of
* command specific handler methods. The primary purpose of this method is
* to parse the raw command string to determine exactly which handler should
* be called. It returns true if expecting additional commands, false otherwise.
*
* @param rawCommand the raw command string passed in over the socket
*
* @return whether additional commands are expected.
*/
private boolean parseCommand(String rawCommand) throws Exception {
String argument = null;
boolean returnValue = true;
String command = rawCommand;
if (rawCommand == null) {
return false;
}
if ((state.get(MESG_FAILED) == null) && (getLogger().isDebugEnabled())) {
getLogger().debug("Command received: " + command);
}
int spaceIndex = command.indexOf(" ");
if (spaceIndex > 0) {
argument = command.substring(spaceIndex + 1);
command = command.substring(0, spaceIndex);
}
command = command.toUpperCase(Locale.US);
if (command.equals(COMMAND_HELO)) {
doHELO(argument);
} else if (command.equals(COMMAND_EHLO)) {
doEHLO(argument);
} else if (command.equals(COMMAND_AUTH)) {
doAUTH(argument);
} else if (command.equals(COMMAND_MAIL)) {
doMAIL(argument);
} else if (command.equals(COMMAND_RCPT)) {
doRCPT(argument);
} else if (command.equals(COMMAND_NOOP)) {
doNOOP(argument);
} else if (command.equals(COMMAND_RSET)) {
doRSET(argument);
} else if (command.equals(COMMAND_DATA)) {
doDATA(argument);
} else if (command.equals(COMMAND_QUIT)) {
doQUIT(argument);
returnValue = false;
} else if (command.equals(COMMAND_VRFY)) {
doVRFY(argument);
} else if (command.equals(COMMAND_EXPN)) {
doEXPN(argument);
} else if (command.equals(COMMAND_HELP)) {
doHELP(argument);
} else {
if (state.get(MESG_FAILED) == null) {
doUnknownCmd(command, argument);
}
}
return returnValue;
}
/**
* Handler method called upon receipt of a HELO command.
* Responds with a greeting and informs the client whether
* client authentication is required.
*
* @param argument the argument passed in with the command by the SMTP client
*/
private void doHELO(String argument) {
String responseString = null;
if (argument == null) {
responseString = "501 Domain address required: " + COMMAND_HELO;
writeLoggedFlushedResponse(responseString);
} else {
resetState();
state.put(CURRENT_HELO_MODE, COMMAND_HELO);
if (theConfigData.isAuthRequired()) {
//This is necessary because we're going to do a multiline response
responseBuffer.append("250-");
} else {
responseBuffer.append("250 ");
}
responseBuffer.append(theConfigData.getHelloName())
.append(" Hello ")
.append(argument)
.append(" (")
.append(remoteHost)
.append(" [")
.append(remoteIP)
.append("])");
responseString = clearResponseBuffer();
if (theConfigData.isAuthRequired()) {
writeLoggedResponse(responseString);
responseString = "250 AUTH LOGIN PLAIN";
}
}
writeLoggedFlushedResponse(responseString);
}
/**
* Handler method called upon receipt of a EHLO command.
* Responds with a greeting and informs the client whether
* client authentication is required.
*
* @param argument the argument passed in with the command by the SMTP client
*/
private void doEHLO(String argument) {
String responseString = null;
if (argument == null) {
responseString = "501 Domain address required: " + COMMAND_EHLO;
writeLoggedFlushedResponse(responseString);
} else {
resetState();
state.put(CURRENT_HELO_MODE, COMMAND_EHLO);
// Extension defined in RFC 1870
long maxMessageSize = theConfigData.getMaxMessageSize();
if (maxMessageSize > 0) {
responseString = "250-SIZE " + maxMessageSize;
writeLoggedResponse(responseString);
}
if (theConfigData.isAuthRequired()) {
//This is necessary because we're going to do a multiline response
responseBuffer.append("250-");
} else {
responseBuffer.append("250 ");
}
responseBuffer.append(theConfigData.getHelloName())
.append(" Hello ")
.append(argument)
.append(" (")
.append(remoteHost)
.append(" [")
.append(remoteIP)
.append("])");
responseString = clearResponseBuffer();
if (theConfigData.isAuthRequired()) {
writeLoggedResponse(responseString);
responseString = "250 AUTH LOGIN PLAIN";
}
writeLoggedFlushedResponse(responseString);
}
}
/**
* Handler method called upon receipt of a AUTH command.
* Handles client authentication to the SMTP server.
*
* @param argument the argument passed in with the command by the SMTP client
*/
private void doAUTH(String argument)
throws Exception {
String responseString = null;
if (getUser() != null) {
responseString = "503 User has previously authenticated. "
+ " Further authentication is not required!";
writeLoggedFlushedResponse(responseString);
} else if (argument == null) {
responseString = "501 Usage: AUTH (authentication type) <challenge>";
writeLoggedFlushedResponse(responseString);
} else {
String initialResponse = null;
if ((argument != null) && (argument.indexOf(" ") > 0)) {
initialResponse = argument.substring(argument.indexOf(" ") + 1);
argument = argument.substring(0,argument.indexOf(" "));
}
String authType = argument.toUpperCase(Locale.US);
if (authType.equals(AUTH_TYPE_PLAIN)) {
doPlainAuth(initialResponse);
return;
} else if (authType.equals(AUTH_TYPE_LOGIN)) {
doLoginAuth(initialResponse);
return;
} else {
doUnknownAuth(authType, initialResponse);
return;
}
}
}
/**
* Carries out the Plain AUTH SASL exchange.
*
* @param initialResponse the initial response line passed in with the AUTH command
*/
private void doPlainAuth(String initialResponse)
throws IOException {
String userpass = null, user = null, pass = null, responseString = null;
if (initialResponse == null) {
responseString = "334 OK. Continue authentication";
writeLoggedFlushedResponse(responseString);
userpass = readCommandLine();
} else {
userpass = initialResponse.trim();
}
try {
if (userpass != null) {
userpass = Base64.decodeAsString(userpass);
}
if (userpass != null) {
StringTokenizer authTokenizer = new StringTokenizer(userpass, "\0");
user = authTokenizer.nextToken();
pass = authTokenizer.nextToken();
authTokenizer = null;
}
}
catch (Exception e) {
// Ignored - this exception in parsing will be dealt
// with in the if clause below
}
// Authenticate user
if ((user == null) || (pass == null)) {
responseString = "501 Could not decode parameters for AUTH PLAIN";
writeLoggedFlushedResponse(responseString);
} else if (theConfigData.getUsersRepository().test(user, pass)) {
setUser(user);
responseString = "235 Authentication Successful";
writeLoggedFlushedResponse(responseString);
getLogger().info("AUTH method PLAIN succeeded");
} else {
responseString = "535 Authentication Failed";
writeLoggedFlushedResponse(responseString);
getLogger().error("AUTH method PLAIN failed");
}
return;
}
/**
* Carries out the Login AUTH SASL exchange.
*
* @param initialResponse the initial response line passed in with the AUTH command
*/
private void doLoginAuth(String initialResponse)
throws IOException {
String user = null, pass = null, responseString = null;
if (initialResponse == null) {
responseString = "334 VXNlcm5hbWU6"; // base64 encoded "Username:"
writeLoggedFlushedResponse(responseString);
user = readCommandLine();
} else {
user = initialResponse.trim();
}
if (user != null) {
try {
user = Base64.decodeAsString(user);
} catch (Exception e) {
// Ignored - this parse error will be
// addressed in the if clause below
user = null;
}
}
responseString = "334 UGFzc3dvcmQ6"; // base64 encoded "Password:"
writeLoggedFlushedResponse(responseString);
pass = readCommandLine();
if (pass != null) {
try {
pass = Base64.decodeAsString(pass);
} catch (Exception e) {
// Ignored - this parse error will be
// addressed in the if clause below
pass = null;
}
}
// Authenticate user
if ((user == null) || (pass == null)) {
responseString = "501 Could not decode parameters for AUTH LOGIN";
} else if (theConfigData.getUsersRepository().test(user, pass)) {
setUser(user);
responseString = "235 Authentication Successful";
if (getLogger().isDebugEnabled()) {
// TODO: Make this string a more useful debug message
getLogger().debug("AUTH method LOGIN succeeded");
}
} else {
responseString = "535 Authentication Failed";
// TODO: Make this string a more useful error message
getLogger().error("AUTH method LOGIN failed");
}
writeLoggedFlushedResponse(responseString);
return;
}
/**
* Handles the case of an unrecognized auth type.
*
* @param authType the unknown auth type
* @param initialResponse the initial response line passed in with the AUTH command
*/
private void doUnknownAuth(String authType, String initialResponse) {
String responseString = "504 Unrecognized Authentication Type";
writeLoggedFlushedResponse(responseString);
if (getLogger().isErrorEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(128)
.append("AUTH method ")
.append(authType)
.append(" is an unrecognized authentication type");
getLogger().error(errorBuffer.toString());
}
return;
}
/**
* Handler method called upon receipt of a MAIL command.
* Sets up handler to deliver mail as the stated sender.
*
* @param argument the argument passed in with the command by the SMTP client
*/
private void doMAIL(String argument) {
String responseString = null;
String sender = null;
if ((argument != null) && (argument.indexOf(":") > 0)) {
int colonIndex = argument.indexOf(":");
sender = argument.substring(colonIndex + 1);
argument = argument.substring(0, colonIndex);
}
if (state.containsKey(SENDER)) {
responseString = "503 Sender already specified";
writeLoggedFlushedResponse(responseString);
} else if (argument == null || !argument.toUpperCase(Locale.US).equals("FROM")
|| sender == null) {
responseString = "501 Usage: MAIL FROM:<sender>";
writeLoggedFlushedResponse(responseString);
} else {
sender = sender.trim();
int lastChar = sender.lastIndexOf('>');
// Check to see if any options are present and, if so, whether they are correctly formatted
// (separated from the closing angle bracket by a ' ').
if ((lastChar > 0) && (sender.length() > lastChar + 2) && (sender.charAt(lastChar + 1) == ' ')) {
String mailOptionString = sender.substring(lastChar + 2);
// Remove the options from the sender
sender = sender.substring(0, lastChar + 1);
StringTokenizer optionTokenizer = new StringTokenizer(mailOptionString, " ");
while (optionTokenizer.hasMoreElements()) {
String mailOption = optionTokenizer.nextToken();
int equalIndex = mailOptionString.indexOf('=');
String mailOptionName = mailOption;
String mailOptionValue = "";
if (equalIndex > 0) {
mailOptionName = mailOption.substring(0, equalIndex).toUpperCase(Locale.US);
mailOptionValue = mailOption.substring(equalIndex + 1);
}
// Handle the SIZE extension keyword
if (mailOptionName.startsWith(MAIL_OPTION_SIZE)) {
if (!(doMailSize(mailOptionValue))) {
return;
}
} else {
// Unexpected option attached to the Mail command
if (getLogger().isDebugEnabled()) {
StringBuffer debugBuffer =
new StringBuffer(128)
.append("MAIL command had unrecognized/unexpected option ")
.append(mailOptionName)
.append(" with value ")
.append(mailOptionValue);
getLogger().debug(debugBuffer.toString());
}
}
}
}
if (!sender.startsWith("<") || !sender.endsWith(">")) {
responseString = "501 Syntax error in MAIL command";
writeLoggedFlushedResponse(responseString);
if (getLogger().isErrorEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(128)
.append("Error parsing sender address: ")
.append(sender)
.append(": did not start and end with < >");
getLogger().error(errorBuffer.toString());
}
return;
}
MailAddress senderAddress = null;
//Remove < and >
sender = sender.substring(1, sender.length() - 1);
if (sender.length() == 0) {
//This is the <> case. Let senderAddress == null
} else {
if (sender.indexOf("@") < 0) {
sender = sender + "@localhost";
}
try {
senderAddress = new MailAddress(sender);
} catch (Exception pe) {
responseString = "501 Syntax error in sender address";
writeLoggedFlushedResponse(responseString);
if (getLogger().isErrorEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(256)
.append("Error parsing sender address: ")
.append(sender)
.append(": ")
.append(pe.getMessage());
getLogger().error(errorBuffer.toString());
}
return;
}
}
state.put(SENDER, senderAddress);
responseBuffer.append("250 Sender <")
.append(sender)
.append("> OK");
responseString = clearResponseBuffer();
writeLoggedFlushedResponse(responseString);
}
}
/**
* Handles the SIZE MAIL option.
*
* @param mailOptionValue the option string passed in with the SIZE option
* @returns true if further options should be processed, false otherwise
*/
private boolean doMailSize(String mailOptionValue) {
int size = 0;
try {
size = Integer.parseInt(mailOptionValue);
} catch (NumberFormatException pe) {
// This is a malformed option value. We return an error
String responseString = "501 Syntactically incorrect value for SIZE parameter";
writeLoggedFlushedResponse(responseString);
getLogger().error("Rejected syntactically incorrect value for SIZE parameter.");
return false;
}
if (getLogger().isDebugEnabled()) {
StringBuffer debugBuffer =
new StringBuffer(128)
.append("MAIL command option SIZE received with value ")
.append(size)
.append(".");
getLogger().debug(debugBuffer.toString());
}
long maxMessageSize = theConfigData.getMaxMessageSize();
if ((maxMessageSize > 0) && (size > maxMessageSize)) {
// Let the client know that the size limit has been hit.
String responseString = "552 Message size exceeds fixed maximum message size";
writeLoggedFlushedResponse(responseString);
StringBuffer errorBuffer =
new StringBuffer(256)
.append("Rejected message from ")
.append(state.get(SENDER).toString())
.append(" from host ")
.append(remoteHost)
.append(" (")
.append(remoteIP)
.append(") of size ")
.append(size)
.append(" exceeding system maximum message size of ")
.append(maxMessageSize)
.append("based on SIZE option.");
getLogger().error(errorBuffer.toString());
return false;
} else {
// put the message size in the message state so it can be used
// later to restrict messages for user quotas, etc.
state.put(MESG_SIZE, new Integer(size));
}
return true;
}
/**
* Handler method called upon receipt of a RCPT command.
* Reads recipient. Does some connection validation.
*
* @param argument the argument passed in with the command by the SMTP client
*/
private void doRCPT(String argument) {
String responseString = null;
String recipient = null;
if ((argument != null) && (argument.indexOf(":") > 0)) {
int colonIndex = argument.indexOf(":");
recipient = argument.substring(colonIndex + 1);
argument = argument.substring(0, colonIndex);
}
if (!state.containsKey(SENDER)) {
responseString = "503 Need MAIL before RCPT";
writeLoggedFlushedResponse(responseString);
} else if (argument == null || !argument.toUpperCase(Locale.US).equals("TO")
|| recipient == null) {
responseString = "501 Usage: RCPT TO:<recipient>";
writeLoggedFlushedResponse(responseString);
} else {
Collection rcptColl = (Collection) state.get(RCPT_LIST);
if (rcptColl == null) {
rcptColl = new ArrayList();
}
recipient = recipient.trim();
int lastChar = recipient.lastIndexOf('>');
// Check to see if any options are present and, if so, whether they are correctly formatted
// (separated from the closing angle bracket by a ' ').
if ((lastChar > 0) && (recipient.length() > lastChar + 2) && (recipient.charAt(lastChar + 1) == ' ')) {
String rcptOptionString = recipient.substring(lastChar + 2);
// Remove the options from the recipient
recipient = recipient.substring(0, lastChar + 1);
StringTokenizer optionTokenizer = new StringTokenizer(rcptOptionString, " ");
while (optionTokenizer.hasMoreElements()) {
String rcptOption = optionTokenizer.nextToken();
int equalIndex = rcptOptionString.indexOf('=');
String rcptOptionName = rcptOption;
String rcptOptionValue = "";
if (equalIndex > 0) {
rcptOptionName = rcptOption.substring(0, equalIndex).toUpperCase(Locale.US);
rcptOptionValue = rcptOption.substring(equalIndex + 1);
}
// Unexpected option attached to the RCPT command
if (getLogger().isDebugEnabled()) {
StringBuffer debugBuffer =
new StringBuffer(128)
.append("RCPT command had unrecognized/unexpected option ")
.append(rcptOptionName)
.append(" with value ")
.append(rcptOptionValue);
getLogger().debug(debugBuffer.toString());
}
}
optionTokenizer = null;
}
if (!recipient.startsWith("<") || !recipient.endsWith(">")) {
responseString = "501 Syntax error in parameters or arguments";
writeLoggedFlushedResponse(responseString);
if (getLogger().isErrorEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(192)
.append("Error parsing recipient address: ")
.append(recipient)
.append(": did not start and end with < >");
getLogger().error(errorBuffer.toString());
}
return;
}
MailAddress recipientAddress = null;
//Remove < and >
recipient = recipient.substring(1, recipient.length() - 1);
if (recipient.indexOf("@") < 0) {
recipient = recipient + "@localhost";
}
try {
recipientAddress = new MailAddress(recipient);
} catch (Exception pe) {
responseString = "501 Syntax error in recipient address";
writeLoggedFlushedResponse(responseString);
if (getLogger().isErrorEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(192)
.append("Error parsing recipient address: ")
.append(recipient)
.append(": ")
.append(pe.getMessage());
getLogger().error(errorBuffer.toString());
}
return;
}
if (theConfigData.isAuthRequired()) {
// Make sure the mail is being sent locally if not
// authenticated else reject.
if (getUser() == null) {
String toDomain = recipientAddress.getHost();
if (!theConfigData.getMailServer().isLocalServer(toDomain)) {
responseString = "530 Authentication Required";
writeLoggedFlushedResponse(responseString);
getLogger().error("Rejected message - authentication is required for mail request");
return;
}
} else {
// Identity verification checking
if (theConfigData.isVerifyIdentity()) {
String authUser = (getUser()).toLowerCase(Locale.US);
MailAddress senderAddress = (MailAddress) state.get(SENDER);
boolean domainExists = false;
if ((!authUser.equals(senderAddress.getUser())) ||
(!theConfigData.getMailServer().isLocalServer(senderAddress.getHost()))) {
responseString = "503 Incorrect Authentication for Specified Email Address";
writeLoggedFlushedResponse(responseString);
if (getLogger().isErrorEnabled()) {
StringBuffer errorBuffer =
new StringBuffer(128)
.append("User ")
.append(authUser)
.append(" authenticated, however tried sending email as ")
.append(senderAddress);
getLogger().error(errorBuffer.toString());
}
return;
}
}
}
}
rcptColl.add(recipientAddress);
state.put(RCPT_LIST, rcptColl);
responseBuffer.append("250 Recipient <")
.append(recipient)
.append("> OK");
responseString = clearResponseBuffer();
writeLoggedFlushedResponse(responseString);
}
}
/**
* Handler method called upon receipt of a NOOP command.
* Just sends back an OK and logs the command.
*
* @param argument the argument passed in with the command by the SMTP client
*/
private void doNOOP(String argument) {
String responseString = "250 OK";
writeLoggedFlushedResponse(responseString);
}
/**
* Handler method called upon receipt of a RSET command.
* Resets message-specific, but not authenticated user, state.
*
* @param argument the argument passed in with the command by the SMTP client
*/
private void doRSET(String argument) {
String responseString = "";
if ((argument == null) || (argument.length() == 0)) {
responseString = "250 OK";
resetState();
} else {
responseString = "500 Unexpected argument provided with RSET command";
}
writeLoggedFlushedResponse(responseString);
}
/**
* Handler method called upon receipt of a DATA command.
* Reads in message data, creates header, and delivers to
* mail server service for delivery.
*
* @param argument the argument passed in with the command by the SMTP client
*/
private void doDATA(String argument) {
String responseString = null;
if ((argument != null) && (argument.length() > 0)) {
responseString = "500 Unexpected argument provided with DATA command";
writeLoggedFlushedResponse(responseString);
}
if (!state.containsKey(SENDER)) {
responseString = "503 No sender specified";
writeLoggedFlushedResponse(responseString);
} else if (!state.containsKey(RCPT_LIST)) {
responseString = "503 No recipients specified";
writeLoggedFlushedResponse(responseString);
} else {
responseString = "354 Ok Send data ending with <CRLF>.<CRLF>";
writeLoggedFlushedResponse(responseString);
InputStream msgIn = new CharTerminatedInputStream(in, SMTPTerminator);
try {
msgIn = new BytesReadResetInputStream(msgIn,
theWatchdog,
theConfigData.getResetLength());
// if the message size limit has been set, we'll
// wrap msgIn with a SizeLimitedInputStream
long maxMessageSize = theConfigData.getMaxMessageSize();
if (maxMessageSize > 0) {
if (getLogger().isDebugEnabled()) {
StringBuffer logBuffer =
new StringBuffer(128)
.append("Using SizeLimitedInputStream ")
.append(" with max message size: ")
.append(maxMessageSize);
getLogger().debug(logBuffer.toString());
}
msgIn = new SizeLimitedInputStream(msgIn, maxMessageSize);
}
// Removes the dot stuffing
msgIn = new SMTPInputStream(msgIn);
// Parse out the message headers
MailHeaders headers = new MailHeaders(msgIn);
headers = processMailHeaders(headers);
processMail(headers, msgIn);
headers = null;
} catch (MessagingException me) {
// Grab any exception attached to this one.
Exception e = me.getNextException();
// If there was an attached exception, and it's a
// MessageSizeException
if (e != null && e instanceof MessageSizeException) {
// Add an item to the state to suppress
// logging of extra lines of data
// that are sent after the size limit has
// been hit.
state.put(MESG_FAILED, Boolean.TRUE);
// then let the client know that the size
// limit has been hit.
responseString = "552 Error processing message: "
+ e.getMessage();
StringBuffer errorBuffer =
new StringBuffer(256)
.append("Rejected message from ")
.append(state.get(SENDER).toString())
.append(" from host ")
.append(remoteHost)
.append(" (")
.append(remoteIP)
.append(") exceeding system maximum message size of ")
.append(theConfigData.getMaxMessageSize());
getLogger().error(errorBuffer.toString());
} else {
responseString = "451 Error processing message: "
+ me.getMessage();
getLogger().error("Unknown error occurred while processing DATA.", me);
}
writeLoggedFlushedResponse(responseString);
return;
} finally {
if (msgIn != null) {
try {
msgIn.close();
} catch (Exception e) {
// Ignore close exception
}
msgIn = null;
}
}
resetState();
responseString = "250 Message received";
writeLoggedFlushedResponse(responseString);
}
}
private MailHeaders processMailHeaders(MailHeaders headers)
throws MessagingException {
// If headers do not contains minimum REQUIRED headers fields,
// add them
if (!headers.isSet(RFC2822Headers.DATE)) {
headers.setHeader(RFC2822Headers.DATE, rfc822DateFormat.format(new Date()));
}
if (!headers.isSet(RFC2822Headers.FROM) && state.get(SENDER) != null) {
headers.setHeader(RFC2822Headers.FROM, state.get(SENDER).toString());
}
// Determine the Return-Path
String returnPath = headers.getHeader(RFC2822Headers.RETURN_PATH, "\r\n");
headers.removeHeader(RFC2822Headers.RETURN_PATH);
StringBuffer headerLineBuffer = new StringBuffer(512);
if (returnPath == null) {
if (state.get(SENDER) == null) {
returnPath = "<>";
} else {
headerLineBuffer.append("<")
.append(state.get(SENDER))
.append(">");
returnPath = headerLineBuffer.toString();
headerLineBuffer.delete(0, headerLineBuffer.length());
}
}
// We will rebuild the header object to put Return-Path and our
// Received header at the top
Enumeration headerLines = headers.getAllHeaderLines();
MailHeaders newHeaders = new MailHeaders();
// Put the Return-Path first
newHeaders.addHeaderLine(RFC2822Headers.RETURN_PATH + ": " + returnPath);
// Put our Received header next
headerLineBuffer.append(RFC2822Headers.RECEIVED + ": from ")
.append(remoteHost)
.append(" ([")
.append(remoteIP)
.append("])");
newHeaders.addHeaderLine(headerLineBuffer.toString());
headerLineBuffer.delete(0, headerLineBuffer.length());
headerLineBuffer.append(" by ")
.append(theConfigData.getHelloName())
.append(" (")
.append(SOFTWARE_TYPE)
.append(") with SMTP ID ")
.append(smtpID);
if (((Collection) state.get(RCPT_LIST)).size() == 1) {
// Only indicate a recipient if they're the only recipient
// (prevents email address harvesting and large headers in
// bulk email)
newHeaders.addHeaderLine(headerLineBuffer.toString());
headerLineBuffer.delete(0, headerLineBuffer.length());
headerLineBuffer.append(" for <")
.append(((List) state.get(RCPT_LIST)).get(0).toString())
.append(">;");
newHeaders.addHeaderLine(headerLineBuffer.toString());
headerLineBuffer.delete(0, headerLineBuffer.length());
} else {
// Put the ; on the end of the 'by' line
headerLineBuffer.append(";");
newHeaders.addHeaderLine(headerLineBuffer.toString());
headerLineBuffer.delete(0, headerLineBuffer.length());
}
headerLineBuffer = null;
newHeaders.addHeaderLine(" " + rfc822DateFormat.format(new Date()));
// Add all the original message headers back in next
while (headerLines.hasMoreElements()) {
newHeaders.addHeaderLine((String) headerLines.nextElement());
}
return newHeaders;
}
/**
* Processes the mail message coming in off the wire. Reads the
* content and delivers to the spool.
*
* @param headers the headers of the mail being read
* @param msgIn the stream containing the message content
*/
private void processMail(MailHeaders headers, InputStream msgIn)
throws MessagingException {
ByteArrayInputStream headersIn = null;
MailImpl mail = null;
List recipientCollection = null;
try {
headersIn = new ByteArrayInputStream(headers.toByteArray());
recipientCollection = (List) state.get(RCPT_LIST);
mail =
new MailImpl(theConfigData.getMailServer().getId(),
(MailAddress) state.get(SENDER),
recipientCollection,
new SequenceInputStream(headersIn, msgIn));
// Call mail.getSize() to force the message to be
// loaded. Need to do this to enforce the size limit
if (theConfigData.getMaxMessageSize() > 0) {
mail.getMessageSize();
}
mail.setRemoteHost(remoteHost);
mail.setRemoteAddr(remoteIP);
theConfigData.getMailServer().sendMail(mail);
Collection theRecipients = mail.getRecipients();
String recipientString = "";
if (theRecipients != null) {
recipientString = theRecipients.toString();
}
if (getLogger().isDebugEnabled()) {
StringBuffer debugBuffer =
new StringBuffer(256)
.append("Successfully spooled mail )")
.append(mail.getName())
.append(" from ")
.append(mail.getSender())
.append(" for ")
.append(recipientString);
getLogger().debug(debugBuffer.toString());
} else if (getLogger().isInfoEnabled()) {
StringBuffer infoBuffer =
new StringBuffer(256)
.append("Successfully spooled mail from ")
.append(mail.getSender())
.append(" for ")
.append(recipientString);
getLogger().info(infoBuffer.toString());
}
} finally {
if (recipientCollection != null) {
recipientCollection.clear();
}
recipientCollection = null;
if (mail != null) {
mail.dispose();
}
mail = null;
if (headersIn != null) {
try {
headersIn.close();
} catch (IOException ioe) {
// Ignore exception on close.
}
}
headersIn = null;
}
}
/**
* Handler method called upon receipt of a QUIT command.
* This method informs the client that the connection is
* closing.
*
* @param argument the argument passed in with the command by the SMTP client
*/
private void doQUIT(String argument) {
String responseString = "";
if ((argument == null) || (argument.length() == 0)) {
responseBuffer.append("221 ")
.append(theConfigData.getHelloName())
.append(" Service closing transmission channel");
responseString = clearResponseBuffer();
} else {
responseString = "500 Unexpected argument provided with QUIT command";
}
writeLoggedFlushedResponse(responseString);
}
/**
* Handler method called upon receipt of a VRFY command.
* This method informs the client that the command is
* not implemented.
*
* @param argument the argument passed in with the command by the SMTP client
*/
private void doVRFY(String argument) {
String responseString = "502 VRFY is not supported";
writeLoggedFlushedResponse(responseString);
}
/**
* Handler method called upon receipt of a EXPN command.
* This method informs the client that the command is
* not implemented.
*
* @param argument the argument passed in with the command by the SMTP client
*/
private void doEXPN(String argument) {
String responseString = "502 EXPN is not supported";
writeLoggedFlushedResponse(responseString);
}
/**
* Handler method called upon receipt of a HELP command.
* This method informs the client that the command is
* not implemented.
*
* @param argument the argument passed in with the command by the SMTP client
*/
private void doHELP(String argument) {
String responseString = "502 HELP is not supported";
writeLoggedFlushedResponse(responseString);
}
/**
* Handler method called upon receipt of an unrecognized command.
* Returns an error response and logs the command.
*
* @param command the command parsed by the SMTP client
* @param argument the argument passed in with the command by the SMTP client
*/
private void doUnknownCmd(String command, String argument) {
responseBuffer.append("500 ")
.append(theConfigData.getHelloName())
.append(" Syntax error, command unrecognized: ")
.append(command);
String responseString = clearResponseBuffer();
writeLoggedFlushedResponse(responseString);
}
/**
* A private inner class which serves as an adaptor
* between the WatchdogTarget interface and this
* handler class.
*/
private class SMTPWatchdogTarget
implements WatchdogTarget {
/**
* @see org.apache.james.util.watchdog.WatchdogTarget#execute()
*/
public void execute() {
SMTPHandler.this.idleClose();
}
}
}
|
package org.jdesktop.swingx.painter;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.geom.Point2D;
import javax.swing.JComponent;
import org.jdesktop.swingx.util.Resize;
/**
* "Paints" text at the given location.
*
* @author rbair
*/
public class TextPainter extends AbstractPainter {
private Resize resize;
private String text = "";
private Font font;
private Paint paint;
private Point2D location = new Point2D.Double(.0, .0);
/** Creates a new instance of TextPainter */
public TextPainter() {
}
public TextPainter(String text) {
this(text, new Font("Dialog", Font.PLAIN, 12));
}
public TextPainter(String text, Font font) {
this(text, font, Color.BLACK);
}
public TextPainter(String text, Font font, Paint paint) {
this.text = text;
this.font = font;
this.paint = paint;
}
public void setFont(Font f) {
Font old = getFont();
this.font = f;
firePropertyChange("font", old, getFont());
}
public Font getFont() {
return font;
}
public void setText(String text) {
String old = getText();
this.text = text == null ? "" : text;
firePropertyChange("text", old, getText());
}
public String getText() {
return text;
}
public void setPaint(Paint paint) {
Paint old = getPaint();
this.paint = paint;
firePropertyChange("paint", old, getPaint());
}
public Paint getPaint() {
return paint;
}
public void setLocation(Point2D location) {
Point2D old = getLocation();
this.location = location == null ? new Point2D.Double(.0, .0) : location;
firePropertyChange("location", old, getLocation());
}
public Point2D getLocation() {
return location;
}
protected void paintBackground(Graphics2D g, JComponent component) {
Font font = getFont();
if (font != null) {
g.setFont(font);
}
Paint paint = getPaint();
if (paint != null) {
g.setPaint(paint);
}
FontMetrics metrics = g.getFontMetrics(g.getFont());
Point2D location = getLocation();
double x = location.getX() * component.getWidth();
double y = location.getY() * component.getHeight();
y += metrics.getAscent();
String text = getText();
//double stringWidth = SwingUtilities.computeStringWidth(metrics, text);
//x -= stringWidth/2;
g.drawString(text, (float)x, (float)y);
}
}
|
package jmockit.assist;
import static jmockit.assist.ASTUtil.isAnnotationPresent;
import static jmockit.assist.ASTUtil.isMockUpType;
import static org.eclipse.jdt.core.dom.Modifier.isPrivate;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.jdt.core.ICompilationUnit;
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.compiler.BuildContext;
import org.eclipse.jdt.core.compiler.CategorizedProblem;
import org.eclipse.jdt.core.compiler.CompilationParticipant;
import org.eclipse.jdt.core.compiler.IProblem;
import org.eclipse.jdt.core.compiler.ReconcileContext;
import org.eclipse.jdt.core.dom.ASTNode;
import org.eclipse.jdt.core.dom.ASTVisitor;
import org.eclipse.jdt.core.dom.AnonymousClassDeclaration;
import org.eclipse.jdt.core.dom.ClassInstanceCreation;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.core.dom.ExpressionStatement;
import org.eclipse.jdt.core.dom.IMethodBinding;
import org.eclipse.jdt.core.dom.ITypeBinding;
import org.eclipse.jdt.core.dom.MethodDeclaration;
import org.eclipse.jdt.core.dom.MethodInvocation;
import org.eclipse.jdt.internal.compiler.problem.DefaultProblem;
import org.eclipse.jdt.internal.compiler.problem.ProblemSeverities;
import org.eclipse.jdt.internal.corext.dom.Bindings;
@SuppressWarnings("restriction")
/**
* Compilation participant to check mock classes and methods for problems
*/
public final class JMockitCompilationParticipant extends CompilationParticipant
{
public JMockitCompilationParticipant()
{
}
@Override
public void buildStarting(final BuildContext[] files, final boolean isBatch)
{
for (BuildContext f : files)
{
IFile file = f.getFile();
ICompilationUnit cunit = JavaCore.createCompilationUnitFrom(file);
if( cunit != null )
{
CompilationUnit cu = ASTUtil.getAstOrParse(cunit, null);
MockASTVisitor visitor = new MockASTVisitor(cunit);
cu.accept(visitor);
f.recordNewProblems(visitor.getProblems());
}
}
}
@Override
public boolean isActive(final IJavaProject project)
{
IType mockitType = null;
try
{
mockitType = project.findType("mockit.Mockit");
}
catch (JavaModelException e)
{
Activator.log(e);
}
return mockitType != null;
}
@Override
public void reconcile(final ReconcileContext context)
{
try
{
MockASTVisitor visitor = new MockASTVisitor( context.getWorkingCopy() );
context.getAST3().accept(visitor );
CategorizedProblem[] probs = visitor.getProblems();
if( probs.length != 0 )
{
context.putProblems(probs[0].getMarkerType(), probs);
}
}
catch (JavaModelException e)
{
Activator.log(e);
}
}
private static class MockASTVisitor extends ASTVisitor
{
private ICompilationUnit icunit;
private CompilationUnit cu;
private List<CategorizedProblem> probs = new ArrayList<CategorizedProblem>();
public MockASTVisitor(final ICompilationUnit cunitPar)
{
this.icunit = cunitPar;
}
@Override
public boolean visit(final CompilationUnit node)
{
this.cu = node;
return true;
}
@Override
public boolean visit(final AnonymousClassDeclaration node)
{
ITypeBinding binding = node.resolveBinding();
if( ASTUtil.isMockUpType(binding.getSuperclass()) ) // new MockUp< type >
{
ITypeBinding typePar = ASTUtil.getFirstTypeParameter(node);
ASTNode parent = node.getParent();
if( parent instanceof ClassInstanceCreation && typePar.isInterface() ) // creating interface mock
{
ASTNode gparent = parent.getParent();
ClassInstanceCreation creation = (ClassInstanceCreation) parent;
if( gparent instanceof MethodInvocation ) // method invocation follows
{
MethodInvocation inv = (MethodInvocation) gparent;
IMethodBinding meth = inv.resolveMethodBinding();
if( "getMockInstance".equals( meth.getName() ) )
{
if( gparent.getParent() instanceof ExpressionStatement )
{
addMarker(inv.getName(),
"Returned mock instance is not being used.", false);
}
}
else
{
addMarker(creation.getType(),
"Missing call to getMockInstance() on MockUp of interface", false);
}
}
}
}
return true;
}
@Override
public boolean visit(final MethodInvocation node)
{
IMethodBinding meth = node.resolveMethodBinding();
if( meth != null
&& ASTUtil.isMockUpType(meth.getDeclaringClass()) && "getMockInstance".equals(meth.getName()) )
{
ITypeBinding returnType = node.resolveTypeBinding();
if( !returnType.isInterface() )
{
String msg = "getMockInstance() used on mock of class " + returnType.getName()
+ ". Use on interfaces";
addMarker(node.getName(), msg , false);
}
}
return true;
}
@Override
public boolean visit(final MethodDeclaration node)
{
IMethodBinding meth = node.resolveBinding();
ITypeBinding typePar, declaringClass = meth.getDeclaringClass();
boolean isMockClass = ASTUtil.hasMockClass(declaringClass);
boolean isMockUpType = isMockUpType(declaringClass.getSuperclass());
if( isMockUpType || isMockClass )
{
if( isMockUpType )
{
typePar = ASTUtil.getFirstTypeParameter(node.getParent());
}
else
{
typePar = ASTUtil.findRealClassType(declaringClass);
}
boolean hasMockAnn = isAnnotationPresent(meth.getAnnotations(), "mockit.Mock");
IMethodBinding origMethod = null;
if( typePar != null )
{
String name = meth.getName();
if( "$init".equals(name) ) // constructor
{
name = typePar.getName();
}
if( typePar.isInterface() )
{
origMethod = Bindings.findMethodInHierarchy(typePar, name, meth.getParameterTypes());
}
else
{
origMethod = Bindings.findMethodInType(typePar, name, meth.getParameterTypes());
}
}
if( !hasMockAnn && origMethod != null )
{
addMarker(node.getName(), "Mocked method missing @Mock annotation", false);
}
if( hasMockAnn && origMethod == null )
{
addMarker(node.getName(), "Mocked real method not found in type " , true);
}
if( hasMockAnn && origMethod != null && isPrivate(meth.getModifiers()) )
{
addMarker(node.getName(), "Mocked method should not be private", true);
}
}
return true;
}
private void addMarker(final ASTNode node, final String msg, final boolean isError)
{
try
{
int start = node.getStartPosition();
int endChar = start + node.getLength();
int line = cu.getLineNumber(start);
int col = cu.getColumnNumber(start);
int id = IProblem.MethodRelated;
int severity = ProblemSeverities.Warning;
if( isError )
{
severity = ProblemSeverities.Error;
}
CategorizedProblem problem
= new DefaultProblem(icunit.getPath().toOSString().toCharArray(), msg, id,
new String[]{}, severity, start, endChar, line, col);
probs.add(problem);
}
catch (Exception e)
{
Activator.log(e);
}
}
public CategorizedProblem[] getProblems()
{
return probs.toArray(new CategorizedProblem[]{});
}
}
}
|
package com.stratio.specs;
import static org.assertj.core.api.Assertions.assertThat;
import static org.testng.Assert.fail;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.Writer;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Keys;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.internal.Locatable;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.stratio.tests.utils.AerospikeUtil;
import com.stratio.tests.utils.AerospikeUtils;
import com.stratio.tests.utils.CassandraUtil;
import com.stratio.tests.utils.CassandraUtils;
import com.stratio.tests.utils.ElasticSearchUtil;
import com.stratio.tests.utils.ElasticSearchUtils;
import com.stratio.tests.utils.ExceptionList;
import com.stratio.tests.utils.HashUtils;
import com.stratio.tests.utils.MongoDBUtil;
import com.stratio.tests.utils.MongoDBUtils;
import com.stratio.tests.utils.ThreadProperty;
/**
* @author Javier Delgado
* @author Hugo Dominguez
*
*/
public class CommonG {
private static final long DEFAULT_CURRENT_TIME = 1000L;
private static final int DEFAULT_SLEEP_TIME = 1500;
private final Logger logger = LoggerFactory.getLogger(ThreadProperty.get("class"));
private RemoteWebDriver driver = null;
private String browserName = null;
private List<WebElement> previousWebElements = null;
private String parentWindow = "";
/**
* Get the common logger.
*
* @return
*/
public Logger getLogger() {
return this.logger;
}
/**
* Get the exception list.
*
* @return
*/
public List<Exception> getExceptions() {
return ExceptionList.INSTANCE.getExceptions();
}
/**
* Get the cassandra utils.
*
* @return
*/
public CassandraUtils getCassandraClient() {
return CassandraUtil.INSTANCE.getCassandraUtils();
}
/**
* Get the elasticSearch utils.
*
* @return
*/
public ElasticSearchUtils getElasticSearchClient() {
return ElasticSearchUtil.INSTANCE.getElasticSearchUtils();
}
/**
* Get the Aerospike utils.
*
* @return
*/
public AerospikeUtils getAerospikeClient() {
return AerospikeUtil.INSTANCE.getAeroSpikeUtils();
}
/**
* Get the MongoDB utils.
*
* @return
*/
public MongoDBUtils getMongoDBClient() {
return MongoDBUtil.INSTANCE.getMongoDBUtils();
}
/**
* Get the remoteWebDriver.
*
* @return
*/
public RemoteWebDriver getDriver() {
return driver;
}
/**
* Set the remoteDriver.
*
* @param driver
*/
public void setDriver(RemoteWebDriver driver) {
this.driver = driver;
}
/**
* Get the browser name.
*
* @return
*/
public String getBrowserName() {
return browserName;
}
/**
* Set the browser name.
*
* @param browserName
*/
public void setBrowserName(String browserName) {
this.browserName = browserName;
}
/**
* Looks for webelements inside a selenium context. This search will be made by id, name and xpath expression
* matching an {@code locator} value
*
* @param element
* @throws Exception
*/
public List<WebElement> locateElement(String method, String element, Integer expectedCount) {
List<WebElement> wel = null;
String newElement = replacePlaceholders(element);
if ("id".equals(method)) {
logger.info("Locating {} by id", newElement);
wel = this.getDriver().findElements(By.id(newElement));
} else if ("name".equals(method)) {
logger.info("Locating {} by name", newElement);
wel = this.getDriver().findElements(By.name(newElement));
} else if ("class".equals(method)) {
logger.info("Locating {} by class", newElement);
wel = this.getDriver().findElements(By.className(newElement));
} else if ("xpath".equals(method)) {
logger.info("Locating {} by xpath", newElement);
wel = this.getDriver().findElements(By.xpath(newElement));
} else if ("css".equals(method)) {
wel = this.getDriver().findElements(By.cssSelector(newElement));
} else {
fail("Unknown search method: " + method);
}
if (expectedCount != -1) {
assertThat(wel.size()).as("Element count doesnt match").isEqualTo(expectedCount);
}
return wel;
}
/**
* Replaces every placeholded element, enclosed in ${} with the corresponding java property
*
* @param element
*/
public String replacePlaceholders(String element) {
String newVal = element;
while (newVal.contains("${")) {
String placeholder = newVal.substring(newVal.indexOf("${"), newVal.indexOf("}") + 1);
String modifier = "";
String sysProp = "";
if (placeholder.contains(".")) {
sysProp = placeholder.substring(2, placeholder.indexOf("."));
modifier = placeholder.substring(placeholder.indexOf(".") + 1, placeholder.length() - 1);
} else {
sysProp = placeholder.substring(2, placeholder.length() - 1);
}
String prop = "";
if ("toLower".equals(modifier)) {
prop = System.getProperty(sysProp, "").toLowerCase();
} else if ("toUpper".equals(modifier)) {
prop = System.getProperty(sysProp, "").toUpperCase();
} else {
prop = System.getProperty(sysProp, "");
}
newVal = newVal.replace(placeholder, prop);
}
return newVal;
}
public String captureEvidence(WebDriver driver, String type) {
String dir = "./target/executions/";
String clazz = ThreadProperty.get("class");
String currentBrowser = ThreadProperty.get("browser");
String currentData = ThreadProperty.get("dataSet");
if (!currentData.equals("")) {
currentData = currentData.replaceAll("[\\\\|\\/|\\|\\s|:|\\*]", "_");
}
currentData = HashUtils.doHash(currentData);
String outputFile = dir + clazz + "/" + currentBrowser + "-" + currentData
+ new Timestamp(new java.util.Date().getTime());
outputFile = outputFile.replaceAll(" ", "_");
if (type.endsWith("htmlSource")) {
if (type.equals("framehtmlSource")) {
boolean isFrame = (Boolean) ((JavascriptExecutor) driver)
.executeScript("return window.top != window.self");
if (isFrame) {
outputFile = outputFile + "frame.html";
} else {
outputFile = "";
}
} else if (type.equals("htmlSource")) {
driver.switchTo().defaultContent();
outputFile = outputFile + ".html";
}
if (!outputFile.equals("")) {
String source = ((RemoteWebDriver) driver).getPageSource();
File fout = new File(outputFile);
boolean dirs = fout.getParentFile().mkdirs();
FileOutputStream fos;
try {
fos = new FileOutputStream(fout, true);
Writer out = new OutputStreamWriter(fos, "UTF8");
PrintWriter writer = new PrintWriter(out, false);
writer.append(source);
writer.close();
out.close();
} catch (IOException e) {
logger.error("Exception on evidence capture", e);
}
}
} else if (type.equals("screenCapture")) {
outputFile = outputFile + ".png";
File file = null;
driver.switchTo().defaultContent();
((Locatable) driver.findElement(By.tagName("body"))).getCoordinates().inViewPort();
if (currentBrowser.startsWith("chrome") || currentBrowser.startsWith("droidemu")) {
Actions actions = new Actions(driver);
actions.keyDown(Keys.CONTROL).sendKeys(Keys.HOME).perform();
actions.keyUp(Keys.CONTROL).perform();
file = chromeFullScreenCapture(driver);
} else {
file = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
}
try {
FileUtils.copyFile(file, new File(outputFile));
} catch (IOException e) {
logger.error("Exception on copying browser screen capture", e);
}
}
return outputFile;
}
private File adjustLastCapture(Integer newTrailingImageHeight, List<File> capture) {
// cuts last image just in case it dupes information
Integer finalHeight = 0;
Integer finalWidth = 0;
File trailingImage = capture.get(capture.size() - 1);
capture.remove(capture.size() - 1);
BufferedImage oldTrailingImage;
File temp = null;
try {
oldTrailingImage = ImageIO.read(trailingImage);
BufferedImage newTrailingImage = new BufferedImage(oldTrailingImage.getWidth(),
oldTrailingImage.getHeight() - newTrailingImageHeight, BufferedImage.TYPE_INT_RGB);
newTrailingImage.createGraphics().drawImage(oldTrailingImage, 0, 0 - newTrailingImageHeight, null);
File newTrailingImageF = File.createTempFile("tmpnewTrailingImage", ".png");
newTrailingImageF.deleteOnExit();
ImageIO.write(newTrailingImage, "png", newTrailingImageF);
capture.add(newTrailingImageF);
finalWidth = ImageIO.read(capture.get(0)).getWidth();
for (File cap : capture) {
finalHeight += ImageIO.read(cap).getHeight();
}
BufferedImage img = new BufferedImage(finalWidth, finalHeight, BufferedImage.TYPE_INT_RGB);
Integer y = 0;
BufferedImage tmpImg = null;
for (File cap : capture) {
tmpImg = ImageIO.read(cap);
img.createGraphics().drawImage(tmpImg, 0, y, null);
y += tmpImg.getHeight();
}
long ts = System.currentTimeMillis() / DEFAULT_CURRENT_TIME;
temp = File.createTempFile("chromecap" + Long.toString(ts), ".png");
temp.deleteOnExit();
ImageIO.write(img, "png", temp);
} catch (IOException e) {
logger.error("Cant read image", e);
}
return temp;
}
private File chromeFullScreenCapture(WebDriver driver) {
driver.switchTo().defaultContent();
// scroll loop n times to get the whole page if browser is chrome
ArrayList<File> capture = new ArrayList<File>();
Boolean atBottom = false;
Integer windowSize = ((Long) ((JavascriptExecutor) driver)
.executeScript("return document.documentElement.clientHeight")).intValue();
Integer accuScroll = 0;
Integer newTrailingImageHeight = 0;
try {
while (!atBottom) {
Thread.sleep(DEFAULT_SLEEP_TIME);
capture.add(((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE));
((JavascriptExecutor) driver).executeScript("if(window.screen)" + " {window.scrollBy(0," + windowSize
+ ");};");
accuScroll += windowSize;
if (getDocumentHeight(driver) <= accuScroll) {
atBottom = true;
}
}
} catch (InterruptedException e) {
logger.error("Interrupted waits among scrolls", e);
}
newTrailingImageHeight = accuScroll - getDocumentHeight(driver);
return adjustLastCapture(newTrailingImageHeight, capture);
}
private Integer getDocumentHeight(WebDriver driver) {
WebElement body = driver.findElement(By.tagName("html"));
return body.getSize().getHeight();
}
public List<WebElement> getPreviousWebElements() {
return previousWebElements;
}
public void setPreviousWebElements(List<WebElement> previousWebElements) {
this.previousWebElements = previousWebElements;
}
public String getParentWindow() {
return this.parentWindow;
}
public void setParentWindow(String windowHandle) {
this.parentWindow = windowHandle;
}
}
|
package com.triggertrap.seekarc;
import android.content.Context;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
/**
*
* SeekArc.java
*
* This is a class that functions much like a SeekBar but
* follows a circle path instead of a straight line.
*
* @author Neil Davies
*
*/
public class SeekArc extends View {
private static final String TAG = SeekArc.class.getSimpleName();
private static int INVALID_PROGRESS_VALUE = -1;
private static double INVALID_ANGLE_VALUE = 999.00;
// The initial rotational offset -90 means we start at 12 o'clock
private final int mAngleOffset = -90;
/**
* The Drawable for the seek arc thumbnail
*/
private Drawable mThumb;
/**
* The Maximum value that this SeekArc can be set to
*/
private int mMax = 100;
/**
* The Current value that the SeekArc is set to
*/
private int mProgress = 0;
/**
* The width of the progress line for this SeekArc
*/
private int mProgressWidth = 4;
/**
* The Width of the background arc for the SeekArc
*/
private int mArcWidth = 2;
/**
* The dimension of allowance that the arc will accept inputs outside of the arc drawing
*/
private int mBoundsInner = 0;
private int mBoundsOuter = 0;
/**
* The Angle to start drawing this Arc from
*/
private int mStartAngle = 0;
/**
* The Angle through which to draw the arc (Max is 360)
*/
private int mSweepAngle = 360;
private int mSweepNormal = mSweepAngle; // use value here when reverting to non-continuous mode
/**
* The rotation of the SeekArc- 0 is twelve o'clock
*/
private int mRotation = 0;
/**
* Give the SeekArc rounded edges
*/
private boolean mRoundedEdges = false;
/**
* Will the progress increase clockwise or anti-clockwise
*/
private boolean mClockwise = true;
/**
* is the control enabled/touchable
*/
private boolean mEnabled = true;
// Internal variables
private boolean mContinuous = false;
private boolean mAccepts = false;
private boolean mDragging = false;
private int mThumbOffset = 0;
private int mArcRadius = 0;
private int mBoundsInnerRadius;
private int mBoundsOuterRadius;
private int mTranslateX;
private int mTranslateY;
private int mThumbXPos;
private int mThumbYPos;
private double mTouchAngleStart;
private double mTouchAnglePrev;
private double mTouchAngle = INVALID_ANGLE_VALUE;
private float mProgressSweep = 0;
private float mProposedSweep = 0;
private RectF mArcRect = new RectF();
private Paint mArcPaint;
private Paint mProgressPaint;
private Paint mProposedPaint;
private OnSeekArcChangeListener mOnSeekArcChangeListener;
private Path.Direction mDirection;
public interface OnSeekArcChangeListener {
/**
* Notification that the progress level has changed. Clients can use the
* fromUser parameter to distinguish user-initiated changes from those
* that occurred programmatically.
*
* @param seekArc
* The SeekArc whose progress has changed
* @param progress
* The current progress level. This will be in the range
* 0..max where max was set by
* {@link SeekArc#setMax(int)}. (The default value for
* max is 100.)
* @param fromUser
* True if the progress change was initiated by the user.
*/
void onProgressChanged(SeekArc seekArc, int progress, boolean fromUser);
/**
* Notification that the user has started a touch gesture. Clients may
* want to use this to disable advancing the seekbar.
*
* @param seekArc
* The SeekArc in which the touch gesture began
*/
void onStartTrackingTouch(SeekArc seekArc);
/**
* Notification that the user has finished a touch gesture. Clients may
* want to use this to re-enable advancing the seekarc.
*
* @param seekArc
* The SeekArc in which the touch gesture began
*/
void onStopTrackingTouch(SeekArc seekArc);
}
public SeekArc(Context context) {
super(context);
init(context, null, 0);
}
public SeekArc(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs, R.attr.seekArcStyle);
}
public SeekArc(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
Log.d(TAG, "Initialising SeekArc");
final Resources res = getResources();
float density = context.getResources().getDisplayMetrics().density;
// Defaults, may need to link this into theme settings
int arcColor = res.getColor(R.color.progress_gray);
int progressColor = res.getColor(R.color.default_blue_light);
int proposedColor = res.getColor(R.color.proposed_red);
int thumbHalfheight;
int thumbHalfWidth;
boolean continuous = false;
mThumb = res.getDrawable(R.drawable.seek_arc_control_selector);
// Convert progress width to pixels for current density
mProgressWidth = (int) (mProgressWidth * density);
mBoundsInner = 0;
mBoundsOuter = 0;
if (attrs != null) {
// Attribute initialization
final TypedArray a = context.obtainStyledAttributes(
attrs,
R.styleable.SeekArc,
defStyle,
0
);
Drawable thumb = a.getDrawable(R.styleable.SeekArc_thumb);
if (thumb != null) {
mThumb = thumb;
}
thumbHalfheight = mThumb.getIntrinsicHeight() / 2;
thumbHalfWidth = mThumb.getIntrinsicWidth() / 2;
mThumb.setBounds(-thumbHalfWidth, -thumbHalfheight, thumbHalfWidth, thumbHalfheight);
mThumbOffset = (int) a.getDimension(R.styleable.SeekArc_thumbOffset, mThumbOffset);
mMax = a.getInteger(R.styleable.SeekArc_max, mMax);
mProgress = a.getInteger(R.styleable.SeekArc_progress, mProgress);
mRotation = a.getInt(R.styleable.SeekArc_rotation, mRotation);
mStartAngle = a.getInt(R.styleable.SeekArc_startAngle, mStartAngle);
mSweepAngle = a.getInt(R.styleable.SeekArc_sweepAngle, mSweepAngle);
mProgressWidth = (int) a.getDimension(R.styleable.SeekArc_progressWidth, mProgressWidth);
mArcWidth = (int) a.getDimension(R.styleable.SeekArc_arcWidth, mArcWidth);
mBoundsInner = (int) a.getDimension(R.styleable.SeekArc_boundsInner, mBoundsInner);
mBoundsOuter = (int) a.getDimension(R.styleable.SeekArc_boundsOuter, mBoundsOuter);
mRoundedEdges = a.getBoolean(R.styleable.SeekArc_roundEdges, mRoundedEdges);
mClockwise = a.getBoolean(R.styleable.SeekArc_clockwise, mClockwise);
mEnabled = a.getBoolean(R.styleable.SeekArc_enabled, mEnabled);
continuous = a.getBoolean(R.styleable.SeekArc_continuous, continuous);
arcColor = a.getColor(R.styleable.SeekArc_arcColor, arcColor);
progressColor = a.getColor(R.styleable.SeekArc_progressColor, progressColor);
proposedColor = a.getColor(R.styleable.SeekArc_proposedColor, proposedColor);
a.recycle();
}
mProgress = (mProgress > mMax) ? mMax : mProgress;
mProgress = (mProgress < 0) ? 0 : mProgress;
mSweepAngle = (mSweepAngle > 360) ? 360 : mSweepAngle;
mSweepAngle = (mSweepAngle < 0) ? 0 : mSweepAngle;
mSweepNormal = mSweepAngle;
mProgressSweep = (float) mProgress / mMax * mSweepAngle;
mStartAngle = (mStartAngle > 360) ? 0 : mStartAngle;
mStartAngle = (mStartAngle < 0) ? 0 : mStartAngle;
// Dotted lines effect ish
// PathEffect effect = new DashPathEffect(new float[]{50, 50}, 0);
mArcPaint = new Paint();
mArcPaint.setColor(arcColor);
mArcPaint.setAntiAlias(true);
mArcPaint.setStyle(Paint.Style.STROKE);
mArcPaint.setStrokeWidth(mArcWidth);
//mArcPaint.setPathEffect(effect);
//mArcPaint.setAlpha(45);
mProgressPaint = new Paint();
mProgressPaint.setColor(progressColor);
mProgressPaint.setAntiAlias(true);
mProgressPaint.setStyle(Paint.Style.STROKE);
mProgressPaint.setStrokeWidth(mProgressWidth);
//mProgressPaint.setPathEffect(effect);
mProposedPaint = new Paint();
mProposedPaint.setColor(proposedColor);
mProposedPaint.setAntiAlias(true);
mProposedPaint.setStyle(Paint.Style.STROKE);
mProposedPaint.setStrokeWidth(mProgressWidth);
//mProposedPaint.setPathEffect(effect);
setContinuous(continuous);
if (mRoundedEdges) {
mArcPaint.setStrokeCap(Paint.Cap.ROUND);
mProgressPaint.setStrokeCap(Paint.Cap.ROUND);
mProposedPaint.setStrokeCap(Paint.Cap.ROUND);
}
}
@Override
protected void onDraw(Canvas canvas) {
if(!mClockwise) {
canvas.scale(-1, 1, mArcRect.centerX(), mArcRect.centerY() );
}
// Draw the arcs
final int arcStart = mStartAngle + mAngleOffset + mRotation;
final int arcSweep = mSweepAngle;
canvas.drawArc(mArcRect, arcStart, arcSweep, false, mArcPaint);
if (!mContinuous && mProgressSweep > 0)
canvas.drawArc(mArcRect, arcStart, mProgressSweep, false, mProgressPaint);
float proposedStart;
float proposedSweep;
if (mContinuous) {
proposedStart = (float)(mTouchAngleStart + mAngleOffset);
proposedSweep = mProposedSweep;
}
else {
// start: at the current progress degree
// sweep: only the different between the proposed and current progress.
proposedStart = arcStart + mProgressSweep;
proposedSweep = mProposedSweep - mProgressSweep;
}
if (mDragging && proposedSweep != 0)
canvas.drawArc(mArcRect, proposedStart, proposedSweep, false, mProposedPaint);
if (mEnabled) {
// Draw the thumb nail
canvas.translate(mTranslateX - mThumbXPos, mTranslateY - mThumbYPos);
mThumb.draw(canvas);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int width = getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec);
final int height = getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec);
final int min = Math.min(width, height);
float top;
float left;
float arcRadius;
float arcSweep;
int arcWidth;
int arcStart;
int arcDiameter;
arcWidth = Math.max(mArcWidth, mProgressWidth);
arcDiameter = min - getPaddingLeft() - arcWidth;
arcRadius = arcDiameter / 2;
top = height / 2 - arcRadius;
left = width / 2 - arcRadius;
mTranslateX = (int) (width * 0.5f);
mTranslateY = (int) (height * 0.5f);
mArcRadius = (int)arcRadius - mThumbOffset;
measureBounds();
mArcRect.set(left, top, left + arcDiameter, top + arcDiameter);
arcSweep = mDragging ? mProposedSweep : mProgressSweep;
arcStart = (int)arcSweep + mStartAngle + mRotation + -mAngleOffset;
mThumbXPos = (int) (mArcRadius * Math.cos(Math.toRadians(arcStart)));
mThumbYPos = (int) (mArcRadius * Math.sin(Math.toRadians(arcStart)));
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mEnabled) {
this.getParent().requestDisallowInterceptTouchEvent(true);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
onStartTrackingTouch();
updateOnTouch(event);
break;
case MotionEvent.ACTION_MOVE:
updateOnTouch(event);
break;
case MotionEvent.ACTION_UP:
onStopTrackingTouch();
setPressed(false);
this.getParent().requestDisallowInterceptTouchEvent(false);
break;
case MotionEvent.ACTION_CANCEL:
onStopTrackingTouch();
setPressed(false);
this.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
return true;
}
return false;
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
if (mThumb != null && mThumb.isStateful()) {
int[] state = getDrawableState();
mThumb.setState(state);
}
invalidate();
}
private void measureBounds() {
int boundsThickness;
boundsThickness = Math.max(mArcWidth, mProgressWidth);
boundsThickness /= 2;
mBoundsOuterRadius = mArcRadius + mBoundsOuter + boundsThickness;
mBoundsInnerRadius = mArcRadius - mBoundsInner - boundsThickness;
}
private void onStartTrackingTouch() {
if (mOnSeekArcChangeListener != null) {
mOnSeekArcChangeListener.onStartTrackingTouch(this);
}
}
private void onStopTrackingTouch() {
if (mOnSeekArcChangeListener != null) {
mOnSeekArcChangeListener.onStopTrackingTouch(this);
}
}
private void updateOnTouch(MotionEvent event) {
float x = event.getX();
float y = event.getY();
int action = event.getAction();
if (action == MotionEvent.ACTION_DOWN)
mAccepts = !ignoreTouch(x, y);
if (!mAccepts)
return;
if (action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_MOVE) {
setPressed(true);
mDragging = true;
}
else {
setPressed(false);
mDragging = false;
}
mTouchAnglePrev = mTouchAngle;
mTouchAngle = getTouchDegrees(x, y);
if (action == MotionEvent.ACTION_DOWN)
mTouchAngleStart = mTouchAngle;
mDirection = getTouchDirection();
onProgressRefresh(getProgressForAngle(mTouchAngle), true);
}
private boolean ignoreTouch(float xPos, float yPos) {
float x = xPos - mTranslateX;
float y = yPos - mTranslateY;
float touchRadius = (float) Math.sqrt(((x * x) + (y * y)));
return touchRadius < mBoundsInnerRadius || touchRadius > mBoundsOuterRadius;
}
private double getTouchDegrees(float xPos, float yPos) {
float x = xPos - mTranslateX;
float y = yPos - mTranslateY;
//invert the x-coord if we are rotating anti-clockwise
x = (mClockwise) ? x : -x;
// convert to arc Angle
double angle;
angle = Math.toDegrees(Math.atan2(y, x) + (Math.PI / 2) - Math.toRadians(mRotation));
angle -= mStartAngle;
angle += angle < 0 ? 360 : 0;
return angle;
}
private Path.Direction getTouchDirection() {
double startLower = (mTouchAngleStart - 1) % 360,
startUpper = (mTouchAngleStart + 1) % 360;
if (mDirection != null)
if (startLower < mTouchAngle && mTouchAngle < startUpper)
return null;
else
return mDirection;
// if ((int)mTouchAngle == (int)mTouchAngleStart)
// return null;
// if (mDirection != null)
// return mDirection;
else if (mTouchAngle < mTouchAngleStart || mTouchAngle == 360 && mTouchAngleStart == 0)
return Path.Direction.CCW;
else if (mTouchAngle > mTouchAngleStart|| mTouchAngleStart == 0 && mTouchAngle == 360)
return Path.Direction.CW;
return mDirection;
}
private int getProgressForAngle(double angle) {
int touchProgress = (int) Math.round(valuePerDegree() * angle);
touchProgress = (touchProgress < 0) ? INVALID_PROGRESS_VALUE : touchProgress;
touchProgress = (touchProgress > mMax) ? INVALID_PROGRESS_VALUE : touchProgress;
return touchProgress;
}
private float valuePerDegree() {
return (float) mMax / mSweepAngle;
}
private void onProgressRefresh(int progress, boolean fromUser) {
if (mDragging)
updateDelta(progress, fromUser);
else
updateProgress(mProgress, fromUser);
}
private void updateThumbPosition() {
float sweep;
int angle;
if (mContinuous)
sweep = mProgressSweep;
else
sweep = mDragging ? mProposedSweep : mProgressSweep;
angle = (int) (mStartAngle + sweep + mRotation - mAngleOffset);
mThumbXPos = (int) (mArcRadius * Math.cos(Math.toRadians(angle)));
mThumbYPos = (int) (mArcRadius * Math.sin(Math.toRadians(angle)));
}
private void updateProgress(int progress, boolean fromUser) {
if (progress == INVALID_PROGRESS_VALUE)
return;
if (mOnSeekArcChangeListener != null)
mOnSeekArcChangeListener.onProgressChanged(this, progress, fromUser);
mProgressSweep = (float) progress / mMax * mSweepAngle;
updateThumbPosition();
invalidate();
}
private void updateDelta(int progress, boolean fromUser) {
if (progress == INVALID_PROGRESS_VALUE)
return;
progress = progress > mMax ? mMax : progress;
progress = progress < 0 ? 0 : progress;
mProgress = progress;
if (mOnSeekArcChangeListener != null)
mOnSeekArcChangeListener.onProgressChanged(this, progress, fromUser);
if (mContinuous) {
if (mDirection == Path.Direction.CW) {
mProposedSweep = (float) (mTouchAngle - mTouchAngleStart);
mProposedSweep = mProposedSweep >= 0
? mProposedSweep
: (float) (360 - mTouchAngleStart + mTouchAngle);
}
else if (mDirection == Path.Direction.CCW) {
mProposedSweep = (float) (mTouchAngle - mTouchAngleStart);
mProposedSweep = mProposedSweep <= 0
? mProposedSweep
: (float) (mTouchAngle - 360 - mTouchAngleStart);
}
else
mProposedSweep = 0;
mProgressSweep = (float)progress / mMax * mSweepAngle;
}
else
mProposedSweep = (float)progress / mMax * mSweepAngle;
updateThumbPosition();
invalidate();
}
/**
* Sets a listener to receive notifications of changes to the SeekArc's
* progress level. Also provides notifications of when the user starts and
* stops a touch gesture within the SeekArc.
*
* @param l
* The seek bar notification listener
*
* @see SeekArc.OnSeekArcChangeListener
*/
public void setOnSeekArcChangeListener(OnSeekArcChangeListener l) {
mOnSeekArcChangeListener = l;
}
public void setProgress(int progress) {
updateProgress(progress, false);
}
public void setDelta(int progress) {
mDragging = true;
updateDelta(progress, false);
onStopTrackingTouch();
}
public void commit() {
updateProgress(mProgress, false);
}
public void rollback() {
}
public int getProgress() {
return mProgress;
}
public int getProgressWidth() {
return mProgressWidth;
}
public void setProgressWidth(int mProgressWidth) {
this.mProgressWidth = mProgressWidth;
mProgressPaint.setStrokeWidth(mProgressWidth);
}
public int getArcWidth() {
return mArcWidth;
}
public void setArcWidth(int mArcWidth) {
this.mArcWidth = mArcWidth;
mArcPaint.setStrokeWidth(mArcWidth);
}
public int getInnerBounds() {
return mBoundsInner;
}
public void setInnerBounds(int bounds) {
mBoundsInner = bounds;
measureBounds();
}
public int getOuterBounds() {
return mBoundsOuter;
}
public void setOuterBounds(int bounds) {
mBoundsOuter = bounds;
measureBounds();
}
public int getArcRotation() {
return mRotation;
}
public void setArcRotation(int mRotation) {
this.mRotation = mRotation;
updateThumbPosition();
}
public int getStartAngle() {
return mStartAngle;
}
public void setStartAngle(int mStartAngle) {
this.mStartAngle = mStartAngle;
updateThumbPosition();
}
public int getSweepAngle() {
return mSweepAngle;
}
public void setSweepAngle(int mSweepAngle) {
this.mSweepAngle = mSweepAngle;
updateThumbPosition();
}
public boolean isRoundedEdges() {
return mRoundedEdges;
}
public void setRoundedEdges(boolean isEnabled) {
mRoundedEdges = isEnabled;
if (mRoundedEdges) {
mArcPaint.setStrokeCap(Paint.Cap.ROUND);
mProgressPaint.setStrokeCap(Paint.Cap.ROUND);
mProposedPaint.setStrokeCap(Paint.Cap.ROUND);
} else {
mArcPaint.setStrokeCap(Paint.Cap.SQUARE);
mProgressPaint.setStrokeCap(Paint.Cap.SQUARE);
mProposedPaint.setStrokeCap(Paint.Cap.SQUARE);
}
}
public boolean isClockwise() {
return mClockwise;
}
public void setClockwise(boolean isClockwise) {
mClockwise = isClockwise;
}
public boolean isEnabled() {
return mEnabled;
}
public void setEnabled(boolean enabled) {
this.mEnabled = enabled;
}
public void setContinuous(boolean continuous) {
mContinuous = continuous;
if (continuous) {
mSweepNormal = mSweepAngle;
mSweepAngle = 360;
}
else {
mSweepAngle = mSweepNormal;
}
}
public int getProgressColor() {
return mProgressPaint.getColor();
}
public void setProgressColor(int color) {
mProgressPaint.setColor(color);
invalidate();
}
public int getArcColor() {
return mArcPaint.getColor();
}
public void setArcColor(int color) {
mArcPaint.setColor(color);
invalidate();
}
public int getMax() {
return mMax;
}
public void setMax(int mMax) {
this.mMax = mMax;
}
}
|
package trikita.kv;
import java.lang.InterruptedException;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ExecutorService;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
public class LruStorage extends LinkedHashMap<String, byte[]>
implements KV.Storage {
private final ExecutorService mService = Executors.newSingleThreadExecutor();
private final KV.Storage mStorage;
private final int mMaxSize;
public LruStorage(KV.Storage storage, int size) {
super(size/2, 0.75f, true);
mStorage = storage;
mMaxSize = size;
}
public void set(final String key, final byte[] value) {
if (value == null) {
this.remove(key);
} else {
this.put(key, value);
}
mService.submit(new Callable<Void>() {
public Void call() {
mStorage.set(key, value);
return null;
}
});
}
public byte[] get(final String key) {
byte[] value = super.get(key);
if (value == null) {
value = wait(new Callable<byte[]>() {
public byte[] call() {
byte[] b = mStorage.get(key);
put(key, b);
return b;
}
});
}
return value;
}
public Set<String> keys(final String mask) {
return wait(new Callable<Set<String>>() {
public Set<String> call() {
return mStorage.keys(mask);
}
});
}
public void close() {
wait(new Callable<Void>() {
public Void call() {
mStorage.close();
return null;
}
});
mService.shutdown();
}
protected boolean removeEldestEntry(Map.Entry<String, byte[]> eldest) {
return size() > mMaxSize;
}
private <T> T wait(Callable<T> c) {
try {
return mService.submit(c).get();
} catch (InterruptedException|ExecutionException e) {
throw new RuntimeException(e);
}
}
}
|
package cgeo.geocaching;
import cgeo.geocaching.activity.Progress;
import cgeo.geocaching.apps.navi.NavigationAppFactory;
import cgeo.geocaching.compatibility.Compatibility;
import cgeo.geocaching.list.StoredList;
import cgeo.geocaching.models.Geocache;
import cgeo.geocaching.network.Network;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.storage.DataStore;
import cgeo.geocaching.ui.CacheDetailsCreator;
import cgeo.geocaching.utils.AndroidRxUtils;
import cgeo.geocaching.utils.CancellableHandler;
import cgeo.geocaching.utils.Log;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.lang.ref.WeakReference;
import java.util.Collections;
import java.util.Set;
import butterknife.ButterKnife;
import org.apache.commons.lang3.StringUtils;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.schedulers.Schedulers;
public class CachePopupFragment extends AbstractDialogFragment {
private final Progress progress = new Progress();
public static DialogFragment newInstance(final String geocode) {
final Bundle args = new Bundle();
args.putString(GEOCODE_ARG, geocode);
final DialogFragment f = new CachePopupFragment();
f.setStyle(DialogFragment.STYLE_NO_TITLE, 0);
f.setArguments(args);
return f;
}
private static class StoreCacheHandler extends CancellableHandler {
private final int progressMessage;
private final WeakReference<CachePopupFragment> popupRef;
StoreCacheHandler(final CachePopupFragment popup, final int progressMessage) {
this.progressMessage = progressMessage;
popupRef = new WeakReference<>(popup);
}
@Override
public void handleRegularMessage(final Message msg) {
if (msg.what == UPDATE_LOAD_PROGRESS_DETAIL && msg.obj instanceof String) {
updateStatusMsg((String) msg.obj);
} else {
final CachePopupFragment popup = popupRef.get();
if (popup != null) {
popup.init();
}
}
}
private void updateStatusMsg(final String msg) {
final CachePopupFragment popup = popupRef.get();
if (popup == null) {
return;
}
popup.progress.setMessage(popup.getResources().getString(progressMessage)
+ "\n\n"
+ msg);
}
}
private static class DropCacheHandler extends Handler {
private final WeakReference<CachePopupFragment> popupRef;
public DropCacheHandler(final CachePopupFragment popup) {
this.popupRef = new WeakReference<>(popup);
}
@Override
public void handleMessage(final Message msg) {
final CachePopupFragment popup = popupRef.get();
if (popup == null) {
return;
}
popup.getActivity().finish();
}
}
@Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.popup, container, false);
initCustomActionBar(v);
return v;
}
@Override
protected void init() {
super.init();
try {
if (StringUtils.isNotBlank(cache.getName())) {
setTitle(cache.getName());
} else {
setTitle(geocode);
}
final TextView titleView = ButterKnife.findById(getView(), R.id.actionbar_title);
titleView.setCompoundDrawablesWithIntrinsicBounds(Compatibility.getDrawable(getResources(), cache.getType().markerId), null, null, null);
final LinearLayout layout = ButterKnife.findById(getView(), R.id.details_list);
details = new CacheDetailsCreator(getActivity(), layout);
addCacheDetails();
// offline use
CacheDetailActivity.updateOfflineBox(getView(), cache, res, new RefreshCacheClickListener(), new DropCacheClickListener(), new StoreCacheClickListener(), null);
CacheDetailActivity.updateCacheLists(getView(), cache, res);
} catch (final Exception e) {
Log.e("CachePopupFragment.init", e);
}
// cache is loaded. remove progress-popup if any there
progress.dismiss();
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
if (super.onOptionsItemSelected(item)) {
return true;
}
final int menuItem = item.getItemId();
switch (menuItem) {
case R.id.menu_delete:
new DropCacheClickListener().onClick(getView());
return true;
}
return false;
}
@Override
public void onConfigurationChanged(final Configuration newConfig) {
super.onConfigurationChanged(newConfig);
init();
}
private class StoreCacheClickListener implements View.OnClickListener {
@Override
public void onClick(final View arg0) {
if (progress.isShowing()) {
showToast(res.getString(R.string.err_detail_still_working));
return;
}
if (Settings.getChooseList() || cache.isOffline()) {
// let user select list to store cache in
new StoredList.UserInterface(getActivity()).promptForMultiListSelection(R.string.lists_title,
new Action1<Set<Integer>>() {
@Override
public void call(final Set<Integer> selectedListIds) {
storeCache(selectedListIds);
}
}, true, cache.getLists());
} else {
storeCache(Collections.singleton(StoredList.STANDARD_LIST_ID));
}
}
protected void storeCache(final Set<Integer> listIds) {
if (cache.isOffline()) {
// cache already offline, just add to another list
DataStore.saveLists(Collections.singletonList(cache), listIds);
CacheDetailActivity.updateOfflineBox(getView(), cache, res, new RefreshCacheClickListener(), new DropCacheClickListener(), new StoreCacheClickListener(), null);
CacheDetailActivity.updateCacheLists(getView(), cache, res);
} else {
final StoreCacheHandler storeCacheHandler = new StoreCacheHandler(CachePopupFragment.this, R.string.cache_dialog_offline_save_message);
final FragmentActivity activity = getActivity();
progress.show(activity, res.getString(R.string.cache_dialog_offline_save_title), res.getString(R.string.cache_dialog_offline_save_message), true, storeCacheHandler.cancelMessage());
AndroidRxUtils.andThenOnUi(Schedulers.io(), new Action0() {
@Override
public void call() {
cache.store(listIds, storeCacheHandler);
}
}, new Action0() {
@Override
public void call() {
activity.supportInvalidateOptionsMenu();
CacheDetailActivity.updateOfflineBox(getView(), cache, res, new RefreshCacheClickListener(), new DropCacheClickListener(), new StoreCacheClickListener(), null);
CacheDetailActivity.updateCacheLists(getView(), cache, res);
}
});
}
}
}
private class RefreshCacheClickListener implements View.OnClickListener {
@Override
public void onClick(final View arg0) {
if (progress.isShowing()) {
showToast(res.getString(R.string.err_detail_still_working));
return;
}
if (!Network.isConnected()) {
showToast(getString(R.string.err_server));
return;
}
final StoreCacheHandler refreshCacheHandler = new StoreCacheHandler(CachePopupFragment.this, R.string.cache_dialog_offline_save_message);
progress.show(getActivity(), res.getString(R.string.cache_dialog_refresh_title), res.getString(R.string.cache_dialog_refresh_message), true, refreshCacheHandler.cancelMessage());
cache.refresh(refreshCacheHandler, AndroidRxUtils.networkScheduler);
}
}
private class DropCacheClickListener implements View.OnClickListener {
@Override
public void onClick(final View arg0) {
if (progress.isShowing()) {
showToast(res.getString(R.string.err_detail_still_working));
return;
}
final DropCacheHandler dropCacheHandler = new DropCacheHandler(CachePopupFragment.this);
progress.show(getActivity(), res.getString(R.string.cache_dialog_offline_drop_title), res.getString(R.string.cache_dialog_offline_drop_message), true, null);
cache.drop(dropCacheHandler);
}
}
@Override
public void navigateTo() {
NavigationAppFactory.startDefaultNavigationApplication(1, getActivity(), cache);
}
@Override
public void showNavigationMenu() {
NavigationAppFactory.showNavigationMenu(getActivity(), cache, null, null, true, true);
}
/**
* Tries to navigate to the {@link Geocache} of this activity.
*/
@Override
protected void startDefaultNavigation2() {
if (cache == null || cache.getCoords() == null) {
showToast(res.getString(R.string.cache_coordinates_no));
return;
}
NavigationAppFactory.startDefaultNavigationApplication(2, getActivity(), cache);
getActivity().finish();
}
@Override
protected TargetInfo getTargetInfo() {
if (cache == null) {
return null;
}
return new TargetInfo(cache.getCoords(), cache.getGeocode());
}
}
|
package org.fife.ui.rsyntaxtextarea.demo;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import org.fife.ui.rtextarea.*;
import org.fife.ui.rsyntaxtextarea.*;
/**
* A simple example showing how to do search and replace in a RSyntaxTextArea.
* The toolbar isn't very user-friendly, but this is just to show you how to use
* the API.
*/
public final class FindAndReplaceDemo extends JFrame implements ActionListener {
private static final long serialVersionUID = 1L;
private RSyntaxTextArea textArea;
private JTextField searchField;
private JCheckBox regexCB;
private JCheckBox matchCaseCB;
private FindAndReplaceDemo() {
JPanel cp = new JPanel(new BorderLayout());
textArea = new RSyntaxTextArea(20, 60);
textArea.setText("one two three one\ntwo three one two\nthree one two three");
textArea.setCaretPosition(0);
textArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_JAVA);
textArea.setCodeFoldingEnabled(true);
RTextScrollPane sp = new RTextScrollPane(textArea);
cp.add(sp);
// Create a toolbar with searching options.
JToolBar toolBar = new JToolBar();
searchField = new JTextField(30);
toolBar.add(searchField);
final JButton nextButton = new JButton("Find Next");
nextButton.setActionCommand("FindNext");
nextButton.addActionListener(this);
toolBar.add(nextButton);
JButton prevButton = new JButton("Find Previous");
prevButton.setActionCommand("FindPrev");
prevButton.addActionListener(this);
toolBar.add(prevButton);
regexCB = new JCheckBox("Regex");
toolBar.add(regexCB);
matchCaseCB = new JCheckBox("Match Case");
toolBar.add(matchCaseCB);
cp.add(toolBar, BorderLayout.NORTH);
// Make Enter and Shift + Enter search forward and backward,
// respectively, when the search field is focused.
InputMap im = searchField.getInputMap();
ActionMap am = searchField.getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "searchForward");
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, InputEvent.SHIFT_MASK), "searchBackward");
am.put("searchForward", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
nextButton.doClick(0);
}
});
am.put("searchBackward", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
prevButton.doClick(0);
}
});
// Make Ctrl+F/Cmd+F focus the search field
int defaultMod = Toolkit.getDefaultToolkit().getMenuShortcutKeyMask();
im = textArea.getInputMap();
am = textArea.getActionMap();
im.put(KeyStroke.getKeyStroke(KeyEvent.VK_F, defaultMod), "doSearch");
am.put("doSearch", new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
searchField.requestFocusInWindow();
}
});
setContentPane(cp);
setTitle("Find and Replace Demo");
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
pack();
setLocationByPlatform(true);
}
@Override
public void actionPerformed(ActionEvent e) {
// "FindNext" => search forward, "FindPrev" => search backward
String command = e.getActionCommand();
boolean forward = "FindNext".equals(command);
// Create an object defining our search parameters.
SearchContext context = new SearchContext();
String text = searchField.getText();
if (text.length() == 0) {
return;
}
context.setSearchFor(text);
context.setMatchCase(matchCaseCB.isSelected());
context.setRegularExpression(regexCB.isSelected());
context.setSearchForward(forward);
context.setWholeWord(false);
boolean found = SearchEngine.find(textArea, context).wasFound();
if (!found) {
JOptionPane.showMessageDialog(this, "Text not found");
}
}
public static void main(String[] args) {
// Start all Swing applications on the EDT.
SwingUtilities.invokeLater(() -> {
try {
String laf = UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(laf);
} catch (Exception e) { /* never happens */ }
FindAndReplaceDemo demo = new FindAndReplaceDemo();
demo.setVisible(true);
demo.textArea.requestFocusInWindow();
});
}
}
|
package com.lunaticedit.legendofwaffles;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.*;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.glutils.FrameBuffer;
import com.badlogic.gdx.math.Rectangle;
import com.badlogic.gdx.math.Vector2;
import com.lunaticedit.legendofwaffles.factories.RepositoryFactory;
import com.lunaticedit.legendofwaffles.factories.SceneFactory;
import com.lunaticedit.legendofwaffles.factories.SpriteBatchFactory;
import com.lunaticedit.legendofwaffles.helpers.Constants;
import com.lunaticedit.legendofwaffles.implementations.Input;
import com.lunaticedit.legendofwaffles.services.ProcessableServices;
import com.lunaticedit.legendofwaffles.services.RenderServices;
import com.lunaticedit.legendofwaffles.services.RepositoryServices;
public class GameScreen implements Screen, InputProcessor {
private Rectangle _viewport;
private final Camera _camera;
private final FrameBuffer _fbo;
public GameScreen() throws UnsupportedOperationException {
(new RepositoryServices(new RepositoryFactory(), new SceneFactory())).bootstrap();
Gdx.input.setInputProcessor(this);
Gdx.input.setCatchBackKey(true);
Gdx.input.setCatchMenuKey(true);
_camera = new OrthographicCamera(Constants.GameWidth, Constants.GameHeight);
_fbo = new FrameBuffer(Pixmap.Format.RGB565, Constants.GameWidth, Constants.GameHeight, false);
Gdx.gl.glTexParameterf(GL20.GL_TEXTURE_2D, GL20.GL_TEXTURE_MAG_FILTER, GL20.GL_NEAREST);
Gdx.gl.glTexParameterf(GL20.GL_TEXTURE_2D, GL20.GL_TEXTURE_MIN_FILTER, GL20.GL_NEAREST);
Gdx.gl.glTexParameterf(GL20.GL_TEXTURE_2D, GL20.GL_TEXTURE_WRAP_S, GL20.GL_CLAMP_TO_EDGE);
Gdx.gl.glTexParameterf(GL20.GL_TEXTURE_2D, GL20.GL_TEXTURE_WRAP_T, GL20.GL_CLAMP_TO_EDGE);
}
@Override
public void render(final float delta) {
if (_viewport == null) { return; }
_camera.update();
final SpriteBatch batch = (new SpriteBatchFactory()).generate();
Gdx.gl.glViewport((int) _viewport.x, (int) _viewport.y, (int) _viewport.width, (int) _viewport.height);
batch.setProjectionMatrix(_camera.combined);
_fbo.begin();
Gdx.gl.glClearColor(0.3f, 0.5f, 0.9f, 1.0f);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
batch.begin();
try { (new RenderServices(new RepositoryFactory())).render(); }
catch (Exception e) { Gdx.app.log("Error", e.getMessage(), e); }
batch.end();
_fbo.end();
batch.begin();
Gdx.gl.glViewport((int) _viewport.x, (int) _viewport.y, (int) _viewport.width, (int) _viewport.height);
batch.draw(_fbo.getColorBufferTexture(), -Constants.GameWidth / 2, -Constants.GameHeight / 2,
Constants.GameWidth, Constants.GameHeight, 0, 0, Constants.GameWidth, Constants.GameHeight, false, true);
batch.end();
try { (new ProcessableServices(new RepositoryFactory())).process(); }
catch (Exception e) { Gdx.app.log("Error", e.getMessage(), e); }
}
/*
public void render(final float delta) {
if (_viewport == null) { return; }
_camera.update();
Gdx.gl.glViewport((int) _viewport.x, (int) _viewport.y, (int) _viewport.width, (int) _viewport.height);
(new SpriteBatchFactory()).generate().setProjectionMatrix(_camera.combined);
Gdx.gl.glClearColor(0.3f, 0.5f, 0.9f, 1.0f);
Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
(new SpriteBatchFactory()).generate().begin();
try { (new RenderServices(new RepositoryFactory())).render(); }
catch (Exception e) { Gdx.app.log("Error", e.getMessage(), e); }
(new SpriteBatchFactory()).generate().end();
try { (new ProcessableServices(new RepositoryFactory())).process(); }
catch (Exception e) { Gdx.app.log("Error", e.getMessage(), e); }
}
*/
@Override
public void resize(final int width, final int height) {
float aspectRatio = (float)width/(float)height;
float scale;
Vector2 crop = new Vector2(0f, 0f);
if(aspectRatio > Constants.AspectRatio)
{ scale = (float)height/(float)Constants.GameHeight; crop.x = (width - Constants.GameWidth * scale)/2f; }
else if(aspectRatio < Constants.AspectRatio)
{ scale = (float)width/(float)Constants.GameWidth; crop.y = (height - Constants.GameHeight*scale)/2f; }
else { scale = (float)width/(float)Constants.GameWidth; }
float w = (float)Constants.GameWidth * scale;
float h = -(float)Constants.GameHeight * scale;
_viewport = new Rectangle(crop.x, crop.y, w, h);
}
@Override
public void show() {}
@Override
public void hide() {}
@Override
public void pause() {}
@Override
public void resume() {}
@Override
public void dispose() {}
@Override
public boolean keyDown(final int keycode)
{ Input.getInstance().setKeyState(keycode, true); return true; }
@Override
public boolean keyUp(final int keycode)
{ Input.getInstance().setKeyState(keycode, false); return false; }
@Override
public boolean keyTyped(final char character)
{ return false; }
@Override
public boolean touchDown(final int screenX, final int screenY, final int pointer, final int button)
{ return false; }
@Override
public boolean touchUp(final int screenX, final int screenY, final int pointer, final int button)
{ return false; }
@Override
public boolean touchDragged(final int screenX, final int screenY, final int pointer)
{ return false; }
@Override
public boolean mouseMoved(final int screenX, final int screenY)
{ return false; }
@Override
public boolean scrolled(final int amount)
{ return false; }
}
|
package at.r7r.schemaInject.dao;
import java.util.LinkedList;
import java.util.List;
/**
* Wrapper around {@link StringBuffer} that adds delimiter support and has some SQL-specific methods
*/
public class SqlBuilder {
/**
* List of string parts (will be joined in {@link #join()})
*/
private List<String> mParts = new LinkedList<String>();
/**
* Delimiter that will be inserted between the items of {@link #mParts}
*/
private String mDelimiter = null;
/**
* Specifies if we should add a new line at the end of each item (including the last one)
*/
private boolean mNewLine = false;
/**
* Constructs a {@link SqlBuilder} object and specifies delimiter and newLine
* @param delimiter Delimiter to insert between items
* @param newLine Specifies whether to add a newLine after each item (even the last one) or not
*/
public SqlBuilder(String delimiter, boolean newLine) {
mDelimiter = delimiter;
mNewLine = newLine;
}
/**
* Constructs a {@link SqlBuilder} without delimiter and newLine set to false
*/
public SqlBuilder() {
}
/**
* Appends a String to the buffer
* @param sql String to add
*/
public void append(String sql) {
mParts.add(sql);
}
/**
* Appends another SqlBuilder object (short form of {@code append(sql.join())})
* @param sql SqlBuilder object to append
*/
public void append(SqlBuilder sql) {
append(sql.join());
}
/**
* Appends an SQL identifier (e.g. a column or table name) enclosed in double brackets
* @param name Identifier name
*/
public void appendIdentifier(String name) {
// TODO escape identifier name
append('\"'+name+'\"');
}
/**
* Joins the parts using the specified delimiter (if present) between and a newline character (if specified) after each item
* @return Joined String
*/
public String join() {
StringBuffer buffer = new StringBuffer();
int i = 0, size = mParts.size();
for (String part: mParts) {
buffer.append(part);
if (mDelimiter != null && ++i < size) buffer.append(mDelimiter);
if (mNewLine) buffer.append('\n');
}
return buffer.toString();
}
public void prepend(String str) {
mParts.add(0, str);
}
/**
* Simply calls {@link #join()}
* @return Joined {@link String}
*/
public String toString() {
return join();
}
}
|
package ch.openech.xml.write;
import java.io.Writer;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;
import org.minimalj.model.properties.FlatProperties;
import org.minimalj.model.validation.InvalidValues;
import org.minimalj.util.StringUtils;
import ch.openech.model.types.EchCode;
public class WriterElement {
public static final String XMLSchema_URI = "http:
private XMLStreamWriter writer;
private String namespaceURI;
private WriterElement child;
public WriterElement(Writer writer, String namespaceURI) {
XMLOutputFactory factory = XMLOutputFactory.newInstance();
try {
this.writer = new IndentingXMLStreamWriter(factory.createXMLStreamWriter(writer));
this.writer.writeStartDocument("UTF-8", "1.0");
} catch (XMLStreamException e) {
throw new RuntimeException(e);
}
this.namespaceURI = namespaceURI;
}
public WriterElement(XMLStreamWriter writer, String namespaceURI) {
this.writer = writer;
this.namespaceURI = namespaceURI;
}
public WriterElement create(String childNameSpaceURI, String localName) throws XMLStreamException {
flush();
writer.writeStartElement(namespaceURI, localName); // OUR namespaceURI not the child's
child = new WriterElement(writer, childNameSpaceURI);
return child;
}
public void startDocument(EchSchema context, int schemaNumber, String rootType) throws XMLStreamException {
List<Integer> namespaceNumbers = new ArrayList<Integer>(context.getNamespaceNumbers());
Collections.sort(namespaceNumbers);
setPrefixs(context, namespaceNumbers);
writer.writeStartElement(namespaceURI, rootType);
writeXmlSchemaLocation(context, schemaNumber);
writeNamespaces(context, namespaceNumbers);
}
private void writeXmlSchemaLocation(EchSchema context, int schemaNumber) throws XMLStreamException {
writer.writeAttribute(WriterEch0020.XMLSchema_URI, "schemaLocation",
context.getNamespaceURI(schemaNumber) + " " +
context.getNamespaceLocation(schemaNumber));
}
private void setPrefixs(EchSchema namespaceContext, List<Integer> namespaceNumbers) throws XMLStreamException {
writer.setPrefix("xsi", XMLSchema_URI);
for (int number : namespaceNumbers) {
writer.setPrefix("e" + number, namespaceContext.getNamespaceURI(number));
}
}
private void writeNamespaces(EchSchema namespaceContext, List<Integer> namespaceNumbers) throws XMLStreamException {
writer.writeNamespace("xsi", XMLSchema_URI);
for (int number : namespaceNumbers) {
writer.writeNamespace("e" + number, namespaceContext.getNamespaceURI(number));
}
if (namespaceContext.getOpenEchNamespaceLocation() != null) {
writer.writeNamespace("openEch", namespaceContext.getOpenEchNamespaceLocation());
}
}
public void endDocument() throws XMLStreamException {
flush();
writer.writeEndElement();
writer.writeEndDocument();
writer.flush();
}
public void text(String localName, String text) throws Exception {
flush();
writer.writeStartElement(namespaceURI, localName);
writer.writeCharacters(text);
writer.writeEndElement();
}
public void textIfSet(String localName, String text) throws Exception {
if (!StringUtils.isEmpty(text)) {
flush();
writer.writeStartElement(namespaceURI, localName);
writer.writeCharacters(text);
writer.writeEndElement();
}
}
public void text(String localName, LocalDate localDate) throws Exception {
if (localDate != null) {
text(localName, DateTimeFormatter.ISO_DATE.format(localDate));
}
}
public void text(String localName, LocalDateTime localDateTime) throws Exception {
if (localDateTime != null) {
text(localName, DateTimeFormatter.ISO_DATE_TIME.format(localDateTime));
}
}
public void text(String localName, EchCode echCode) throws Exception {
if (echCode != null) {
if (!InvalidValues.isInvalid(echCode)) {
text(localName, echCode.getValue());
} else {
text(localName, InvalidValues.getInvalidValue(echCode));
}
}
}
public void text(String localName, Integer integer) throws Exception {
if (integer != null) {
text(localName, String.valueOf(integer));
}
}
public void values(Object object, String... keys) throws Exception {
for (String key : keys) {
Object value = FlatProperties.getValue(object, key);
if (value instanceof EchCode) {
text(key, (EchCode)value);
} else if (value != null) {
String string = value.toString();
if (!StringUtils.isBlank(string)) {
text(key, string);
}
}
}
}
public void values(Object object) throws Exception {
Set<String> keys = FlatProperties.getProperties(object.getClass()).keySet();
values(object, keys.toArray(new String[keys.size()]));
}
public void writeAttribute(String namespaceURI, String localName, String value) throws XMLStreamException {
writer.writeAttribute(namespaceURI, localName, value);
}
public void writeAttribute(String localName, String value) throws XMLStreamException {
writer.writeAttribute(localName, value);
}
public void flush() throws XMLStreamException {
if (child != null) {
child.flush();
writer.writeEndElement();
child = null;
}
}
}
|
package com.Acrobot.ChestShop;
import com.Acrobot.Breeze.Utils.MaterialUtil;
import com.Acrobot.ChestShop.Configuration.Properties;
import com.Acrobot.ChestShop.Listeners.Economy.Plugins.ReserveListener;
import com.Acrobot.ChestShop.Listeners.Economy.Plugins.VaultListener;
import com.Acrobot.ChestShop.Plugins.*;
import com.sk89q.worldguard.bukkit.WorldGuardPlugin;
import org.bukkit.Bukkit;
import org.bukkit.event.Listener;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
/**
* @author Acrobot
*/
public class Dependencies {
public static void initializePlugins() {
PluginManager pluginManager = Bukkit.getPluginManager();
for (String dependency : ChestShop.getDependencies()) {
Plugin plugin = pluginManager.getPlugin(dependency);
if (plugin != null) {
initializePlugin(dependency, plugin);
}
}
}
private static void initializePlugin(String name, Plugin plugin) { //Really messy, right? But it's short and fast :)
Dependency dependency;
try {
dependency = Dependency.valueOf(name);
} catch (IllegalArgumentException exception) {
return;
}
switch (dependency) {
//Terrain protection plugins
case WorldGuard:
if (Properties.WORLDGUARD_USE_FLAG) {
WorldGuardFlags.ENABLE_SHOP.getName(); // force the static code to run
}
break;
}
PluginDescriptionFile description = plugin.getDescription();
ChestShop.getBukkitLogger().info(description.getName() + " version " + description.getVersion() + " loaded.");
}
public static boolean loadPlugins() {
PluginManager pluginManager = Bukkit.getPluginManager();
for (String dependency : ChestShop.getDependencies()) {
Plugin plugin = pluginManager.getPlugin(dependency);
if (plugin != null && plugin.isEnabled()) {
loadPlugin(dependency, plugin);
}
}
return loadEconomy();
}
private static boolean loadEconomy() {
String plugin = "none";
Listener economy = null;
if(Bukkit.getPluginManager().getPlugin("Reserve") != null) {
plugin = "Reserve";
economy = ReserveListener.prepareListener();
}
if(Bukkit.getPluginManager().getPlugin("Vault") != null) {
plugin = "Vault";
economy = VaultListener.initializeVault();
}
if (economy == null) {
ChestShop.getBukkitLogger().severe("No Economy plugin found! You need to install either Vault or Reserve and a compatible economy!");
return false;
}
ChestShop.registerListener(economy);
ChestShop.getBukkitLogger().info(plugin + " loaded! Found an economy plugin!");
return true;
}
private static void loadPlugin(String name, Plugin plugin) { //Really messy, right? But it's short and fast :)
Dependency dependency;
try {
dependency = Dependency.valueOf(name);
} catch (IllegalArgumentException exception) {
return;
}
Listener listener = null;
switch (dependency) {
//Protection plugins
case LWC:
listener = new LightweightChestProtection();
break;
case Lockette:
listener = new Lockette();
break;
case Deadbolt:
listener = new Deadbolt();
break;
case SimpleChestLock:
listener = SimpleChestLock.getSimpleChestLock(plugin);
break;
case Residence:
if (plugin.getDescription().getVersion().startsWith("2")) {
ChestShop.getBukkitLogger().severe("You are using an old version of Residence! " +
"Please update to the newest one, which supports UUIDs: http://ci.drtshock.net/job/Residence/");
break;
}
listener = new ResidenceChestProtection();
break;
//Terrain protection plugins
case WorldGuard:
WorldGuardPlugin worldGuard = (WorldGuardPlugin) plugin;
boolean inUse = Properties.WORLDGUARD_USE_PROTECTION || Properties.WORLDGUARD_INTEGRATION;
if (!inUse) {
return;
}
if (Properties.WORLDGUARD_USE_PROTECTION) {
ChestShop.registerListener(new WorldGuardProtection(worldGuard));
}
if (Properties.WORLDGUARD_INTEGRATION) {
listener = new WorldGuardBuilding(worldGuard);
}
break;
//Other plugins
case Heroes:
Heroes heroes = Heroes.getHeroes(plugin);
if (heroes == null) {
return;
}
listener = heroes;
break;
case OddItem:
MaterialUtil.Odd.initialize();
break;
case ShowItem:
MaterialUtil.Show.initialize(plugin);
break;
}
if (listener != null) {
ChestShop.registerListener(listener);
}
PluginDescriptionFile description = plugin.getDescription();
ChestShop.getBukkitLogger().info(description.getName() + " version " + description.getVersion() + " loaded.");
}
private static enum Dependency {
LWC,
Lockette,
Deadbolt,
SimpleChestLock,
Residence,
OddItem,
WorldGuard,
Heroes,
ShowItem
}
}
|
package controllers;
import play.*;
import play.vfs.VirtualFile;
import util.SubattributeRelationMismatchException;
import java.io.File;
import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import models.attribute.ArrayAttribute;
import models.attribute.Attribute;
import models.data.*;
import util.Util;
public class Data extends CORSController {
public static void listAll() { listAll(Relation.class); }
public static void describe(String id) {
try {
renderJSON( new Relation.Description(find(id), new Query(params.data), Util.requestPath()) );
} catch (QueryException qe) {
badRequest(qe.getMessage());
}
}
public static String getReverseRoute(Relation relation, Query query) {
return Util.getReverseRoute("Data.describe", (query == null ? Query.getEmptyQuery() : query).makeMap("id", relation.name));
}
protected static Relation find(final String id) {
Relation relation = Relation.findById(id);
if (relation == null)
notFoundSeeList("relation", "Data.listAll");
return relation;
}
public static String _deleteAll() {
//Cascading delete cannot handle potentially complex object graphs that have been persisted, so manually unlink models first
for (Relation relation : Relation.all().<Relation>fetch())
relation.prepareForDeletion();
return String.format("%s\nRemoved %d relation(s) and %d attribute(s)", new Date(), Relation.deleteAll(), Attribute.deleteAll());
}
public static String _initialiseRelations() {
long relationCountBefore = Relation.count();
long attrCountBefore = Attribute.count();
File dataDir = VirtualFile.fromRelativePath("/private/datasets").getRealFile();
File[] relationFiles = dataDir.listFiles( (FilenameFilter) new SuffixFileFilter(".js") );
for (File relationFile : relationFiles) {
Logger.trace("Processing relation file: " + relationFile);
initialiseRelation(relationFile);
}
long addedRelations = Relation.count() - relationCountBefore;
long addedAttributes = Attribute.count() - attrCountBefore;
long ignored = relationFiles.length - addedRelations;
return String.format("%s\nSuccessfully created and persisted %d relation(s) and %d distinct attribute(s).%s", new Date(), addedRelations, addedAttributes,
ignored == 0? "" : String.format("\nIgnored %d definitions corresponding to existing relation models.", ignored));
}
private static void initialiseRelation(File relationFile) {
try {
//New relation will also create any locally defined attributes
Logger.info("Loading relation from %s", relationFile);
Relation.Create req = loadRelationCreationRequest(relationFile);
failOnInvalidMessage(req); //even though used internally, still check it
if ( Relation.findById(req.name) == null)
Relation.create(req);
} catch (IOException ioe) {
error(ioe);
} catch (SubattributeRelationMismatchException srme) {
badRequest(srme.getMessage());
}
}
private static Relation.Create loadRelationCreationRequest(File relationFile) throws IOException {
//Just load the entire file all at once
FileReader in = null;
try {
in = new FileReader( relationFile );
char[] buffer = new char[ (int) relationFile.length() ];
in.read(buffer);
return Util.GSON.fromJson(new String(buffer), Relation.Create.class);
} finally {
if (in != null) in.close();
}
}
}
|
package com.agilarity.osmo.feature;
import static java.lang.String.format;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import osmo.tester.annotation.TestStep;
import osmo.tester.model.Requirements;
import com.agilarity.osmo.runner.OsmoTestException;
/**
* Responsible for defining a feature model.
*
* @param D
* Test driver is the facade to the system under test
* @param S
* Test state is used to track the state of the system under test
*/
public abstract class Feature<D, S> { // NOPMD
private static final int EXPECTED_STEPS = 1;
private static final String ONE_STEP = "Expected [1] @TestStep annotation in %s but got [%s]"; // NOCS
private final String requirement;
protected final Requirements requirements; // NOCS NOPMD
protected final D driver; // NOCS NOPMD
protected final S state; // NOCS NOPMD
/**
* @param requirements
* The requirements
* @param driver
* Test driver is the facade to the system under test
* @param state
* Test state is used to track the state of the system under test
*/
public Feature(final Requirements requirements, final D driver,
final S state) {
this.requirements = requirements;
this.driver = driver;
this.state = state;
requirement = findStepName();
if (!this.requirements.getRequirements().contains(requirement)) {
requirements.add(requirement);
}
}
/**
* @return Requirements
*/
public Requirements getRequirements() {
return requirements;
}
/**
* @return Requirement name
*/
public String getRequirement() {
return requirement;
}
/**
* Cover the requirement for this feature.
*/
protected void coverRequirement() {
requirements.covered(requirement);
}
private String findStepName() {
final Method method = findTestStepMethod();
final TestStep annotation = method.getAnnotation(TestStep.class);
if (annotation.value().isEmpty()) {
return method.getName();
} else {
return annotation.value();
}
}
private Method findTestStepMethod() {
final List<Method> testSteps = findTestSteps();
requireExactlyOneTestStep(testSteps);
return testSteps.get(0);
}
private List<Method> findTestSteps() { // NOPMD
final List<Method> testSteps = new ArrayList<Method>();
final Method[] methods = getClass().getDeclaredMethods();
for (final Method method : methods) {
final TestStep annotation = method.getAnnotation(TestStep.class);
if (annotation != null) {
testSteps.add(method);
}
}
return testSteps;
}
private void requireExactlyOneTestStep(final List<Method> testSteps) {
if (testSteps.size() != EXPECTED_STEPS) {
final String error = format(ONE_STEP, getClass().getSimpleName(),
testSteps.size());
throw new OsmoTestException(error);
}
}
}
|
package com.exedio.cope;
import com.exedio.cope.testmodel.AttributeItem;
import com.exedio.cope.testmodel.EmptyItem;
public class TransactionTest extends TestmodelTest
{
protected EmptyItem someItem;
protected AttributeItem item;
private final AttributeItem newItem(final String code) throws ConstraintViolationException
{
return new AttributeItem(code, 5, 6l, 2.2, true, someItem, AttributeItem.SomeEnum.enumValue1);
}
public void setUp() throws Exception
{
super.setUp();
deleteOnTearDown(someItem = new EmptyItem());
deleteOnTearDown(item = newItem("someString"));
}
public void tearDown() throws Exception // TODO: remove !!!!
{
super.tearDown();
}
private Transaction createTransaction(final String name)
{
return model.startTransaction(name);
}
private void commit()
{
model.commit();
}
private void rollback()
{
model.rollback();
}
private void assertSomeString(final AttributeItem actualItem, final String someString)
{
assertEquals(someString, actualItem.getSomeString());
assertTrue(actualItem.TYPE.search(actualItem.someString.equal(someString)).contains(actualItem));
assertFalse(actualItem.TYPE.search(actualItem.someString.equal("X"+someString)).contains(actualItem));
}
private void assertSomeString(final String someString)
{
assertSomeString(item, someString);
}
private void assertNotExists(final AttributeItem actualItem) throws MandatoryViolationException, IntegrityViolationException
{
assertTrue(!actualItem.existsCopeItem());
try
{
actualItem.getSomeNotNullString();
fail();
}
catch(NoSuchItemException e)
{
assertSame(actualItem, e.getItem());
}
try
{
actualItem.setSomeNotNullString("hallo");
fail();
}
catch(NoSuchItemException e)
{
assertSame(actualItem, e.getItem());
}
try
{
actualItem.deleteCopeItem();
fail();
}
catch(NoSuchItemException e)
{
assertSame(actualItem, e.getItem());
}
assertNotNull(actualItem.getCopeID());
assertTrue(actualItem.equals(actualItem));
actualItem.hashCode(); // test, that hashCode works
}
public void testCommitChange() throws ConstraintViolationException
{
assertSomeString(null);
item.setSomeString("someString");
assertSomeString("someString");
commit();
createTransaction("testCommitChange1");
assertSomeString("someString");
item.setSomeString("someString2");
assertSomeString("someString2");
item.setSomeString(null);
commit();
createTransaction("testCommitChange2");
assertSomeString(null);
}
public void testCommitCreate() throws ConstraintViolationException
{
item.setSomeString("someString");
final AttributeItem itemx = newItem("someStringX");
deleteOnTearDown(itemx);
assertSomeString(itemx, null);
assertTrue(itemx.existsCopeItem());
commit();
createTransaction("testCommitCreate1");
assertSomeString(itemx, null);
assertTrue(itemx.existsCopeItem());
final AttributeItem itemy = newItem("someStringY");
deleteOnTearDown(itemy);
assertSomeString(itemx, null);
assertSomeString(itemy, null);
assertTrue(itemy.existsCopeItem());
itemx.setSomeString("someStringX");
itemy.setSomeString("someStringY");
assertSomeString(itemx, "someStringX");
assertSomeString(itemy, "someStringY");
commit();
createTransaction("testCommitCreate2");
assertSomeString(itemx, "someStringX");
assertSomeString(itemy, "someStringY");
assertTrue(itemx.existsCopeItem());
assertTrue(itemy.existsCopeItem());
}
public void testCommitDelete() throws ConstraintViolationException
{
final AttributeItem itemx = newItem("someStringX");
assertTrue(itemx.existsCopeItem());
assertEquals("someStringX", itemx.getSomeNotNullString());
itemx.deleteCopeItem();
assertNotExists(itemx);
commit();
createTransaction("testCommitDelete1");
assertNotExists(itemx);
final AttributeItem itemy = newItem("someStringY");
assertTrue(itemy.existsCopeItem());
assertEquals("someStringY", itemy.getSomeNotNullString());
commit();
createTransaction("testCommitDelete2");
assertNotExists(itemx);
assertTrue(itemy.existsCopeItem());
assertEquals("someStringY", itemy.getSomeNotNullString());
itemy.deleteCopeItem();
assertNotExists(itemy);
commit();
createTransaction("testCommitDelete3");
assertNotExists(itemx);
assertNotExists(itemy);
}
public void testRollbackChange() throws ConstraintViolationException
{
commit();
createTransaction("testRollbackChange1");
assertSomeString(null);
item.setSomeString("someString");
assertSomeString("someString");
rollback();
createTransaction("testRollbackChange2");
assertSomeString(null);
item.setSomeString("someString2");
assertSomeString("someString2");
commit();
createTransaction("testRollbackChange3");
assertSomeString("someString2");
item.setSomeString("someString3");
assertSomeString("someString3");
rollback();
createTransaction("testRollbackChange4");
assertSomeString("someString2");
}
public void testRollbackCreate() throws ConstraintViolationException
{
commit();
createTransaction("testRollbackCreate1");
assertContains(item.TYPE.search(item.someNotNullString.equal("someStringX")));
assertContains(item.TYPE.search(item.someNotNullString.equal("someStringY")));
final AttributeItem itemx = newItem("someStringX");
assertSomeString(itemx, null);
assertContains(itemx, itemx.TYPE.search(itemx.someNotNullString.equal("someStringX")));
assertContains(item.TYPE.search(item.someNotNullString.equal("someStringY")));
assertTrue(itemx.existsCopeItem());
rollback();
createTransaction("testRollbackCreate2");
assertContains(itemx.TYPE.search(itemx.someNotNullString.equal("someStringX")));
assertContains(item.TYPE.search(item.someNotNullString.equal("someStringY")));
assertTrue(!itemx.existsCopeItem());
final AttributeItem itemy = newItem("someStringY");
assertNotEquals(itemx, itemy);
assertSomeString(itemy, null);
assertContains(itemx.TYPE.search(itemx.someNotNullString.equal("someStringX")));
assertContains(itemy, itemy.TYPE.search(itemx.someNotNullString.equal("someStringY")));
assertTrue(itemy.existsCopeItem());
itemy.setSomeString("someStringYY");
assertSomeString(itemy, "someStringYY");
assertContains(itemx.TYPE.search(itemx.someNotNullString.equal("someStringX")));
assertContains(itemy, itemy.TYPE.search(itemx.someNotNullString.equal("someStringY")));
rollback();
createTransaction("testRollbackCreate3");
assertContains(itemx.TYPE.search(itemx.someNotNullString.equal("someStringX")));
assertContains(itemy.TYPE.search(itemx.someNotNullString.equal("someStringY")));
assertNotEquals(itemx, itemy);
assertTrue(!itemx.existsCopeItem());
assertTrue(!itemy.existsCopeItem());
}
public void testRollbackDelete() throws ConstraintViolationException
{
final AttributeItem itemx = newItem("someStringX");
commit();
createTransaction("testRollbackDelete1");
assertTrue(itemx.existsCopeItem());
assertEquals("someStringX", itemx.getSomeNotNullString());
itemx.deleteCopeItem();
assertNotExists(itemx);
rollback();
createTransaction("testRollbackDelete2");
assertTrue(itemx.existsCopeItem());
assertEquals("someString", item.getSomeNotNullString());
item.setSomeNotNullString("someString2");
assertTrue(item.existsCopeItem());
assertEquals("someString2", item.getSomeNotNullString());
item.deleteCopeItem();
assertNotExists(item);
rollback();
createTransaction("testRollbackDelete3");
deleteOnTearDown(itemx);
assertTrue(item.existsCopeItem());
assertEquals("someString", item.getSomeNotNullString());
}
public void xxtestIsolation() throws ConstraintViolationException // TODO enable testIsolation
{
if ( ! model.supportsReadCommitted() ) return;
model.commit();
final Transaction t1 = createTransaction("testIsolation1");
model.leaveTransaction();
final Transaction t2 = createTransaction("testIsolation2");
activate(t1);
assertSomeString(null);
activate(t2);
assertSomeString(null);
activate(t1);
assertSomeString(null);
item.setSomeString("someString");
assertSomeString("someString");
activate(t2);
assertSomeString(null);
item.setSomeString("someString2");
assertSomeString("someString2");
activate(t1);
assertSomeString("someString");
item.setSomeString(null);
assertSomeString(null);
activate(t2);
assertSomeString("someString2");
item.setSomeString(null);
assertSomeString(null);
// TODO: test item creation/deletion
}
public void testNesting()
{
assertEquals( true, model.hasCurrentTransaction() );
Transaction tx = model.getCurrentTransaction();
try
{
model.startTransaction("nested");
fail();
}
catch ( RuntimeException e )
{
assertEquals( "there is already a transaction bound to current thread", e.getMessage() );
}
assertEquals( tx, model.getCurrentTransaction() );
}
}
|
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.MouseEvent;
import javax.swing.*;
import javax.swing.plaf.LayerUI;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
ComboBoxModel<String> model = new DefaultComboBoxModel<>(new String[] {"aaa", "bb", "c"});
JComboBox<String> combo = makeComboBox(model);
combo.setEditable(true);
JPanel p = new JPanel(new GridLayout(0, 1, 5, 5));
setBorder(BorderFactory.createEmptyBorder(5, 20, 5, 20));
p.add(new JLabel("setEditable(true)"));
p.add(new JLayer<>(combo, new ToolTipLayerUI<>()));
p.add(Box.createVerticalStrut(10));
p.add(new JLabel("setEditable(false)"));
p.add(new JLayer<>(makeComboBox(model), new ToolTipLayerUI<>()));
add(p, BorderLayout.NORTH);
setPreferredSize(new Dimension(320, 240));
}
private static <E> JComboBox<E> makeComboBox(ComboBoxModel<E> model) {
return new JComboBox<E>(model) {
@Override public void updateUI() {
setRenderer(null);
super.updateUI();
ListCellRenderer<? super E> renderer = getRenderer();
setRenderer((list, value, index, isSelected, cellHasFocus) -> {
Component c = renderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
if (c instanceof JComponent) {
((JComponent) c).setToolTipText(String.format("Item%d: %s", index, value));
}
return c;
});
}
};
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
UIManager.put("example.SearchBarComboBox", "SearchBarComboBoxUI");
UIManager.put("SearchBarComboBoxUI", "example.BasicSearchBarComboBoxUI");
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class ToolTipLayerUI<V extends JComboBox<?>> extends LayerUI<V> {
@Override public void installUI(JComponent c) {
super.installUI(c);
if (c instanceof JLayer) {
((JLayer<?>) c).setLayerEventMask(AWTEvent.MOUSE_MOTION_EVENT_MASK);
}
}
@Override public void uninstallUI(JComponent c) {
if (c instanceof JLayer) {
((JLayer<?>) c).setLayerEventMask(0);
}
super.uninstallUI(c);
}
@Override protected void processMouseMotionEvent(MouseEvent e, JLayer<? extends V> l) {
JComboBox<?> c = l.getView();
if (e.getComponent() instanceof JButton) {
c.setToolTipText("ArrowButton");
} else {
c.setToolTipText("JComboBox: " + c.getSelectedItem());
}
super.processMouseMotionEvent(e, l);
}
}
|
package models;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.nio.charset.Charset;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import play.libs.Json;
import play.libs.F.Function;
import play.libs.F.Promise;
import constants.NodeType;
import managers.LHSManager;
public class LHS extends LabeledNodeWithProperties {
public Rule rule;
public JsonNode json;
private LHS() {
this.label = NodeType.AVM;
this.jsonProperties = Json.newObject();
}
public LHS(Rule rule) {
this();
this.rule = rule;
UUID uuid = UUID.nameUUIDFromBytes(
rule.name.getBytes(Charset.forName("UTF-8")));
this.jsonProperties.put("uuid", uuid.toString());
}
public Promise<Boolean> create() {
Promise<Boolean> created = this.exists()
.flatMap(new CreateFunction(this));
return created.flatMap(new ConnectToRuleFunction(this));
}
public Promise<LHS> get() {
Promise<JsonNode> json = LHSManager.get(this);
return json.flatMap(new GetFunction(this));
}
public Promise<Boolean> add(Feature feature) {
return new HasRelationship(this, feature).create();
}
private class CreateFunction implements
Function<Boolean, Promise<Boolean>> {
private LHS lhs;
public CreateFunction(LHS lhs) {
this.lhs = lhs;
}
public Promise<Boolean> apply(Boolean exists) {
if (exists) {
return Promise.pure(false);
}
return LHSManager.create(this.lhs);
}
}
private class ConnectToRuleFunction
implements Function<Boolean, Promise<Boolean>> {
private LHS lhs;
public ConnectToRuleFunction(LHS lhs) {
this.lhs = lhs;
}
public Promise<Boolean> apply(Boolean created) {
return new LHSRelationship(this.lhs).create();
}
}
private class GetFunction implements Function<JsonNode, Promise<LHS>> {
private LHS lhs;
public GetFunction(LHS lhs) {
this.lhs = lhs;
}
public Promise<LHS> apply(JsonNode json) {
JsonNode data = json.get("data");
if (data.size() > 0) {
// Process node-relationship-node triples appropriately;
// for now just get names of end nodes (i.e.,
// features) and add them to pairs with arbitrary
// default value
List<JsonNode> endNodes = data.findValues("end");
List<Promise<? extends Feature>> featureList =
new ArrayList<Promise<? extends Feature>>();
for (JsonNode endNode: endNodes) {
Promise<Feature> feature = Feature
.getByURL(endNode.asText());
featureList.add(feature);
}
Promise<List<Feature>> features = Promise
.sequence(featureList);
Promise<ObjectNode> pairs = features.map(
new Function<List<Feature>, ObjectNode>() {
public ObjectNode apply(List<Feature> features) {
ObjectNode pairs = Json.newObject();
for (Feature feature: features) {
ObjectNode info = Json.newObject();
info.put("type", feature.getType());
pairs.put(feature.name, info);
}
return pairs;
}
});
return pairs.map(new SetPairsFunction(this.lhs));
} else {
ObjectNode pairs = Json.newObject();
this.lhs.json = pairs;
return Promise.pure(this.lhs);
}
}
}
private static class SetPairsFunction implements
Function<ObjectNode, LHS> {
private LHS lhs;
public SetPairsFunction(LHS lhs) {
this.lhs = lhs;
}
public LHS apply(ObjectNode pairs) {
this.lhs.json = pairs;
return this.lhs;
}
}
}
|
package com.boundary.sdk.event;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.net.URL;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ScriptUtils {
private static Logger LOG = LoggerFactory.getLogger(ScriptUtils.class);
public ScriptUtils() {
}
/**
* Finds a script to be tested from
* @param scriptName
* @return {@link File}
*/
static public FileReader getFile(String scriptPath) {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
URL url = loader.getResource(scriptPath);
assert(url == null);
File f = new File(url.getFile());
FileReader reader = null;
try {
reader = new FileReader(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
LOG.error(e.getMessage());
}
return reader;
}
}
|
package com.cloudmine.api;
import com.cloudmine.api.exceptions.CreationException;
import com.cloudmine.api.persistance.ClassNameRegistry;
import com.cloudmine.api.rest.CMURLBuilder;
import com.cloudmine.api.rest.HeaderFactory;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class CMApiCredentials {
private static final Logger LOG = LoggerFactory.getLogger(CMApiCredentials.class);
private static CMApiCredentials credentials;
private final String applicationIdentifier;
private final String applicationApiKey;
private final String baseUrl;
static {
ClassNameRegistry.register(JavaAccessListController.CLASS_NAME, JavaAccessListController.class);
ClassNameRegistry.register(CMGeoPoint.GEOPOINT_CLASS, CMGeoPoint.class);
ClassNameRegistry.register(JavaCMUser.CLASS_NAME, JavaCMUser.class);
}
/**
* If you are using CloudMine on Android, this or {@link #initialize(String, String, Object)} is the initialize method you should be calling. Works just
* like {@link #initialize(String, String, String)}, but sets some important android only information
* @param id
* @param apiKey
* @param baseUrl the base CloudMine URL to use, if running on a non default CloudMine install
* @param context either null if not running on android, or the value of getApplicationContext from your main activity. It isn't typed here so the Java sdk does not have any android dependencies
* @return
* @throws CreationException in addition to the reasons defined in {@link #initialize(String, String)}, also if you do not provide the application context and you're running on android
*/
public static synchronized CMApiCredentials initialize(String id, String apiKey, String baseUrl, Object context) throws CreationException {
if(Strings.isEmpty(id) || Strings.isEmpty(apiKey) || Strings.isEmpty(baseUrl)) {
throw new CreationException("Illegal null/empty argument passed to initialize. Given id=" + id + " and apiKey=" + apiKey);
}
try {
Class contextClass = Class.forName("android.content.Context");
boolean invalidContext = context == null || contextClass == null || !contextClass.isAssignableFrom(context.getClass());
if(invalidContext) {
throw new CreationException("Running on android and application context not provided, try passing getApplicationContext to this method");
}
for(Method method : Class.forName("com.cloudmine.api.DeviceIdentifier").getMethods()) {
if("initialize".equals(method.getName())) {
method.invoke(null, context);
}
}
} catch (ClassNotFoundException e) {
LOG.info("Not running on Android", e);
} catch (InvocationTargetException e) {
LOG.error("Exception thrown", e);
} catch (IllegalAccessException e) {
LOG.error("Exception thrown", e);
}
credentials = new CMApiCredentials(id, apiKey, baseUrl);
return credentials;
}
/**
* If you are using CloudMine on Android, this or {@link #initialize(String, String, String, Object)} is the initialize method you should be calling. Works just
* like {@link #initialize(String, String)}, but sets some important android only information
* @param id
* @param apiKey
* @param context either null if not running on android, or the value of getApplicationContext from your main activity. It isn't typed here so the Java sdk does not have any android dependencies
* @return
* @throws CreationException in addition to the reasons defined in {@link #initialize(String, String)}, also if you do not provide the application context and you're running on android
*/
public static synchronized CMApiCredentials initialize(String id, String apiKey, Object context) throws CreationException {
return initialize(id, apiKey, CMURLBuilder.CLOUD_MINE_URL, context);
}
/**
* Sets the application id and api key. Can be called multiple times, but only the first call will modify the credentials value.
* It is an error to call this multiple times with different values
* @param id the application id from your CloudMine dashboard
* @param apiKey the API key from your CloudMine dashboard
* @throws CreationException if you try to initialize twice with different values, or null values were passed in
* @return the initialized CMApiCredentials instance
*/
public static synchronized CMApiCredentials initialize(String id, String apiKey) throws CreationException {
return initialize(id, apiKey, CMURLBuilder.CLOUD_MINE_URL);
}
public static synchronized CMApiCredentials initialize(String id, String apiKey, String baseUrl) throws CreationException {
credentials = new CMApiCredentials(id, apiKey, baseUrl);
return credentials;
}
/**
* Create a new instance of CMApiCredentials.
* @param id
* @param apiKey
* @param baseUrl
*/
public CMApiCredentials(String id, String apiKey, String baseUrl) {
if(Strings.isEmpty(id)) throw new CreationException("Cannot have an empty API id");
if(Strings.isEmpty(apiKey)) throw new CreationException("Cannot have an empty API key");
applicationIdentifier = id;
applicationApiKey = apiKey;
this.baseUrl = baseUrl;
}
/**
* Returns the CMApiCredentials that were created in {@link #initialize(String, String)}
* @return the CMApiCredentials
* @throws CreationException if called before the credentials have been initialized
*/
public static CMApiCredentials getCredentials() throws CreationException {
if(credentials == null) {
throw new CreationException("Cannot access CMApiCredentials before they have been initialized. Please make a call to CMApiCredentials.initialize before attempting to make any CloudMine calls");
}
return credentials;
}
/**
* Returns the application identifier
* @return the application identifier
*/
public static String getApplicationIdentifier() {
return getCredentials().applicationIdentifier;
}
/**
* Returns the application API key
* @return the application API key
*/
public static String getApplicationApiKey() {
return getCredentials().applicationApiKey;
}
/**
* Returns a Header that contains the CloudMine authentication information for a request
* @return a Header that contains the CloudMine authentication information for a request
*/
public static Header getCloudMineHeader() {
return new BasicHeader(HeaderFactory.API_HEADER_KEY, getApplicationApiKey());
}
public String getIdentifier() {
return applicationIdentifier;
}
public String getApiKey() {
return applicationApiKey;
}
public String getBaseUrl() {
return baseUrl;
}
}
|
package com.collective.celos;
/**
* Trivial trigger that always signals data availability,
* for use when a workflow doesn't have any data dependencies
* and simply needs to run at every scheduled time.
*/
public class AlwaysTrigger implements Trigger {
public boolean isDataAvailable(ScheduledTime t) {
return true;
}
}
|
package com.github.kratorius.jefs;
import sun.misc.Unsafe;
public class LFBitSet extends NotSafe {
private static Unsafe unsafe = getUnsafe();
private static final int base = unsafe.arrayBaseOffset(long[].class);
private static final int shift;
static {
int scale = Integer.numberOfLeadingZeros(unsafe.arrayIndexScale(long[].class));
shift = 31 - scale;
}
// The volatile is needed because clear() creates a whole new array
private volatile long[] bitset;
private final int nbits;
public LFBitSet(int nbits) {
if (nbits < 0) {
throw new IllegalArgumentException();
}
this.nbits = nbits;
this.bitset = new long[getBucket(nbits) + 1];
}
private long byteOffset(int idx) {
return ((long) idx << shift) + base;
}
private int getBucket(int bit) {
//noinspection NumericOverflow
return ((bit - 1) >> 6) + 1;
}
public void clear() {
this.bitset = new long[getBucket(nbits) + 1];
}
public void clear(int bitIndex) {
int bucket = getBucket(bitIndex);
if (bucket >= bitset.length) {
throw new IndexOutOfBoundsException();
}
long v1, v2;
for (;;) {
v1 = bitset[bucket];
v2 = v1 & ~(1L << bitIndex);
if (unsafe.compareAndSwapLong(bitset, byteOffset(bucket), v1, v2)) {
return;
}
}
}
public void flip(int bitIndex) {
int bucket = getBucket(bitIndex);
if (bucket >= bitset.length) {
throw new IndexOutOfBoundsException();
}
long v1, v2;
for (;;) {
v1 = bitset[bucket];
v2 = v1 ^ (1L << bitIndex);
if (unsafe.compareAndSwapLong(bitset, byteOffset(bucket), v1, v2)) {
return;
}
}
}
public void set(int bitIndex) {
int bucket = getBucket(bitIndex);
if (bucket >= bitset.length) {
throw new IndexOutOfBoundsException();
}
long v1, v2;
for (;;) {
v1 = bitset[bucket];
v2 = v1 | (1L << bitIndex);
if (unsafe.compareAndSwapLong(bitset, byteOffset(bucket), v1, v2)) {
return;
}
}
}
public void set(int bitIndex, boolean value) {
if (value) {
set(bitIndex);
} else {
clear(bitIndex);
}
}
public boolean get(int bitIndex) {
int bucket = getBucket(bitIndex);
if (bucket >= bitset.length) {
throw new IndexOutOfBoundsException();
}
long v = unsafe.getLongVolatile(bitset, byteOffset(bucket));
return (v & (1L << bitIndex)) != 0;
}
}
|
package com.imotspot.dashboard;
import com.google.common.eventbus.Subscribe;
import com.imotspot.dagger.AppComponent;
import com.imotspot.dashboard.data.DataProvider;
import com.imotspot.dashboard.domain.User;
import com.imotspot.dashboard.event.DashboardEvent.BrowserResizeEvent;
import com.imotspot.dashboard.event.DashboardEvent.CloseOpenWindowsEvent;
import com.imotspot.dashboard.event.DashboardEvent.UserLoggedOutEvent;
import com.imotspot.dashboard.event.DashboardEvent.UserLoginRequestedEvent;
import com.imotspot.dashboard.event.DashboardEventBus;
import com.imotspot.dashboard.view.MainView;
import com.vaadin.annotations.PreserveOnRefresh;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.Title;
import com.vaadin.server.Page;
import com.vaadin.server.Page.BrowserWindowResizeEvent;
import com.vaadin.server.Page.BrowserWindowResizeListener;
import com.vaadin.server.Responsive;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinSession;
import com.vaadin.ui.UI;
import com.vaadin.ui.Window;
import com.vaadin.ui.themes.ValoTheme;
import javax.inject.Inject;
import java.util.Locale;
@PreserveOnRefresh
@Theme("dashboard")
//@Widgetset("com.vaadin.demo.dashboard.DashboardWidgetSet")
@Title("Imot Spot Dashboard")
@SuppressWarnings("serial")
public final class DashboardUI extends UI {
/*
* This field stores an access to the dummy backend layer. In real
* applications you most likely gain access to your beans trough lookup or
* injection; and not in the UI but somewhere closer to where they're
* actually accessed.
*/
private final DataProvider dataProvider;
private final DashboardEventBus dashboardEventbus;
public DashboardUI() {
this(AppComponent.daggerInjector().dashboardEventBus(), AppComponent.daggerInjector().dataProvider());
}
@Inject
public DashboardUI(DashboardEventBus dashboardEventbus, DataProvider dataProvider) {
this.dashboardEventbus = dashboardEventbus;
this.dataProvider = dataProvider;
}
@Override
protected void init(final VaadinRequest request) {
setLocale(Locale.US);
DashboardEventBus.register(this);
Responsive.makeResponsive(this);
addStyleName(ValoTheme.UI_WITH_MENU);
updateContent();
// Some views need to be aware of browser resize events so a
// BrowserResizeEvent gets fired to the event bus on every occasion.
Page.getCurrent().addBrowserWindowResizeListener(
new BrowserWindowResizeListener() {
@Override
public void browserWindowResized(
final BrowserWindowResizeEvent event) {
DashboardEventBus.post(new BrowserResizeEvent());
}
});
}
/**
* Updates the correct content for this UI based on the current user status.
* If the user is logged in with appropriate privileges, main view is shown.
* Otherwise login view is shown.
*/
private void updateContent() {
User user = (User) VaadinSession.getCurrent().getAttribute(
User.class.getName());
if (user == null) {
user = new User();
user.setFirstName("guest");
user.setLastName("");
user.setRole("guest");
VaadinSession.getCurrent().setAttribute(User.class.getName(), user);
}
setContent(new MainView());
removeStyleName("loginview");
getNavigator().navigateTo(getNavigator().getState());
// } else {
// setContent(new LoginView());
// addStyleName("loginview");
}
@Subscribe
public void userLoginRequested(final UserLoginRequestedEvent event) {
User user = getDataProvider().authenticate(event.getUserName(),
event.getPassword());
VaadinSession.getCurrent().setAttribute(User.class.getName(), user);
updateContent();
}
@Subscribe
public void userLoggedOut(final UserLoggedOutEvent event) {
// When the user logs out, current VaadinSession gets closed and the
// page gets reloaded on the login screen. Do notice the this doesn't
// invalidate the current HttpSession.
VaadinSession.getCurrent().close();
Page.getCurrent().reload();
}
@Subscribe
public void closeOpenWindows(final CloseOpenWindowsEvent event) {
for (Window window : getWindows()) {
window.close();
}
}
/**
* @return An instance for accessing the (dummy) services layer.
*/
public static DataProvider getDataProvider() {
return ((DashboardUI) getCurrent()).dataProvider;
}
public static DashboardEventBus getDashboardEventbus() {
return ((DashboardUI) getCurrent()).dashboardEventbus;
}
}
|
package com.intrbiz.balsa.scgi;
import java.io.InputStream;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import org.apache.log4j.Logger;
import com.intrbiz.balsa.parameter.ListParameter;
import com.intrbiz.balsa.parameter.Parameter;
import com.intrbiz.balsa.parameter.StringParameter;
import com.intrbiz.balsa.util.LengthLimitedSocketInputStream;
/**
* A SCGI request
*
* It pulls information out of the SCGI headers.
*
* It allows access to the input stream, but provides no processing of them
*
*/
public class SCGIRequest
{
private Logger logger = Logger.getLogger(SCGIRequest.class);
private int contentLength = 0;
private String contentType;
private String version;
private String serverSoftware;
private String serverName;
private String serverAddress;
private int serverPort;
private String serverProtocol;
private String remoteAddress;
private int remotePort;
private String requestMethod;
private String requestScheme;
private String requestUri;
private String pathInfo;
private String queryString;
private String scriptName;
private String scriptFileName;
private String documentRoot;
private Map<String, String> headers = new TreeMap<String, String>();
private Map<String, String> scgiVariables = new TreeMap<String, String>();
private Map<String, Parameter> parameters = new TreeMap<String, Parameter>();
private Map<String, String> cookies = new TreeMap<String, String>();
private InputStream input;
private LengthLimitedSocketInputStream bodyInput = null;
private Object body;
private long processingStart;
private long processingEnd;
public SCGIRequest()
{
super();
}
public void variable(String name, String value)
{
if (this.logger.isTraceEnabled()) this.logger.trace("SCGI Variable: " + name + " => " + value);
if (name.startsWith("HTTP"))
{
this.headers.put(name.substring(5), value);
}
else if ("CONTENT_LENGTH".equals(name))
{
this.contentLength = Integer.parseInt(value);
}
else if ("CONTENT_TYPE".equals(name))
{
this.contentType = value;
}
else if ("SCGI".equals(name))
{
this.version = value;
}
else if ("SERVER_SOFTWARE".equals(name))
{
this.serverSoftware = value;
}
else if ("SERVER_NAME".equals(name))
{
this.serverName = value;
}
else if ("SERVER_ADDR".equals(name))
{
this.serverAddress = value;
}
else if ("SERVER_PORT".equals(name))
{
this.serverPort = Integer.parseInt(value);
}
else if ("SERVER_PROTOCOL".equals(name))
{
this.serverProtocol = value;
}
else if ("REMOTE_ADDR".equals(name))
{
this.remoteAddress = value;
}
else if ("REMOTE_PORT".equals(name))
{
this.remotePort = Integer.parseInt(value);
}
else if ("REQUEST_METHOD".equals(name))
{
this.requestMethod = value;
}
else if ("REQUEST_SCHEME".equals(name))
{
this.requestScheme = value;
}
else if ("REQUEST_URI".equals(name))
{
this.requestUri = value;
}
else if ("PATH_INFO".equals(name))
{
this.pathInfo = value;
}
else if ("QUERY_STRING".equals(name))
{
this.queryString = value;
}
else if ("SCRIPT_NAME".equals(name))
{
this.scriptName = value;
}
else if ("SCRIPT_FILENAME".equals(name))
{
this.scriptFileName = value;
}
else if ("DOCUMENT_ROOT".equals(name))
{
this.documentRoot = value;
}
else
{
this.scgiVariables.put(name, value);
}
}
public void stream(InputStream input)
{
this.input = input;
}
public void activate()
{
}
public void deactivate()
{
// clear all state!
this.input = null;
this.bodyInput = null;
this.headers.clear();
this.scgiVariables.clear();
this.parameters.clear();
this.contentLength = 0;
this.contentType = null;
this.version = null;
this.serverSoftware = null;
this.serverName = null;
this.serverAddress = null;
this.serverPort = 0;
this.serverProtocol = null;
this.remoteAddress = null;
this.remotePort = 0;
this.requestMethod = null;
this.requestScheme = null;
this.requestUri = null;
this.pathInfo = null;
this.queryString = null;
this.scriptName = null;
this.scriptFileName = null;
this.documentRoot = null;
}
/*
* Accessors
*/
/**
* Get an input stream to read the request body
* @return
*/
public InputStream getInput()
{
if (this.bodyInput == null)
{
this.bodyInput = new LengthLimitedSocketInputStream(this.contentLength, this.input);
}
return this.bodyInput;
}
public int getContentLength()
{
return contentLength;
}
public String getContentType()
{
return contentType;
}
public String getVersion()
{
return version;
}
public String getServerSoftware()
{
return serverSoftware;
}
public String getServerName()
{
return serverName;
}
public String getServerAddress()
{
return serverAddress;
}
public int getServerPort()
{
return serverPort;
}
public String getServerProtocol()
{
return serverProtocol;
}
public String getRemoteAddress()
{
return remoteAddress;
}
public int getRemotePort()
{
return remotePort;
}
public String getRequestMethod()
{
return requestMethod;
}
public String getRequestScheme()
{
return requestScheme;
}
public String getRequestUri()
{
return requestUri;
}
public String getPathInfo()
{
return pathInfo;
}
public String getQueryString()
{
return queryString;
}
public String getScriptName()
{
return scriptName;
}
public String getScriptFileName()
{
return scriptFileName;
}
public String getDocumentRoot()
{
return documentRoot;
}
public Map<String, String> getHeaders()
{
return headers;
}
public String getHeader(String name)
{
return this.headers.get(cgifyHeaderName(name));
}
private String cgifyHeaderName(String name)
{
return name.toUpperCase().replace('-', '_');
}
public Set<String> getHeaderNames()
{
return this.headers.keySet();
}
public Map<String, String> getVariables()
{
return scgiVariables;
}
public String getVariable(String name)
{
return this.scgiVariables.get(name.toUpperCase());
}
public Set<String> getVariableNames()
{
return this.scgiVariables.keySet();
}
public Map<String, Parameter> getParameters()
{
return parameters;
}
public Parameter getParameter(String name)
{
return this.parameters.get(name);
}
public void addParameter(Parameter parameter)
{
this.parameters.put(parameter.getName(), parameter);
}
public Set<String> getParameterNames()
{
return this.parameters.keySet();
}
public Collection<Parameter> getParameterValues()
{
return this.parameters.values();
}
public boolean containsParameter(String name)
{
return this.parameters.containsKey(name);
}
public String cookie(String name)
{
return this.cookies.get(name);
}
public void cookie(String name, String value)
{
this.cookies.put(name, value);
}
public Object getBody()
{
return body;
}
public void setBody(Object body)
{
this.body = body;
}
public String dumpRequest()
{
StringBuilder sb = new StringBuilder();
sb.append(this.getRequestMethod()).append(" ").append(this.getPathInfo()).append("\r\n\r\n");
sb.append("CONTENT_LENGTH: ").append(this.contentLength).append("\r\n");
sb.append("CONTENT_TYPE: ").append(this.contentType).append("\r\n");
sb.append("SCGI: ").append(this.version).append("\r\n");
sb.append("SERVER_SOFTWARE: ").append(this.serverSoftware).append("\r\n");
sb.append("SERVER_NAME: ").append(this.serverName).append("\r\n");
sb.append("SERVER_ADDR: ").append(this.serverAddress).append("\r\n");
sb.append("SERVER_PORT: ").append(this.serverPort).append("\r\n");
sb.append("SERVER_PROTOCOL: ").append(this.serverProtocol).append("\r\n");
sb.append("REMOTE_ADDR: ").append(this.remoteAddress).append("\r\n");
sb.append("REMOTE_PORT: ").append(this.remotePort).append("\r\n");
sb.append("REQUEST_METHOD: ").append(this.requestMethod).append("\r\n");
sb.append("REQUEST_SCHEME: ").append(this.requestScheme).append("\r\n");
sb.append("REQUEST_URI: ").append(this.requestUri).append("\r\n");
sb.append("PATH_INFO: ").append(this.pathInfo).append("\r\n");
sb.append("QUERY_STRING: ").append(this.queryString).append("\r\n");
sb.append("SCRIPT_NAME: ").append(this.scriptName).append("\r\n");
sb.append("SCRIPT_FILENAME: ").append(this.scriptFileName).append("\r\n");
sb.append("DOCUMENT_ROOT: ").append(this.documentRoot).append("\r\n");
sb.append("\r\nVariables:\r\n");
for (Entry<String, String> var : this.getVariables().entrySet())
{
sb.append("\t").append(var.getKey()).append(" => ").append(var.getValue()).append("\r\n");
}
sb.append("\r\nHeaders:\r\n");
for (Entry<String, String> hd : this.getHeaders().entrySet())
{
sb.append("\t").append(hd.getKey()).append(" => ").append(hd.getValue()).append("\r\n");
}
sb.append("\r\nParameters:\r\n");
for (Parameter p : this.getParameterValues())
{
if (p instanceof StringParameter)
{
sb.append("\t").append(p.getName()).append(" => ").append(p.getStringValue()).append("\r\n");
}
else if (p instanceof ListParameter)
{
for (Parameter v : p.getListValue())
{
if (v instanceof StringParameter)
{
sb.append("\t").append(p.getName()).append(" => ").append(v.getStringValue()).append("\r\n");
}
}
}
}
return sb.toString();
}
// Timing
public final long getProcessingStart()
{
return processingStart;
}
public final void setProcessingStart(long processingStart)
{
this.processingStart = processingStart;
}
public final long getProcessingEnd()
{
return processingEnd;
}
public final void setProcessingEnd(long processingEnd)
{
this.processingEnd = processingEnd;
}
}
|
package com.jcabi.github.mock;
import com.jcabi.aspects.Immutable;
import com.jcabi.aspects.Loggable;
import com.jcabi.github.Coordinates;
import com.jcabi.github.Reference;
import com.jcabi.github.References;
import com.jcabi.github.Repo;
import com.jcabi.xml.XML;
import java.io.IOException;
import javax.validation.constraints.NotNull;
import lombok.EqualsAndHashCode;
import org.xembly.Directives;
/**
* Mock of Github References.
* @author Mihai Andronache (amihaiemil@gmail.com)
* @version $Id$
* @checkstyle MultipleStringLiterals (500 lines)
*/
@Immutable
@Loggable(Loggable.DEBUG)
@EqualsAndHashCode(of = { "storage", "self", "coords" })
final class MkReferences implements References {
/**
* Storage.
*/
private final transient MkStorage storage;
/**
* Login of the user logged in.
*/
private final transient String self;
/**
* Repo name.
*/
private final transient Coordinates coords;
/**
* Public constructor.
* @param stg Storage.
* @param login Login name.
* @param rep Repo coordinates.
* @throws IOException - If something goes wrong.
*/
MkReferences(
@NotNull(message = "stg can't be NULL") final MkStorage stg,
@NotNull(message = "login can't be NULL") final String login,
@NotNull(message = "rep can't be NULL") final Coordinates rep
) throws IOException {
this.storage = stg;
this.self = login;
this.coords = rep;
this.storage.apply(
new Directives().xpath(
String.format(
"/github/repos/repo[@coords='%s']/git",
this.coords
)
).addIf("refs")
);
}
@Override
@NotNull(message = "Repository can't be NULL")
public Repo repo() {
return new MkRepo(this.storage, this.self, this.coords);
}
@Override
@NotNull(message = "created ref can't be NULL")
public Reference create(
@NotNull(message = "ref can't be NULL") final String ref,
@NotNull(message = "sha can't be NULL") final String sha
) throws IOException {
this.storage.apply(
new Directives().xpath(this.xpath()).add("reference")
.add("ref").set(ref).up()
.add("sha").set(sha).up()
);
return this.get(ref);
}
@Override
@NotNull(message = "Reference is never NULL")
public Reference get(
@NotNull(message = "identifier can't be NULL") final String identifier
) {
return new MkReference(
this.storage, this.self, this.coords, identifier
);
}
@Override
@NotNull(message = "Iterable of references can't be NULL")
public Iterable<Reference> iterate() {
return new MkIterable<Reference>(
this.storage,
String.format("%s/reference", this.xpath()),
new MkIterable.Mapping<Reference>() {
@Override
public Reference map(final XML xml) {
return MkReferences.this.get(
xml.xpath("ref/text()").get(0)
);
}
}
);
}
@Override
@NotNull(message = "Iterable of references can't be NULL")
public Iterable<Reference> iterate(
@NotNull(message = "subnamespace can't be NULL")
final String subnamespace
) {
return new MkIterable<Reference>(
this.storage,
String.format(
"%s/reference/ref[starts-with(., 'refs/%s')]", this.xpath(),
subnamespace
),
new MkIterable.Mapping<Reference>() {
@Override
public Reference map(final XML xml) {
return MkReferences.this.get(
xml.xpath("text()").get(0)
);
}
}
);
}
@Override
@NotNull(message = "Iterable of references is never NULL")
public Iterable<Reference> tags() {
return this.iterate("tags");
}
@Override
@NotNull(message = "Iterable of references is never NULL")
public Iterable<Reference> heads() {
return this.iterate("heads");
}
@Override
public void remove(
@NotNull(message = "identifier shouldn't be NULL")
final String identifier
) throws IOException {
this.storage.apply(
new Directives().xpath(
String.format(
"%s/reference[ref='%s']", this.xpath(), identifier
)
).remove()
);
}
/**
* XPath of this element in XML tree.
* @return XPath
*/
@NotNull(message = "Xpath is never NULL")
private String xpath() {
return String.format(
"/github/repos/repo[@coords='%s']/git/refs",
this.coords
);
}
}
|
package com.kapre.irobot.shell;
import java.io.Console;
import jssc.SerialPortList;
import com.google.common.base.Optional;
import com.google.common.collect.Lists;
import com.kapre.irobot.Command;
import com.kapre.irobot.Connection;
import com.kapre.irobot.IRobotCreate;
import com.kapre.irobot.SensorData;
import com.kapre.irobot.enums.OpCode;
import com.kapre.irobot.impl.BaudCommand;
import com.kapre.irobot.impl.DemoCommand;
import com.kapre.irobot.impl.DigitalOutputCommand;
import com.kapre.irobot.impl.DriveCommand;
import com.kapre.irobot.impl.LedCommand;
import com.kapre.irobot.impl.LowSideDriver;
import com.kapre.irobot.impl.MoveToCommand;
import com.kapre.irobot.impl.OpCommand;
import com.kapre.irobot.impl.SensorCommand;
import com.kapre.irobot.impl.SerialPortConnection;
import com.kapre.irobot.impl.TurnCommand;
import com.kapre.irobot.impl.WaitCommand;
public class CreateShell {
private static final int DEFAULT_TIMEOUT = 10000;
public static void main(String[] args) {
Console console = System.console();
Optional<String> serialPort = getSerialPort(console);
/* Bail out if no serial port is present */
if (!serialPort.isPresent()) {
console.printf("No serial port detected.\n");
return;
}
Connection connection = new SerialPortConnection(serialPort.get(), DEFAULT_TIMEOUT);
IRobotCreate executor = new IRobotCreate(connection);
CommandInterpreter<Command> commandInterpreter = buildInterpreter();
try {
/* open connection to irobot */
executor.init();
while (true) {
/* read command */
String cmd = console.readLine("> ");
/* quit if given quit command */
if (cmd.trim().equalsIgnoreCase("quit")) {
break;
}
try {
/* Interpret command given and build Command object */
Optional<? extends Command> result = commandInterpreter
.interpret(cmd);
if (!result.isPresent()) {
console.format("'%s' is not a valid command\n", cmd);
continue;
}
/* execute command object */
Command command = result.get();
Optional<SensorData> response = executor.execute(command);
if(response.isPresent()) {
console.format("Command successful. Response: %s\n", response.get().toString());
} else {
console.format("Command successful.\n");
}
} catch (InterpreterException e) {
printException(console, e);
}
}
executor.shutdown();
} catch (RuntimeException e) {
printException(console, e);
}
}
private static void printException(Console console, RuntimeException e) {
console.format("Exception : \n");
e.printStackTrace(console.writer());
console.format("\n");
}
/* build our command interpreter */
public static CommandInterpreter<Command> buildInterpreter() {
CommandInterpreter<Command> interpreter = new CommandInterpreter<Command>();
interpreter.add("start", null, OpCommand.class,
Lists.newArrayList(OpCode.START));
interpreter.add("safe", null, OpCommand.class,
Lists.newArrayList(OpCode.SAFE));
interpreter.add("full", null, OpCommand.class,
Lists.newArrayList(OpCode.FULL));
interpreter.add("baud", "<i>", BaudCommand.class);
interpreter.add("demo", "<i>", DemoCommand.class);
interpreter.add("drive", "<s> <s>", DriveCommand.class,
Lists.newArrayList(OpCode.DRIVE));
interpreter.add("drivedirect", "<s> <s>", DriveCommand.class,
Lists.newArrayList(OpCode.DRIVE_DIRECT));
interpreter.add("led", "<f> <f> <i> <i>", LedCommand.class);
interpreter.add("dout", "<f> <f> <f>", DigitalOutputCommand.class);
interpreter.add("lowside", "<f> <f> <f>", LowSideDriver.class);
interpreter.add("lowsidepwm", "<i> <i> <i>", LowSideDriver.class);
interpreter.add("sendir", "<i>", OpCommand.class,
Lists.newArrayList(OpCode.SEND_IR));
interpreter.add("waittime", "<i>", OpCommand.class,
Lists.newArrayList(OpCode.WAIT_TIME));
interpreter.add("waitdistance", "<s>", WaitCommand.class,
Lists.newArrayList(OpCode.WAIT_DISTANCE));
interpreter.add("waitangle", "<s>", WaitCommand.class,
Lists.newArrayList(OpCode.WAIT_ANGLE));
interpreter.add("moveto", "<s> <s>", MoveToCommand.class);
interpreter.add("turn", "<s> <s>", TurnCommand.class);
interpreter.add("sensor", "<i>", SensorCommand.class);
return interpreter;
}
/* get list of serial ports and prompt user for selection */
public static Optional<String> getSerialPort(Console console) {
String[] portNames = SerialPortList.getPortNames();
if (portNames.length > 0) {
for (int i = 0; i < portNames.length; i++) {
console.format("[Port No] %d ==> %s\n", i, portNames[i]);
}
while (true) {
try {
int choice = Integer.valueOf(console.readLine("Enter Port No:"));
if (choice >= 0 && choice < portNames.length) {
return Optional.of(portNames[choice]);
}
} catch (NumberFormatException e) {
}
}
}
return Optional.absent();
}
}
|
package com.laytonsmith.core.functions;
import com.laytonsmith.PureUtilities.Common.StringUtils;
import com.laytonsmith.PureUtilities.RunnableQueue;
import com.laytonsmith.PureUtilities.Version;
import com.laytonsmith.abstraction.StaticLayer;
import com.laytonsmith.annotations.api;
import com.laytonsmith.core.CHLog;
import com.laytonsmith.core.CHVersion;
import com.laytonsmith.core.ObjectGenerator;
import com.laytonsmith.core.Optimizable;
import com.laytonsmith.core.ParseTree;
import com.laytonsmith.core.Static;
import com.laytonsmith.core.constructs.CArray;
import com.laytonsmith.core.constructs.CBoolean;
import com.laytonsmith.core.constructs.CByteArray;
import com.laytonsmith.core.constructs.CClosure;
import com.laytonsmith.core.constructs.CDouble;
import com.laytonsmith.core.constructs.CFunction;
import com.laytonsmith.core.constructs.CInt;
import com.laytonsmith.core.constructs.CNull;
import com.laytonsmith.core.constructs.CString;
import com.laytonsmith.core.constructs.CVoid;
import com.laytonsmith.core.constructs.Construct;
import com.laytonsmith.core.constructs.Target;
import com.laytonsmith.core.environments.Environment;
import com.laytonsmith.core.environments.GlobalEnv;
import com.laytonsmith.core.exceptions.ConfigCompileException;
import com.laytonsmith.core.exceptions.ConfigRuntimeException;
import com.laytonsmith.core.functions.Exceptions.ExceptionType;
import com.laytonsmith.database.Profiles;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ParameterMetaData;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class SQL {
public static String docs() {
return "This class of functions provides methods for accessing various SQL servers.";
}
@api
public static class query extends AbstractFunction implements Optimizable{
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.SQLException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
try {
Profiles.Profile profile;
if (args[0] instanceof CArray) {
Map<String, String> data = new HashMap<String, String>();
for (String key : ((CArray) args[0]).keySet()) {
data.put(key, ((CArray) args[0]).get(key).val());
}
profile = Profiles.getProfile(data);
} else {
Profiles profiles = environment.getEnv(GlobalEnv.class).getSQLProfiles();
profile = profiles.getProfileById(args[0].val());
}
String query = args[1].val();
Construct[] params = new Construct[args.length - 2];
for (int i = 2; i < args.length; i++) {
int index = i - 2;
params[index] = args[i];
}
//Parameters are now all parsed into java objects.
Connection conn = DriverManager.getConnection(profile.getConnectionString());
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(query, Statement.RETURN_GENERATED_KEYS);
for (int i = 0; i < params.length; i++) {
int type = ps.getParameterMetaData().getParameterType(i + 1);
if (params[i] == null) {
if (ps.getParameterMetaData().isNullable(i + 1) == ParameterMetaData.parameterNoNulls) {
throw new ConfigRuntimeException("Parameter " + (i + 1) + " cannot be set to null. Check your parameters and try again.", ExceptionType.SQLException, t);
} else {
ps.setNull(i + 1, type);
continue;
}
}
try {
if (params[i] instanceof CInt) {
ps.setLong(i + 1, Static.getInt(params[i], t));
} else if (params[i] instanceof CDouble) {
ps.setDouble(i + 1, (Double) Static.getDouble(params[i], t));
} else if (params[i] instanceof CString) {
ps.setString(i + 1, (String) params[i].val());
} else if (params[i] instanceof CByteArray) {
ps.setBytes(i + 1, ((CByteArray) params[i]).asByteArrayCopy());
} else if (params[i] instanceof CBoolean) {
ps.setBoolean(i + 1, Static.getBoolean(params[i]));
}else{
throw new ConfigRuntimeException("The type " + params[i].getClass().getSimpleName()
+ " of parameter " + (i + 1) + " is not supported."
, ExceptionType.CastException, t);
}
} catch (ClassCastException ex) {
throw new ConfigRuntimeException("Could not cast parameter " + (i + 1) + " to "
+ ps.getParameterMetaData().getParameterTypeName(i + 1) + " from "
+ params[i].getClass().getSimpleName() + "."
, ExceptionType.CastException, t, ex);
}
}
boolean isResultSet = ps.execute();
if (isResultSet) {
//Result set
CArray ret = new CArray(t);
ResultSetMetaData md = ps.getMetaData();
ResultSet rs = ps.getResultSet();
while (rs.next()) {
CArray row = new CArray(t);
for (int i = 1; i <= md.getColumnCount(); i++) {
Construct value;
int columnType = md.getColumnType(i);
if (columnType == Types.INTEGER
|| columnType == Types.TINYINT
|| columnType == Types.SMALLINT
|| columnType == Types.BIGINT) {
value = new CInt(rs.getLong(i), t);
} else if (columnType == Types.FLOAT
|| columnType == Types.DOUBLE
|| columnType == Types.REAL
|| columnType == Types.DECIMAL
|| columnType == Types.NUMERIC) {
value = new CDouble(rs.getDouble(i), t);
} else if (columnType == Types.VARCHAR
|| columnType == Types.CHAR
|| columnType == Types.LONGVARCHAR) {
value = new CString(rs.getString(i), t);
} else if (columnType == Types.BLOB
|| columnType == Types.BINARY
|| columnType == Types.VARBINARY
|| columnType == Types.LONGVARBINARY) {
value = CByteArray.wrap(rs.getBytes(i), t);
} else if (columnType == Types.DATE
|| columnType == Types.TIME
|| columnType == Types.TIMESTAMP) {
if (md.getColumnTypeName(i).equals("YEAR")){
value = new CInt(rs.getLong(i), t);
} else {
value = new CInt(rs.getTimestamp(i).getTime(), t);
}
} else if (columnType == Types.BOOLEAN
|| columnType == Types.BIT) {
value = new CBoolean(rs.getBoolean(i), t);
} else {
throw new ConfigRuntimeException("SQL returned a unhandled column type "
+ md.getColumnTypeName(i) + " for column " + md.getColumnName(i) + "."
, ExceptionType.CastException, t);
}
row.set(md.getColumnName(i), value, t);
}
ret.push(row);
}
return ret;
} else {
ResultSet rs = ps.getGeneratedKeys();
if (rs.next()) {
//This was an insert or something that returned generated keys. So we return
//that here.
return new CInt(rs.getInt(1), t);
}
//Update count. Just return null.
return new CNull(t);
}
} finally {
if (ps != null) {
ps.close();
}
if (conn != null) {
conn.close();
}
}
} catch (Profiles.InvalidProfileException ex) {
throw new ConfigRuntimeException(ex.getMessage(), ExceptionType.SQLException, t, ex);
} catch (SQLException ex) {
throw new ConfigRuntimeException(ex.getMessage(), ExceptionType.SQLException, t, ex);
}
}
@Override
public ParseTree optimizeDynamic(Target t, List<ParseTree> children) throws ConfigCompileException, ConfigRuntimeException {
//We can check 2 things here, one, that the statement isn't dynamic, and if not, then
//2, that the parameter count matches the ? count. No checks can be done for typing,
//without making a connection to the db though, so we won't do that here.
Construct queryData = children.get(1).getData();
if(queryData instanceof CFunction){
//If it's a concat or sconcat, warn them that this is bad
if("sconcat".equals(queryData.val()) || "concat".equals(queryData.val())){
CHLog.GetLogger().w(CHLog.Tags.COMPILER, "Use of concatenated query detected! This"
+ " is very bad practice, and could lead to SQL injection vulnerabilities"
+ " in your code. It is highly recommended that you use prepared queries,"
+ " which ensure that your parameters are properly escaped.", t);
}
} else if(queryData instanceof CString){
//It's a hard coded query, so we can double check parameter lengths
int count = 0;
for(char c : queryData.val().toCharArray()){
if(c == '?'){
count++;
}
}
//-2 accounts for the profile data and query
if(children.size() - 2 != count){
throw new ConfigCompileException(
StringUtils.PluralTemplateHelper(count, "%d parameter token was", "%d parameter tokens were")
+ " found in the query, but "
+ StringUtils.PluralTemplateHelper(children.size() - 2, "%d parameter was", "%d parameters were")
+ " provided to query().", t);
}
}
return null;
}
@Override
public String getName() {
return "query";
}
@Override
public Integer[] numArgs() {
return new Integer[]{Integer.MAX_VALUE};
}
@Override
public String docs() {
return getBundledDocs();
}
@Override
public Version since() {
return CHVersion.V3_3_1;
}
@Override
public Set<OptimizationOption> optimizationOptions() {
return EnumSet.of(OptimizationOption.OPTIMIZE_DYNAMIC);
}
}
@api
public static class query_async extends AbstractFunction {
RunnableQueue queue = null;
boolean started = false;
private synchronized void startup(){
if(queue == null){
queue = new RunnableQueue("MethodScript-queryAsync");
}
if(!started){
queue.invokeLater(null, new Runnable() {
@Override
public void run() {
//This warms up the queue. Apparently.
}
});
StaticLayer.GetConvertor().addShutdownHook(new Runnable() {
@Override
public void run() {
queue.shutdown();
queue = null;
started = false;
}
});
started = true;
}
}
@Override
public ExceptionType[] thrown() {
return new ExceptionType[]{ExceptionType.CastException};
}
@Override
public boolean isRestricted() {
return true;
}
@Override
public Boolean runAsync() {
return null;
}
@Override
public Construct exec(final Target t, final Environment environment, Construct... args) throws ConfigRuntimeException {
startup();
Construct arg = args[args.length - 1];
if(!(arg instanceof CClosure)){
throw new ConfigRuntimeException("The last argument to " + getName() + " must be a closure.", ExceptionType.CastException, t);
}
final CClosure closure = ((CClosure)arg);
final Construct[] newArgs = new Construct[args.length - 1];
//Make a new array minus the closure
System.arraycopy(args, 0, newArgs, 0, newArgs.length);
queue.invokeLater(environment.getEnv(GlobalEnv.class).GetDaemonManager(), new Runnable() {
@Override
public void run() {
Construct returnValue = new CNull();
Construct exception = new CNull();
try{
returnValue = new query().exec(t, environment, newArgs);
} catch(ConfigRuntimeException ex){
exception = ObjectGenerator.GetGenerator().exception(ex, t);
}
final Construct cret = returnValue;
final Construct cex = exception;
StaticLayer.GetConvertor().runOnMainThreadLater(environment.getEnv(GlobalEnv.class).GetDaemonManager(), new Runnable() {
@Override
public void run() {
closure.execute(new Construct[]{cret, cex});
}
});
}
});
return new CVoid(t);
}
@Override
public String getName() {
return "query_async";
}
@Override
public Integer[] numArgs() {
return new Integer[]{Integer.MAX_VALUE};
}
@Override
public String docs() {
return "void {profile, query, [params...], callback} Asynchronously makes a query to an SQL server."
+ " The profile, query, and params arguments work the same as {{function|query}}, so see"
+ " the documentation of that function for details about those parameters."
+ " The callback should have the following signature: closure(@contents, @exception){ <code> }."
+ " @contents will contain the return value that query would normally return. If @exception is not"
+ " null, then an exception occurred during the query, and that exception will be passed in. If"
+ " @exception is null, then no error occured, though @contents may still be null if query() would"
+ " otherwise have returned null.";
}
@Override
public Version since() {
return CHVersion.V3_3_1;
}
}
}
|
package com.qihoo.fireline;
import hudson.Launcher;
import hudson.EnvVars;
import hudson.Extension;
import hudson.FilePath;
import hudson.model.AbstractBuild;
import hudson.model.AbstractProject;
import hudson.model.Computer;
import hudson.model.JDK;
import hudson.model.Run;
import hudson.model.TaskListener;
import hudson.tasks.Builder;
import hudson.tasks.BuildStepDescriptor;
import jenkins.model.Jenkins;
import jenkins.tasks.SimpleBuildStep;
import net.sf.json.JSONObject;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.StaplerRequest;
import com.qihoo.utils.BuilderUtils;
import com.qihoo.utils.FileUtils;
import javax.annotation.CheckForNull;
import javax.annotation.Nullable;
import java.io.File;
import java.io.IOException;
/**
* Sample {@link Builder}.
*
* @author weihao
*/
public class FireLineBuilder extends Builder implements SimpleBuildStep {
private final FireLineTarget fireLineTarget;
private String jdk;
// private String output;
private static String jarFile = "/lib/firelineJar.jar";
public final static String platform = System.getProperty("os.name");
// Fields in config.jelly must match the parameter names in the
// "DataBoundConstructor"
@DataBoundConstructor
public FireLineBuilder(@CheckForNull FireLineTarget fireLineTarget) {
// this.fireLineTargets=fireLineTargets != null ? new
// ArrayList<FireLineTarget>(fireLineTargets) : new ArrayList<FireLineTarget>();
this.fireLineTarget = fireLineTarget;
}
@CheckForNull
public FireLineTarget getFireLineTarget() {
return this.fireLineTarget;
}
@Override
public DescriptorImpl getDescriptor() {
return (DescriptorImpl) super.getDescriptor();
}
@Override
public void perform(Run<?, ?> build, FilePath workspace, Launcher launcher, TaskListener listener)
throws InterruptedException, IOException {
String jvmString = "-Xms1g -Xmx1g -XX:MaxPermSize=512m";
EnvVars env = BuilderUtils.getEnvAndBuildVars(build, listener);
String projectPath = workspace.getRemote();
String reportFileNameTmp=fireLineTarget.getReportFileName().substring(0,fireLineTarget.getReportFileName().lastIndexOf("."));
jdk = fireLineTarget.getJdk();
String jarPath = null;
//add actions
// build.addAction(new FireLineScanCodeAction());
// Set JDK version
computeJdkToUse(build, workspace, listener, env);
//get path of fireline.jar
jarPath = getFireLineJar(listener);
// check params
if (!FileUtils.existFile(projectPath))
listener.getLogger().println("The path of project " + projectPath + "can't be found.");
checkReportPath(fireLineTarget.getReportPath());
String cmd = "java " + jvmString + " -jar " + jarPath + " -s=" + projectPath + " -r="
+ fireLineTarget.getReportPath() + " reportFileName=" + reportFileNameTmp;
if (fireLineTarget.getConfiguration() != null) {
File conf = new File(fireLineTarget.getConfiguration());
if (conf.exists() && !conf.isDirectory())
cmd = cmd + " config=" + fireLineTarget.getConfiguration();
}
if (!fireLineTarget.getNotScan()) {
// debug/
// if (checkFireLineJdk(getProject(build).getJDK())) {
if (new File(jarPath).exists()) {
// execute fireline
listener.getLogger().println("FireLine start scanning...");
exeCmd(cmd, listener);
listener.getLogger().println("FireLine report path: " + fireLineTarget.getReportPath());
} else {
listener.getLogger().println("fireline.jar does not exist!!");
}
}
}
private void exeCmd(String commandStr, TaskListener listener) {
Process p = null;
try {
Runtime rt = Runtime.getRuntime();
// listener.getLogger().println(commandStr);
p = rt.exec(commandStr);
listener.getLogger().println("CommandLine output:");
StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(), "ERROR", listener);
StreamGobbler outputGobbler = new StreamGobbler(p.getInputStream(), "INFO", listener);
errorGobbler.start();
outputGobbler.start();
p.waitFor();
} catch (RuntimeException e) {
throw (e);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (p != null) {
p.destroy();
}
}
}
private String getFireLineJar(TaskListener listener) {
String oldPath = null;
String newPath = null;
if (platform.contains("Linux")) {
oldPath = FireLineBuilder.class.getResource(jarFile).getFile();
int index1 = oldPath.indexOf("file:");
int index2 = oldPath.indexOf("fireline.jar");
newPath = oldPath.substring(index1 + 5, index2) + "firelineJar.jar";
} else {
oldPath = new File(FireLineBuilder.class.getResource(jarFile).getFile()).getAbsolutePath();
int index1 = oldPath.indexOf("file:");
int index2 = oldPath.indexOf("fireline.jar");
newPath = oldPath.substring(index1 + 6, index2) + "firelineJar.jar";
}
try {
JarCopy.copyJarResource(jarFile, newPath);
} catch (Exception e) {
// TODO catch
e.printStackTrace();
}
return newPath;
}
private void checkReportPath(String path) {
if (path != null && path.length() > 0) {
File filePath = new File(path);
if (filePath.exists() && filePath.isDirectory()) {
} else {
try {
filePath.mkdirs();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
public static String getMemUsage() {
long free = java.lang.Runtime.getRuntime().freeMemory();
long total = java.lang.Runtime.getRuntime().totalMemory();
StringBuffer buf = new StringBuffer();
buf.append("[Mem: used ").append((total - free) >> 20).append("M free ").append(free >> 20).append("M total ")
.append(total >> 20).append("M]");
return buf.toString();
}
private static AbstractProject<?, ?> getProject(Run<?, ?> run) {
AbstractProject<?, ?> project = null;
if (run instanceof AbstractBuild) {
AbstractBuild<?, ?> build = (AbstractBuild<?, ?>) run;
project = build.getProject();
}
return project;
}
private void computeJdkToUse(Run<?, ?> build, FilePath workspace, TaskListener listener, EnvVars env)
throws IOException, InterruptedException {
JDK jdkToUse = getJdkToUse(getProject(build));
if (jdkToUse != null) {
Computer computer = workspace.toComputer();
// just in case we are not in a build
if (computer != null) {
jdkToUse = jdkToUse.forNode(computer.getNode(), listener)==null?jdkToUse:jdkToUse.forNode(computer.getNode(), listener);
}
jdkToUse.buildEnvVars(env);
}
}
/**
* @return JDK to be used with this project.
*/
private JDK getJdkToUse(@Nullable AbstractProject<?, ?> project) {
JDK jdkToUse = getJdkFromJenkins();
if (jdkToUse == null && project != null) {
jdkToUse = project.getJDK();
}
return jdkToUse;
}
/**
* Gets the JDK that this builder is configured with, or null.
*/
@CheckForNull
public JDK getJdkFromJenkins() {
return Jenkins.getInstance().getJDK(jdk)==null? null:Jenkins.getInstance().getJDK(jdk);
}
public boolean checkFireLineJdk(JDK jdkToUse) {
String jdkPath=jdkToUse.getHome();
return jdk != null && (jdkPath.contains("1.8") || jdkPath.contains("1.7"));
}
@Extension
public static class DescriptorImpl extends BuildStepDescriptor<Builder> {
@Override
public boolean isApplicable(Class<? extends AbstractProject> aClass) {
return true;
}
@Override
public String getDisplayName() {
return "Execute FireLine";
}
@Override
public boolean configure(StaplerRequest req, JSONObject formData) throws FormException {
save();
return super.configure(req, formData);
}
}
}
|
package com.seifernet.wissen.util;
import java.util.Random;
public class Markzwei {
public static String testString = "# Markzvei: a #Markdown alternative by @seiferson\n" +
"\n" +
"Markzvei is a markup language that translates to HTML using specific rules which\n" +
"differ from markdown by adding strict rules, you can follow this [link](http://link.com)\n" +
"\n" +
"There are multiple elements that can be used such as:\n" +
" + Lists\n" +
" * Emphasis elements\n" +
" - Other stuff like blockquote,\n" +
" links and images\n" +
"\n" +
"## Other important stuff\n" +
"\n" +
"This documents can also contain images  and @user mentions\n" +
"and #king search tags\n" +
"\n" +
"```\n" +
"#Code blocks can be placed within backticks\n" +
"print('something')\n" +
"```\n" +
"\n" +
"Reasons to use markzvei:\n" +
" 1. Rules are well defined\n" +
" 2. no\n" +
" lazy\n" +
" definitions\n" +
"\n" +
" * * *\n" +
"\n" +
"> One day I will finish this project\n" +
"> Seiferson 2017\n" +
"\n" +
"Last but not least\n" +
"=====================================\n" +
"\n" +
"This is a last comment to close this document";
public static void fromHTMLtoMarkzwei(String text){
}
}
|
package com.xpn.xwiki.web;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
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.Properties;
import java.util.ResourceBundle;
import java.util.Set;
import org.apache.log4j.Logger;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
/**
* Internationalization service based on key/property values. The key is the id of the message being
* looked for and the returned value is the message in the language requested. There are 3 sources
* where properties are looked for (in the specified order):
* <ol>
* <li>If there's a "documentBundles" property in the XWiki Preferences page then the XWiki
* documents listed there (separated by commas) are considered the source for properties</li>
* <li>If there's a "xwiki.documentBundles" property in the XWiki configuration file (xwiki.cfg)
* then the XWiki documents listed there (separated by commas) are considered for source for
* properties</li>
* <li>The Resource Bundle passed in the constructor</li>
* </ol>
* If the property is not found in any of these 3 sources then the key is returned in place of the
* value. In addition the property values are cached for better performance but if one of the XWiki
* documents containing the properties is modified, its content is cached again next time a key is
* asked.
*
* @version $Id: $
*/
public class XWikiMessageTool
{
/**
* Log4J logger object to log messages in this class.
*/
private static final Logger LOG = Logger.getLogger(XWikiMessageTool.class);
/**
* Property name used to defined internationalization document bundles in either XWikiProperties
* ("documentBundles") or in the xwiki.cfg configuration file ("xwiki.documentBundles").
*/
private static final String KEY = "documentBundles";
/**
*
The encoding used for storing unicode characters as bytes.
*/
private static final String BYTE_ENCODING = "UTF-8";
/**
* The default Resource Bundle to fall back to if no document bundle is found when trying to get
* a key.
*/
private ResourceBundle bundle;
/**
* The {@link com.xpn.xwiki.XWikiContext} object, used to get access to XWiki primitives for
* loading documents.
*/
private XWikiContext context;
/**
* Cache properties loaded from the document bundles for maximum efficiency. The map is of type
* (Long, Properties) where Long is the XWiki document ids.
*/
private Map propsCache = new HashMap();
/**
* Cache for saving the last modified dates of document bundles that have been loaded. This is
* used so that we can reload them if they've been modified since last time they were cached.
* The map is of type (Long, Date) where Long is the XWiki document ids.
*/
private Map previousDates = new HashMap();
/**
* List of document bundles that have been modified since the last time they were cached. The
* Set containers Long objects which are the XWiki document ids. TODO: This instance variable
* should be removed as it's used internally and its state shouldn't encompass several calls to
* get().
*/
private Set docsToRefresh = new HashSet();
/**
* @param bundle the default Resource Bundle to fall back to if no document bundle is found when
* trying to get a key
* @param context the {@link com.xpn.xwiki.XWikiContext} object, used to get access to XWiki
* primitives for loading documents
*/
public XWikiMessageTool(ResourceBundle bundle, XWikiContext context)
{
this.bundle = bundle;
this.context = context;
}
/**
* @param key the key identifying the message to look for
* @return the message in the defined language. The message should be a simple string without
* any parameters. If you need to pass parameters see
* {@link #get(String, java.util.List)}
* @see com.xpn.xwiki.web.XWikiMessageTool for more details on the algorithm used to find the
* message
*/
public String get(String key)
{
String translation = getTranslation(key);
if (translation == null) {
try {
translation = this.bundle.getString(key);
} catch (Exception e) {
translation = key;
}
}
return translation;
}
/**
* Find a translation and then replace any parameters found in the translation by the passed
* params parameters. The format is the one used by {@link java.text.MessageFormat}.
* <p>
* Note: The reason we're using a List instead of an Object array is because we haven't found
* how to easily create an Array in Velocity whereas an Array is easily created. For example:
* <code>$msg.get("key", ["1", "2", "3"])</code>.
* </p>
*
* @param key the key of the string to find
* @param params the list of parameters to use for replacing "{N}" elements in the string. See
* {@link java.text.MessageFormat} for the full syntax
* @return the translated string with parameters resolved
*/
public String get(String key, List params)
{
String translation = get(key);
if (params != null) {
translation = MessageFormat.format(translation, params.toArray());
}
return translation;
}
/**
* @return the list of internationalisation document bundle names as a list of XWiki page names
* ("Space.Document") or an empty list if no such documents have been found
* @see com.xpn.xwiki.web.XWikiMessageTool for more details on the algorithm used to find the
* document bundles
*/
protected List getDocumentBundleNames()
{
List docNamesList;
String docNames = this.context.getWiki().getXWikiPreference(KEY, this.context);
if (docNames == null || "".equals(docNames)) {
docNames = this.context.getWiki().Param("xwiki." + KEY);
}
if (docNames == null) {
docNamesList = new ArrayList();
} else {
docNamesList = Arrays.asList(docNames.split(","));
}
return docNamesList;
}
/**
* @return the internationalization document bundles (a list of {@XWikiDocument})
* @see com.xpn.xwiki.web.XWikiMessageTool for more details on the algorithm used to find the
* document bundles
*/
protected List getDocumentBundles()
{
List result = new ArrayList();
Iterator docNames = getDocumentBundleNames().iterator();
while (docNames.hasNext()) {
String docName = ((String) docNames.next()).trim();
XWikiDocument docBundle = getDocumentBundle(docName);
if (docBundle != null) {
if (!docBundle.isNew()) {
// Checks for a name update
Long docId = new Long(docBundle.getId());
Date docDate = docBundle.getDate();
// Check for a doc modification
if (!docDate.equals(this.previousDates.get(docId))) {
this.docsToRefresh.add(docId);
this.previousDates.put(docId, docDate);
}
result.add(docBundle);
} else {
// The document listed as a document bundle doesn't exist. Do nothing
// and log.
LOG.warn("The document [" + docBundle.getFullName() + "] is listed "
+ "as an internationalization document bundle but it does not "
+ "exist.");
}
}
}
return result;
}
/**
* @param documentName the document's name (eg Space.Document)
* @return the document object corresponding to the passed document's name. A translated version
* of the document for the current Locale is looked for.
*/
private XWikiDocument getDocumentBundle(String documentName)
{
XWikiDocument docBundle;
if (documentName.length() == 0) {
docBundle = null;
} else {
try {
// First, looks for a document suffixed by the language
docBundle = this.context.getWiki().getDocument(documentName, this.context);
docBundle = docBundle.getTranslatedDocument(this.context);
} catch (XWikiException e) {
// Error while loading the document.
// TODO: A runtime exception should be thrown that will bubble up till the
// topmost level. For now simply log the error
LOG.error("Failed to load internationalization document bundle [" + documentName
+ "].", e);
docBundle = null;
}
}
return docBundle;
}
/**
* @param documentName the Resource bundle's name (eg Space.Document)
* @param context the {@link com.xpn.xwiki.XWikiContext} object, used to get access to XWiki
* primitives for loading documents
* @return the properties object corresponding to the passed Resource Bundle. A translated
* version of the document for the current Locale is looked for.
*/
public Properties getDocumentBundleProperties(String documentName, XWikiContext context)
{
Properties props = null;
try {
XWikiDocument docBundle = context.getWiki().getDocument(documentName, context);
if (context.getWiki().getRightService().hasAccessLevel("view", context.getUser(),
documentName, context) && !docBundle.isNew())
{
props = getDocumentBundleProperties(docBundle);
}
} catch (XWikiException e) {
// Cannot do anything
}
return props;
}
/**
* @param docBundle the documentwho contains the bundle
* @return the properties object corresponding to the docBundle. A translated version
* of the document for the current Locale is looked for.
*/
private Properties getDocumentBundleProperties(XWikiDocument docBundle)
{
Properties props = new Properties();
String content = docBundle.getContent();
byte[] docContent;
try {
docContent = content.getBytes(BYTE_ENCODING);
} catch (UnsupportedEncodingException ex) {
LOG.error("Error splitting the document into bytes", ex);
docContent = content.getBytes();
}
InputStream is = new ByteArrayInputStream(docContent);
try {
props.load(is);
} catch (IOException e) {
// Cannot do anything
}
return props;
}
/**
* Looks for a translation in the list of internationalization document bundles. It first checks
* if the translation can be found in the cache.
*
* @param key the key identifying the translation
* @return the translation or null if not found or if the passed key is null
*/
protected String getTranslation(String key)
{
String returnValue = null;
if (key != null) {
Iterator it = getDocumentBundles().iterator();
while (it.hasNext()) {
XWikiDocument docBundle = (XWikiDocument) it.next();
if (docBundle != null) {
Long docId = new Long(docBundle.getId());
Properties props = null;
if (this.docsToRefresh.contains(docId) || !this.propsCache.containsKey(docId)) {
// Cache needs to be updated
props = getDocumentBundleProperties(docBundle);
// updates cache
this.propsCache.put(docId, props);
this.docsToRefresh.remove(docId);
} else {
// gets from cache
props = (Properties) this.propsCache.get(docId);
}
String translation = props.getProperty(key);
if (translation != null) {
returnValue = translation;
try {
returnValue =
new String(returnValue.getBytes("ISO-8859-1"), BYTE_ENCODING);
} catch (UnsupportedEncodingException ex) {
LOG.error("Error recombining the value from bytes", ex);
}
break;
}
}
}
}
return returnValue;
}
}
|
/**
* yoshinoda.com
*/
package com.yoshinoda.shou6216;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.yoshinoda.shou6216.model.AreaMeshRoute;
/**
*
* @author shou_y
*
*/
public class RegisterRun {
private static final Logger LOGGER = LoggerFactory.getLogger(RegisterRun.class);
private static final String FROM_FILE = "fromList.txt";
private static final String TO_FILE = "toList.txt";
private static final int TO_COLUMN = 4;
private static final String JSON_FORMAT =
"{'fromMeshCode':%d,'toMeshCode':%d,'timeWalk':%d,'timeCar':%d,'timeTrain':%d}";
private static final String OUTPUT_DIR = "result";
private static final String OUTPUT_FILE_FORMAT = "idsAreaMeshRoute_%d_to%d_%tF.json";
public static void main(String[] args) {
StopWatch sw = new StopWatch();
sw.start();
LOGGER.info("RegisterRun start");
RegisterRun registerRun = new RegisterRun();
registerRun.execute();
sw.stop();
LOGGER.info("RegisterRun end {}[msec]", sw.getTime());
}
public void execute() {
if (!Files.isDirectory(Paths.get(OUTPUT_DIR))) {
LOGGER.warn("output dire not found : {}", OUTPUT_DIR);
return;
}
List<Integer> fromMeshCodeList = getFromMeshCodeList();
if (fromMeshCodeList.isEmpty()) {
LOGGER.info("fromMeshCodeList is empty");
return;
}
Date date = Calendar.getInstance().getTime();
LOGGER.info("date : {}", date);
LOGGER.info("Number of fromMeshCodeList : {}", fromMeshCodeList.size());
for (int fromMeshCode : fromMeshCodeList) {
LOGGER.info("fromMeshCode : {}", fromMeshCode);
//correctionfrom
List<String> writeLines = getToMeshList(fromMeshCode)
.parallelStream()
.map(to -> {
float correctionCar = getCorrection(
fromMeshCode, to.getToMeshCode());
to.setTimeCar(Math.round(to.getTimeCar() * correctionCar));
return String.format(JSON_FORMAT,
to.getFromMeshCode(),
to.getToMeshCode(),
to.getTimeWalk(),
to.getTimeCar(),
to.getTimeTrain());
})
.collect(Collectors.toList());
String outputFileName = String.format(OUTPUT_FILE_FORMAT,
fromMeshCode, writeLines.size(), date);
writeLines(outputFileName, writeLines);
}
}
private float getCorrection(int fromMeshCode, int toMeshCode) {
return Double.valueOf(Math.random()).floatValue();
}
private List<Integer> getFromMeshCodeList() {
Path path = Paths.get(FROM_FILE);
LOGGER.info("fromMeshCodeList path={}", path);
List<Integer> fromMeshCodeList = new ArrayList<Integer>();
try (Stream<String> stream = Files.lines(path, Charset.forName("UTF-8"))) {
fromMeshCodeList = stream
.filter(line -> StringUtils.isNotBlank(line))
.map(line -> Integer.valueOf(line))
.collect(Collectors.toList());
} catch (IOException e) {
LOGGER.error("read fromMeshCodeList error", e);
}
return fromMeshCodeList;
}
private Set<AreaMeshRoute> getToMeshList(int fromMeshCode) {
Set<AreaMeshRoute> toMeshSet = new HashSet<AreaMeshRoute>();
try (Stream<String> stream = Files.lines(Paths.get(TO_FILE), Charset.forName("UTF-8"))) {
toMeshSet = stream
.map(line -> line.split(","))
.filter(values -> values.length == TO_COLUMN)
.map(values -> new AreaMeshRoute(
fromMeshCode,
Integer.valueOf(values[0]),
Integer.valueOf(values[1]),
Integer.valueOf(values[2]),
Integer.valueOf(values[3])
))
.collect(Collectors.toSet());
} catch (IOException e) {
LOGGER.error("read toMeshList error", e);
}
return toMeshSet;
}
private void writeLines(String fileName, List<String> writeLines) {
try {
Files.write(Paths.get(OUTPUT_DIR, fileName), writeLines,
Charset.forName("UTF-8"), StandardOpenOption.CREATE);
} catch (IOException e) {
LOGGER.error("write JSON error", e);
}
}
}
|
package controllers.api;
import com.google.common.base.Strings;
import com.google.common.io.ByteStreams;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import exception.ElementNotFoundException;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.bson.types.ObjectId;
import org.mongodb.morphia.Datastore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.InputStream;
import java.util.Date;
import model.Resource;
import ninja.Context;
import ninja.Result;
import ninja.Results;
import ninja.exceptions.BadRequestException;
import ninja.jaxy.GET;
import ninja.jaxy.POST;
import ninja.jaxy.Path;
import ninja.params.PathParam;
import ninja.utils.HttpCacheToolkit;
@Singleton
@Path("/api/resource")
public class ResourceController {
Logger LOG = LoggerFactory.getLogger(ResourceController.class);
@Inject
private Datastore datastore;
@Inject
private HttpCacheToolkit httpCacheToolkit;
@POST
@Path("/upload")
public Result upload(Context context) throws Exception {
if (context.isMultipart()) {
FileItemIterator fileItemIterator = context.getFileItemIterator();
while (fileItemIterator.hasNext()) {
FileItemStream item = fileItemIterator.next();
String name = item.getFieldName();
String contentType = item.getContentType();
InputStream stream = item.openStream();
if (item.isFormField()) {
LOG.warn("no form field expected");
} else {
Resource resource = new Resource();
resource.setName(name);
resource.setMimeType(contentType);
resource.setContent(ByteStreams.toByteArray(stream));
resource.setLastModified(new Date());
datastore.save(resource);
// TODO: HIRE-94: search for nice solution to return resourceId only
return Results.ok().json().render("id", resource.getId().toString());
}
}
}
return Results.badRequest();
}
@Path("/{id}")
@GET
public Result getResourceById(Context context, @PathParam("id") String id) {
if (Strings.isNullOrEmpty(id)) {
throw new BadRequestException();
}
if (!ObjectId.isValid(id)) {
throw new ElementNotFoundException();
}
final Resource resource = datastore.get(Resource.class, new ObjectId(id));
if (resource == null) {
throw new ElementNotFoundException();
}
Result result = Results.ok().json();
httpCacheToolkit.addEtag(context, result, resource.getLastModified().getTime());
// if resource was modified render image as result
if (result.getStatusCode() != Result.SC_304_NOT_MODIFIED) {
result.contentType(resource.getMimeType()).renderRaw(resource.getContent());
}
// if resource was not modified return result with not modified header
return result;
}
}
|
package cubicchunks.server;
import com.google.common.collect.Maps;
import cubicchunks.CubicChunks;
import cubicchunks.server.chunkio.CubeIO;
import cubicchunks.util.AddressTools;
import cubicchunks.util.Coords;
import cubicchunks.util.CubeCoords;
import cubicchunks.world.ICubeCache;
import cubicchunks.world.ICubicWorldServer;
import cubicchunks.world.column.Column;
import cubicchunks.world.cube.Cube;
import net.minecraft.entity.EnumCreatureType;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.WorldServer;
import net.minecraft.world.biome.Biome;
import net.minecraft.world.chunk.Chunk;
import net.minecraft.world.gen.ChunkProviderOverworld;
import net.minecraft.world.gen.ChunkProviderServer;
import org.apache.logging.log4j.Logger;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.io.IOException;
import java.util.ArrayDeque;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Queue;
import static cubicchunks.server.ServerCubeCache.LoadType.FORCE_LOAD;
import static cubicchunks.server.ServerCubeCache.LoadType.LOAD_ONLY;
import static cubicchunks.server.ServerCubeCache.LoadType.LOAD_OR_GENERATE;
/**
* This is CubicChunks equivalent of ChunkProviderServer, it loads and unloads Cubes and Columns.
* <p>
* There are a few necessary changes to the way vanilla methods work:
* * Because loading a Chunk (Column) doesn't make much sense with CubicChunks,
* all methods that load Chunks, actually load an empry column with no blocks in it
* (there may be some entities that are not in any Cube yet).
* * dropChunk method is not supported. Columns are unloaded automatically when the last cube is unloaded
*/
public class ServerCubeCache extends ChunkProviderServer implements ICubeCache {
private static final Logger log = CubicChunks.LOGGER;
public static final int SPAWN_LOAD_RADIUS = 12; // highest render distance is 32
private ICubicWorldServer worldServer;
private CubeIO cubeIO;
private HashMap<Long, Column> loadedColumns;
private Queue<CubeCoords> cubesToUnload;
public ServerCubeCache(ICubicWorldServer worldServer) {
//TODO: Replace add ChunkGenerator argument and use chunk generator object for generating terrain?
//ChunkGenerator has to exist for mob spawning to work
super((WorldServer) worldServer, worldServer.getSaveHandler().getChunkLoader(worldServer.getProvider()),
new ChunkProviderOverworld((World) worldServer, worldServer.getSeed(), false, null));
this.worldServer = worldServer;
this.cubeIO = new CubeIO(worldServer);
this.loadedColumns = Maps.newHashMap();
this.cubesToUnload = new ArrayDeque<>();
}
@Override
public Collection<Chunk> getLoadedChunks() {
return (Collection<Chunk>) (Object) this.loadedColumns.values();
}
@Override
public void unload(Chunk chunk) {
//ignore, ChunkGc unloads cubes
}
@Override
public void unloadAllChunks() {
// unload all the cubes in the columns
for (Column column : this.loadedColumns.values()) {
for (Cube cube : column.getAllCubes()) {
this.cubesToUnload.add(cube.getCoords());
}
}
}
/**
* Vanilla method, returns a Chunk (Column) only of it's already loaded.
* Same as getColumn(cubeX, cubeZ)
*/
@Override
@Nullable
public Chunk getLoadedChunk(int cubeX, int cubeZ) {
return this.getColumn(cubeX, cubeZ);
}
/**
* Loads Chunk (Column) if it can be loaded from disk, or returns already loaded one.
* Doesn't generate new Columns.
*/
@Override
@Nullable
public Column loadChunk(int cubeX, int cubeZ) {
return this.loadColumn(cubeX, cubeZ, LOAD_ONLY);
}
/**
* Load chunk asynchronously. Currently CubicChunks only loads synchronously.
*/
@Override
@Nullable
public Column loadChunk(int cubeX, int cubeZ, Runnable runnable) {
Column column = this.loadColumn(cubeX, cubeZ, LOAD_OR_GENERATE);
if (runnable == null) {
return column;
}
runnable.run();
return null;
}
/**
* If this Column is already loaded - returns it.
* Loads from disk if possible, otherwise generated new Column.
*/
@Override
public Column provideChunk(int cubeX, int cubeZ) {
return loadChunk(cubeX, cubeZ, null);
}
@Override
public boolean saveChunks(boolean alwaysTrue) {
for (Column column : this.loadedColumns.values()) {
// save the column
if (column.needsSaving(alwaysTrue)) {
this.cubeIO.saveColumn(column);
}
// save the cubes
for (Cube cube : column.getAllCubes()) {
if (cube.needsSaving()) {
this.cubeIO.saveCube(cube);
}
}
}
return true;
}
@Override
public boolean unloadQueuedChunks() {
// NOTE: the return value is completely ignored
if (this.worldServer.getDisableLevelSaving()) {
return false;
}
final int maxUnload = 400;
Iterator<CubeCoords> iter = this.cubesToUnload.iterator();
int processed = 0;
while (iter.hasNext() && processed < maxUnload) {
CubeCoords coords = iter.next();
iter.remove();
++processed;
long columnAddress = AddressTools.getAddress(coords.getCubeX(), coords.getCubeZ());
Column column = this.loadedColumns.get(columnAddress);
if (column == null) {
continue;
}
Cube cube = column.removeCube(coords.getCubeY());
if (cube != null) {
cube.onUnload();
this.cubeIO.saveCube(cube);
}
if (!column.hasCubes()) {
column.onChunkUnload();
this.loadedColumns.remove(columnAddress);
this.cubeIO.saveColumn(column);
}
}
return false;
}
@Override
public String makeString() {
return "ServerCubeCache: " + this.loadedColumns.size() + " columns, Unload: " + this.cubesToUnload.size() +
" cubes";
}
@Override
public List<Biome.SpawnListEntry> getPossibleCreatures(@Nonnull final EnumCreatureType type, @Nonnull final BlockPos pos) {
return super.getPossibleCreatures(type, pos);
}
@Nullable
public BlockPos getStrongholdGen(@Nonnull World worldIn, @Nonnull String structureName, @Nonnull BlockPos position) {
return null;
}
@Override
public int getLoadedChunkCount() {
return this.loadedColumns.size();
}
@Override
public boolean chunkExists(int cubeX, int cubeZ) {
return this.loadedColumns.containsKey(AddressTools.getAddress(cubeX, cubeZ));
}
@Override
public boolean cubeExists(int cubeX, int cubeY, int cubeZ) {
long columnAddress = AddressTools.getAddress(cubeX, cubeZ);
Column column = this.loadedColumns.get(columnAddress);
if (column == null) {
return false;
}
return column.getCube(cubeY) != null;
}
public boolean cubeExists(CubeCoords coords) {
return this.cubeExists(coords.getCubeX(), coords.getCubeY(), coords.getCubeZ());
}
@Override
public Column getColumn(int columnX, int columnZ) {
return this.loadedColumns.get(AddressTools.getAddress(columnX, columnZ));
}
@Override
public Cube getCube(int cubeX, int cubeY, int cubeZ) {
long columnAddress = AddressTools.getAddress(cubeX, cubeZ);
Column column = this.loadedColumns.get(columnAddress);
if (column == null) {
return null;
}
return column.getCube(cubeY);
}
public Cube getCube(CubeCoords coords) {
return this.getCube(coords.getCubeX(), coords.getCubeY(), coords.getCubeZ());
}
public void loadCube(int cubeX, int cubeY, int cubeZ, LoadType loadType) {
if (loadType == FORCE_LOAD) {
throw new UnsupportedOperationException("Cannot force load a cube");
}
// Get the column
long columnAddress = AddressTools.getAddress(cubeX, cubeZ);
// Is it loaded?
Column column = this.loadedColumns.get(columnAddress);
// Try loading the column.
if (column == null) {
column = this.loadColumn(cubeX, cubeZ, loadType);
}
// If we couldn't load or generate the column - give up.
if (column == null) {
if (loadType == LOAD_OR_GENERATE) {
CubicChunks.LOGGER.error(
"Loading cube at " + cubeX + ", " + cubeY + ", " + cubeZ + " failed, couldn't load column");
}
return;
}
// Get the cube.
long cubeAddress = AddressTools.getAddress(cubeX, cubeY, cubeZ);
// Is the cube loaded?
Cube cube = column.getCube(cubeY);
if (cube != null) {
return;
}
// Try loading the cube.
try {
cube = this.cubeIO.loadCubeAndAddToColumn(column, cubeAddress);
} catch (IOException ex) {
log.error("Unable to load cube ({},{},{})", cubeX, cubeY, cubeZ, ex);
return;
}
// If loading it didn't work...
if (cube == null) {
// ... and generating has been requested, generate it.
if (loadType == LoadType.LOAD_OR_GENERATE) {
cube = column.getOrCreateCube(cubeY, true);
this.worldServer.getCubeGenerator().generateCube(cube);
}
// ... or quit.
else {
return;
}
}
// Init the column.
if (!column.isLoaded()) {
column.onChunkLoad();
}
column.setTerrainPopulated(true);
// Init the cube.
cube.onLoad();
}
public void loadCube(CubeCoords coords, LoadType loadType) {
this.loadCube(coords.getCubeX(), coords.getCubeY(), coords.getCubeZ(), loadType);
}
public Column loadColumn(int cubeX, int cubeZ, LoadType loadType) {
Column column = null;
//if we are not forced to load from disk - try to get it first
if (loadType != FORCE_LOAD) {
column = getColumn(cubeX, cubeZ);
}
if (column != null) {
return column;
}
try {
column = this.cubeIO.loadColumn(cubeX, cubeZ);
} catch (IOException ex) {
log.error("Unable to load column ({},{})", cubeX, cubeZ, ex);
return null;
}
if (column == null) {
// there wasn't a column, generate a new one (if allowed to generate)
if (loadType == LOAD_OR_GENERATE) {
column = this.worldServer.getColumnGenerator().generateColumn(cubeX, cubeZ);
}
} else {
// the column was loaded
column.setLastSaveTime(this.worldServer.getTotalWorldTime());
}
if (column == null) {
return null;
}
this.loadedColumns.put(AddressTools.getAddress(cubeX, cubeZ), column);
column.onChunkLoad();
return column;
}
private boolean cubeIsNearSpawn(Cube cube) {
if (!this.worldServer.getProvider().canRespawnHere()) {
// no spawn points
return false;
}
BlockPos spawnPoint = this.worldServer.getSpawnPoint();
int spawnCubeX = Coords.blockToCube(spawnPoint.getX());
int spawnCubeY = Coords.blockToCube(spawnPoint.getY());
int spawnCubeZ = Coords.blockToCube(spawnPoint.getZ());
int dx = Math.abs(spawnCubeX - cube.getX());
int dy = Math.abs(spawnCubeY - cube.getY());
int dz = Math.abs(spawnCubeZ - cube.getZ());
return dx <= SPAWN_LOAD_RADIUS && dy <= SPAWN_LOAD_RADIUS && dz <= SPAWN_LOAD_RADIUS;
}
public String dumpLoadedCubes() {
StringBuilder sb = new StringBuilder(10000).append("\n");
for (Column column : this.loadedColumns.values()) {
if (column == null) {
sb.append("column = null\n");
continue;
}
sb.append("Column[").append(column.getX()).append(", ").append(column.getZ()).append("] {");
boolean isFirst = true;
for (Cube cube : column.getAllCubes()) {
if (!isFirst) {
sb.append(", ");
}
isFirst = false;
if (cube == null) {
sb.append("cube = null");
continue;
}
sb.append("Cube[").append(cube.getY()).append("]");
}
sb.append("\n");
}
return sb.toString();
}
public void flush() {
this.cubeIO.flush();
}
public void unloadCube(Cube cube) {
// don't unload cubes near the spawn
if (cubeIsNearSpawn(cube)) {
return;
}
// queue the cube for unloading
this.cubesToUnload.add(cube.getCoords());
}
public void unloadColumn(Column column) {
if(!column.hasCubes()) {
//TODO: remove unloadColumn hack
//the column has no cubes, to unload the column - try to unload already unloaded cube
//unloadQueuedChunks will automatically unload column once it's empty
//just in case additional cube gets loaded between call to this method
//and actual unload - specify impossible Y coordinate
this.cubesToUnload.add(new CubeCoords(column.getX(), Integer.MIN_VALUE, column.getZ()));
}
}
public enum LoadType {
LOAD_ONLY, LOAD_OR_GENERATE, FORCE_LOAD
}
}
|
package de.bmoth.modelchecker;
import com.microsoft.z3.Context;
import com.microsoft.z3.Expr;
import com.microsoft.z3.Model;
import de.bmoth.backend.Abortable;
import de.bmoth.backend.TranslationOptions;
import de.bmoth.backend.z3.FormulaToZ3Translator;
import de.bmoth.backend.z3.MachineToZ3Translator;
import de.bmoth.parser.ast.nodes.MachineNode;
import de.bmoth.parser.ast.nodes.PredicateNode;
import de.bmoth.parser.ast.nodes.ltl.BuechiAutomaton;
import de.bmoth.parser.ast.nodes.ltl.BuechiAutomatonNode;
import java.util.HashSet;
import java.util.Set;
public abstract class ModelChecker implements Abortable {
private Context ctx;
private MachineToZ3Translator machineTranslator;
private volatile boolean isAborted;
protected ModelChecker(MachineNode machine) {
this.ctx = new Context();
this.machineTranslator = new MachineToZ3Translator(machine, ctx);
}
public final ModelCheckingResult check() {
isAborted = false;
return doModelCheck();
}
@Override
public void abort() {
isAborted = true;
}
protected boolean isAborted() {
return isAborted;
}
protected Context getContext() {
return ctx;
}
protected MachineToZ3Translator getMachineTranslator() {
return machineTranslator;
}
protected abstract ModelCheckingResult doModelCheck();
protected State getStateFromModel(State predecessor, Model model, TranslationOptions ops, BuechiAutomaton buechiAutomaton) {
Set<BuechiAutomatonNode> buechiNodes;
if (predecessor == null) {
buechiNodes = buechiAutomaton.getInitialStates();
} else {
buechiNodes = new HashSet<>();
Set<BuechiAutomatonNode> predecessorBuechiNodes = predecessor.getBuechiNodes();
for (BuechiAutomatonNode node : predecessorBuechiNodes) {
Set<BuechiAutomatonNode> nodeSuccessors = node.getSuccessors();
for (BuechiAutomatonNode successor : nodeSuccessors) {
if (successor.getLabels().isEmpty()) {
buechiNodes.add(successor);
}
for (PredicateNode label : successor.getLabels()) {
Expr eval = model.eval(FormulaToZ3Translator.translatePredicate(label, ctx, machineTranslator.getZ3TypeInference()), true);
switch (eval.getBoolValue()) {
case Z3_L_FALSE:
break;
case Z3_L_UNDEF:
throw new UnsupportedOperationException("should not be undefined");
case Z3_L_TRUE:
buechiNodes.add(successor);
}
}
}
}
}
return new State(predecessor, getMachineTranslator().getVarMapFromModel(model, ops), buechiNodes);
}
protected State getStateFromModel(State predecessor, Model model, TranslationOptions ops) {
return new State(predecessor, getMachineTranslator().getVarMapFromModel(model, ops));
}
}
|
package de.ddb.pdc.metadata;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.ArrayList;
@JsonIgnoreProperties(ignoreUnknown = true)
class EntitiesResult {
@JsonProperty
private ArrayList<EntitiesResultList> results;
public EntitiesResultItem getResultItem() {
if (results.size() == 0 || results.get(0).getDocs().size() == 0) {
return null;
} else {
return results.get(0).getDocs().get(0);
}
}
}
|
package de.epiceric.shopchest.nms;
import de.epiceric.shopchest.ShopChest;
import de.epiceric.shopchest.utils.Utils;
import org.bukkit.Location;
import org.bukkit.entity.ArmorStand;
import org.bukkit.entity.Player;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
public class Hologram {
private static List<Hologram> holograms = new ArrayList<>();
private boolean exists = false;
private List<Object> entityList = new ArrayList<>();
private List<UUID> entityUuidList = new ArrayList<>();
private String[] text;
private Location location;
private List<Player> visible = new ArrayList<>();
private ShopChest plugin;
private Class<?> entityArmorStandClass = Utils.getNMSClass("EntityArmorStand");
private Class<?> nmsWorldClass = Utils.getNMSClass("World");
private Class<?> packetPlayOutSpawnEntityLivingClass = Utils.getNMSClass("PacketPlayOutSpawnEntityLiving");
private Class<?> packetPlayOutEntityDestroyClass = Utils.getNMSClass("PacketPlayOutEntityDestroy");
private Class<?> entityClass = Utils.getNMSClass("Entity");
private Class<?> entityLivingClass = Utils.getNMSClass("EntityLiving");
public Hologram(ShopChest plugin, String[] text, Location location) {
this.plugin = plugin;
this.text = text;
this.location = location;
Class[] requiredClasses = new Class[] {
nmsWorldClass, entityArmorStandClass, entityLivingClass, entityClass,
packetPlayOutSpawnEntityLivingClass, packetPlayOutEntityDestroyClass
};
for (Class c : requiredClasses) {
if (c == null) {
plugin.debug("Failed to create hologram: Could not find all required classes");
return;
}
}
create();
}
private void create() {
Location loc = location.clone();
for (int i = 0; i <= text.length; i++) {
String text = null;
if (i != this.text.length) {
text = this.text[i];
if (text == null) continue;
} else {
if (plugin.getShopChestConfig().enable_hologram_interaction) {
loc = location.clone();
loc.add(0, 1, 0);
} else {
continue;
}
}
try {
Object craftWorld = loc.getWorld().getClass().cast(loc.getWorld());
Object nmsWorldServer = craftWorld.getClass().getMethod("getHandle").invoke(craftWorld);
Constructor entityArmorStandConstructor = entityArmorStandClass.getConstructor(nmsWorldClass, double.class, double.class, double.class);
Object entityArmorStand = entityArmorStandConstructor.newInstance(nmsWorldServer, loc.getX(), loc.getY(),loc.getZ());
if (text != null) {
entityArmorStandClass.getMethod("setCustomName", String.class).invoke(entityArmorStand, text);
entityArmorStandClass.getMethod("setCustomNameVisible", boolean.class).invoke(entityArmorStand, true);
}
entityArmorStandClass.getMethod("setInvisible", boolean.class).invoke(entityArmorStand, true);
if (Utils.getMajorVersion() < 10) {
entityArmorStandClass.getMethod("setGravity", boolean.class).invoke(entityArmorStand, false);
} else {
entityArmorStandClass.getMethod("setNoGravity", boolean.class).invoke(entityArmorStand, true);
}
// Probably like an addEntity() method...
Method b = nmsWorldServer.getClass().getDeclaredMethod("b", entityClass);
b.setAccessible(true);
b.invoke(nmsWorldServer, entityArmorStand);
Object uuid = entityClass.getMethod("getUniqueID").invoke(entityArmorStand);
entityUuidList.add((UUID) uuid);
entityList.add(entityArmorStand);
loc.subtract(0, 0.25, 0);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException | InstantiationException e) {
plugin.getLogger().severe("Could not create Hologram with reflection");
plugin.debug("Could not create Hologram with reflection");
plugin.debug(e);
}
}
holograms.add(this);
exists = true;
}
/**
* @return Location of the hologram
*/
public Location getLocation() {
return location;
}
/**
* @param p Player to which the hologram should be shown
*/
public void showPlayer(Player p) {
for (Object o : entityList) {
try {
Object entityLiving = entityLivingClass.cast(o);
Object packet = packetPlayOutSpawnEntityLivingClass.getConstructor(entityLivingClass).newInstance(entityLiving);
Utils.sendPacket(plugin, packet, p);
} catch (NoSuchMethodException | InstantiationException | InvocationTargetException | IllegalAccessException e) {
plugin.getLogger().severe("Could not show Hologram to player with reflection");
plugin.debug("Could not show Hologram to player with reflection");
plugin.debug(e);
}
}
visible.add(p);
}
/**
* @param p Player from which the hologram should be hidden
*/
public void hidePlayer(Player p) {
for (Object o : entityList) {
try {
int id = (int) entityArmorStandClass.getMethod("getId").invoke(o);
Object packet = packetPlayOutEntityDestroyClass.getConstructor(int[].class).newInstance((Object) new int[] {id});
Utils.sendPacket(plugin, packet, p);
} catch (NoSuchMethodException | InstantiationException | InvocationTargetException | IllegalAccessException e) {
plugin.getLogger().severe("Could not hide Hologram from player with reflection");
plugin.debug("Could not hide Hologram from player with reflection");
plugin.debug(e);
}
}
visible.remove(p);
}
/**
* @param p Player to check
* @return Whether the hologram is visible to the player
*/
public boolean isVisible(Player p) {
return visible.contains(p);
}
/**
* @return Whether the hologram exists and is not dead
*/
public boolean exists() {
return exists;
}
/**
* @param armorStand Armor stand to check
* @return Whether the given armor stand is part of the hologram
*/
public boolean contains(ArmorStand armorStand) {
return entityUuidList.contains(armorStand.getUniqueId());
}
/**
* Removes the hologram. <br>
* IHologram will be hidden from all players and will be killed
*/
public void remove() {
for (Object o : entityList) {
try {
o.getClass().getMethod("die").invoke(o);
} catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
plugin.getLogger().severe("Could not remove Hologram with reflection");
plugin.debug("Could not remove Hologram with reflection");
plugin.debug(e);
}
}
exists = false;
holograms.remove(this);
}
/**
* @param armorStand Armor stand that's part of a hologram
* @return Hologram, the armor stand is part of
*/
public static Hologram getHologram(ArmorStand armorStand) {
for (Hologram hologram : holograms) {
if (hologram.contains(armorStand)) return hologram;
}
return null;
}
/**
* @param armorStand Armor stand to check
* @return Whether the armor stand is part of a hologram
*/
public static boolean isPartOfHologram(ArmorStand armorStand) {
for (Hologram hologram : holograms) {
if (hologram.contains(armorStand)) {
return true;
}
}
return false;
}
}
|
package de.fau.cs.mad.kwikshop.common;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.j256.ormlite.field.DataType;
import com.j256.ormlite.field.DatabaseField;
import com.j256.ormlite.table.DatabaseTable;
import javax.persistence.*;
import java.sql.Blob;
import java.util.Date;
//Hibernate annotations (server side)
@Entity(name = "Item")
//ORMLite annotations (android client)
@DatabaseTable(tableName = "item")
public class Item {
public static final String FOREIGN_SHOPPINGLIST_FIELD_NAME = "shoppingList";
public static final String FOREIGN_RECIPE_FIELD_NAME = "recipe";
//Hibernate
@Id
@GeneratedValue
@Column(name = "id")
//ORMLite
@DatabaseField(generatedId = true)
private int id;
/**
* Order of this Item in the ShoppingList
*/
//Hibernate
@Column(name="itemOrder")
//ORMLite
@DatabaseField
private int order = -1;
//Hibernate
@Column(name="isBought")
//ORMLite
@DatabaseField
private Boolean bought = false;
//Hibernate
@Column(name = "name")
//ORMLite
@DatabaseField(canBeNull = false)
private String name = "";
//Hibernate
@Column(name = "amount")
//ORMLite
@DatabaseField
private int amount = 1;
//Hibernate
@Column(name = "isHighlighted")
//ORMLite
@DatabaseField
private Boolean highlight = false;
//Hibernate
@Column(name ="brand")
//ORMLite
@DatabaseField(canBeNull = true)
private String brand;
//Hibernate
@Column(name="comment")
//ORMLite
@DatabaseField(canBeNull = true)
private String comment;
//Hibernate
@ManyToOne(fetch = FetchType.EAGER, cascade = { CascadeType.PERSIST, CascadeType.REMOVE })
@JoinColumn(name = "groupId")
//ORMLite
@DatabaseField(foreign = true)
private Group group;
//Hibernate
@ManyToOne(fetch = FetchType.EAGER, cascade = { CascadeType.PERSIST, CascadeType.REMOVE })
@JoinColumn(name = "unitId")
//ORMLite
@DatabaseField(foreign = true)
private Unit unit;
/**
* The ShoppingList, that contains this Item.
* (Required for ORMLite)
*/
//Hibernate: not mapped
@Transient
//ORMLite
@DatabaseField(foreign = true, columnName = FOREIGN_SHOPPINGLIST_FIELD_NAME)
private ShoppingList shoppingList;
/**
* The Recipe, that contains this Item.
* (Required for ORMLite)
*/
//Hibernate: not mapped
@Transient
//ORMLite
@DatabaseField(foreign = true, columnName = FOREIGN_RECIPE_FIELD_NAME)
private Recipe recipe;
//Hibernate
@Column(name = "lastBought")
//ORMLite
@DatabaseField(canBeNull = true)
private Date lastBought;
//Hibernate
@Column(name = "isRegularlyRepeatedItem")
//ORMLite
@DatabaseField
private boolean regularlyRepeatItem;
//Hibernate
@Column(name = "repeatType")
@Enumerated(EnumType.ORDINAL)
//ORMLite
@DatabaseField
private TimePeriodsEnum periodType;
//Hibernate
@Column(name ="selectedRepeatTime")
//ORMLite
@DatabaseField
private int selectedRepeatTime;
//Hibernate
@Column(name = "remindFromNextPurchaseOn")
//ORMLite
@DatabaseField
private boolean remindFromNextPurchaseOn;
//Hibernate
@Column(name = "remindAtDate")
//ORMLite
@DatabaseField(canBeNull = true)
private Date remindAtDate;
//Hibernate
@ManyToOne(fetch = FetchType.EAGER, cascade = { CascadeType.PERSIST, CascadeType.REMOVE })
@JoinColumn(name = "locationId")
//ORMLite
@DatabaseField(foreign = true, canBeNull = true)
private LastLocation location;
//Hibernate
@Column(name = "imageItem")
//ORMLite
@DatabaseField(canBeNull = true)
private String imageItem;
public Item() {
// Default no-arg constructor for generating Items, required for ORMLite
}
/**
* Copies an other item. Most fields are copied, but not order, recipe, shoppingList, id and all repeat-related fields
* @param item The item to copy
*/
public Item(Item item) {
this.amount = item.amount;
this.name = item.name;
this.highlight = item.highlight;
this.brand = item.brand;
this.comment = item.comment;
this.group = item.group;
this.unit = item.unit;
this.location = item.location;
this.imageItem = item.imageItem;
}
@JsonProperty
public int getId() {
return id;
}
// TODO: REMOVE THIS, only for testing. IDs should be read only
public void setID(int id) {
this.id = id;
}
@JsonProperty
public int getOrder() {
return order;
}
public void setOrder(int order) {
this.order = order;
}
@JsonProperty
public Boolean isBought() {
return bought;
}
public void setBought(Boolean bought) {
this.bought = bought;
}
@JsonProperty
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@JsonProperty
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
@JsonProperty
public Boolean isHighlight() {
return highlight;
}
public void setHighlight(Boolean highlight) {
this.highlight = highlight;
}
@JsonProperty
public String getBrand() {
return (brand == null ? "" : brand);
}
public void setBrand(String brand) {
this.brand = brand;
}
@JsonProperty
public String getComment() {
return (comment == null ? "" : comment);
}
public void setComment(String comment) {
this.comment = comment;
}
@JsonProperty
public Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
@JsonProperty
public Unit getUnit() {
return unit;
}
public void setUnit(Unit unit) {
this.unit = unit;
}
@JsonProperty
public Date getLastBought() {
return lastBought;
}
public void setLastBought(Date lastBought) {
this.lastBought = lastBought;
}
@JsonProperty
public boolean isRegularlyRepeatItem() {
return regularlyRepeatItem;
}
public void setRegularlyRepeatItem(boolean regularlyRepeatItem) {
this.regularlyRepeatItem = regularlyRepeatItem;
}
@JsonProperty
public TimePeriodsEnum getPeriodType() {
return periodType;
}
public void setPeriodType(TimePeriodsEnum periodType) {
this.periodType = periodType;
}
@JsonProperty
public int getSelectedRepeatTime() {
return selectedRepeatTime;
}
public void setSelectedRepeatTime(int selectedRepeatTime) {
this.selectedRepeatTime = selectedRepeatTime;
}
@JsonProperty
public Date getRemindAtDate() {
return remindAtDate;
}
public void setRemindAtDate(Date remindAtDate) {
this.remindAtDate = remindAtDate;
}
@JsonProperty
public boolean isRemindFromNextPurchaseOn() {
return remindFromNextPurchaseOn;
}
public void setRemindFromNextPurchaseOn(boolean remindFromNextPurchaseOn) {
this.remindFromNextPurchaseOn = remindFromNextPurchaseOn;
}
@JsonProperty
public boolean isRemindFromNowOn() {
return !remindFromNextPurchaseOn;
}
public void setRemindFromNowOn(boolean remindFromNowOn) {
this.remindFromNextPurchaseOn = !remindFromNowOn;
}
@JsonProperty
public LastLocation getLocation() {
return location;
}
public void setLocation(LastLocation location) {
this.location = location;
}
@JsonProperty
public String getImageItem() {
return imageItem;
}
public void setImageItem(String imageItem) {
this.imageItem = imageItem;
}
@JsonIgnore
public ShoppingList getShoppingList() {
return shoppingList;
}
//TODO: REMOVE THIS, only for testing. The shoppingList should only be changed by ORM
public void setShoppingList(ShoppingList shoppingList) {
this.shoppingList = shoppingList;
}
@Override
public boolean equals(Object o) {
if (o == null) {
return false;
}
if (this == o) {
return true;
}
if (o.getClass() != this.getClass()) {
return false;
}
Item item = (Item) o;
return item.id == this.id;
}
@Override
public int hashCode() {
return id;
}
}
|
/**
* Main class for the 3D Game
*/
package graphics.d3;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.ApplicationListener;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.PerspectiveCamera;
import com.badlogic.gdx.graphics.VertexAttributes;
import com.badlogic.gdx.graphics.VertexAttributes.Usage;
import com.badlogic.gdx.graphics.g3d.Environment;
import com.badlogic.gdx.graphics.g3d.Material;
import com.badlogic.gdx.graphics.g3d.Model;
import com.badlogic.gdx.graphics.g3d.ModelBatch;
import com.badlogic.gdx.graphics.g3d.ModelInstance;
import com.badlogic.gdx.graphics.g3d.attributes.BlendingAttribute;
import com.badlogic.gdx.graphics.g3d.attributes.ColorAttribute;
import com.badlogic.gdx.graphics.g3d.environment.DirectionalLight;
import com.badlogic.gdx.graphics.g3d.utils.CameraInputController;
import com.badlogic.gdx.graphics.g3d.utils.ModelBuilder;
import com.badlogic.gdx.math.Vector3;
import graphics.rooms.game.Game.STATE;
import graphics.rooms.game.GameRepository;
import logic.Input.KEY;
import logic.Objeto;
import logic.characters.Block;
import logic.characters.Bomb;
import logic.characters.DestroyableBlock;
import logic.characters.Enemy;
import logic.characters.ExplosionPart;
import logic.characters.Item;
import logic.characters.Player;
import logic.collisions.Point2D;
import logic.misc.Level;
import main.Game;
/**
* @author Patricia Lazaro Tello (554309)
* @author Jaime Ruiz-Borau Vizarraga (546751)
*/
public class SuperBomberman3D extends ApplicationAdapter implements ApplicationListener {
/**
* @param game
* 2DGame room
*/
public SuperBomberman3D(graphics.rooms.game.Game game) {
room = game;
}
/**
* @param game
* 2DGame room
* @return a new desktop libgdx application that runs the 3D game
*/
public static LwjglApplication main(graphics.rooms.game.Game game) {
LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();
config.height = Game.HEIGHT;
config.width = Game.WIDTH;
config.title = "Super Bomberman 3D";
return new LwjglApplication(new SuperBomberman3D(game), config);
}
/* attributes */
public PerspectiveCamera cam;
public CameraInputController camController;
public Model bombermanModel;
public Model enemyModel;
public Model boxModel;
public Model destroyableModel;
public Model itemModelS;
public Model itemModelP;
public Model itemModelB;
public Model bombModel;
public Model explosionModel;
public Model planeModel;
public Environment env;
public ModelBatch modelBatch;
private int FIELD_OF_VIEW = 67;
private Vector3 initialPosition = new Vector3(200f, 500f, 200f);
private Vector3 origin = new Vector3(0, 0, 0);
private float near = 1f;
private float far = 5000f;
private int width, height;
/* Game */
public graphics.rooms.game.Game room;
private int xInitPlane, zInitPlane, xEndPlane, zEndPlane;
public Map<Objeto, ModelInstance> objetos;
public ModelInstance plane;
/* End Game */
@Override
public void create() {
init();
camera();
models();
environment();
System.out.println("Finished creating things");
}
/**
* Initializes some variables
*/
private void init() {
Level lvl = room.level;
xInitPlane = lvl.mapInitX;
xEndPlane = lvl.mapInitX + lvl.mapWidth;
zInitPlane = lvl.mapInitY;
zEndPlane = lvl.mapInitY + lvl.mapHeight;
float xMid = xInitPlane + (xEndPlane - xInitPlane) / 2;
float zMid = zInitPlane + (zEndPlane - zInitPlane) / 2;
origin = new Vector3(xMid, 0, zMid);
initialPosition = new Vector3(xMid, 600, zMid);
}
/**
* Initializes the camera
*/
private void camera() {
cam = new PerspectiveCamera(FIELD_OF_VIEW, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
cam.position.set(initialPosition);
cam.lookAt(origin);
cam.near = near;
cam.far = far;
cam.update();
camController = new CameraInputController(cam);
Gdx.input.setInputProcessor(camController);
}
/**
* Initializes the 3D models and instances them
*/
private void models() {
modelBatch = new ModelBatch();
ModelBuilder mb = new ModelBuilder();
width = GameRepository.block.getWidth();
height = GameRepository.block.getHeight();
/* bomberman */
bombermanModel = mb.createBox(width - 10, height + height / 2, width - 10,
new Material(ColorAttribute.createDiffuse(Color.BLUE)), Usage.Position | Usage.Normal);
/* enemy */
enemyModel = mb.createBox(width - 10, height + height / 2, width - 10,
new Material(ColorAttribute.createDiffuse(Color.ORANGE)), Usage.Position | Usage.Normal);
/* box */
boxModel = mb.createBox(width, height, width, new Material(ColorAttribute.createDiffuse(Color.BROWN)),
Usage.Position | Usage.Normal);
/* destroyable */
destroyableModel = mb.createBox(width, height, width, new Material(ColorAttribute.createDiffuse(Color.OLIVE)),
Usage.Position | Usage.Normal);
/* item */
itemModelS = mb.createBox(width, height, width, new Material(ColorAttribute.createDiffuse(Color.CYAN)),
Usage.Position | Usage.Normal);
itemModelP = mb.createBox(width, height, width, new Material(ColorAttribute.createDiffuse(Color.YELLOW)),
Usage.Position | Usage.Normal);
itemModelB = mb.createBox(width, height, width, new Material(ColorAttribute.createDiffuse(Color.BLACK)),
Usage.Position | Usage.Normal);
/* bomb */
bombModel = mb.createSphere(width, height, width, 100,100,new Material(ColorAttribute.createDiffuse(Color.GRAY),ColorAttribute.createAmbient(Color.BLACK)),
Usage.Position | Usage.Normal);
/* explosion */
explosionModel = mb.createCylinder(width, height, width, 100, new Material(ColorAttribute.createDiffuse(Color.RED)),
Usage.Position | Usage.Normal);
/* plane model */
planeModel = mb.createRect(xInitPlane, 0, zEndPlane, xEndPlane, 0, zEndPlane, xEndPlane, 0, zInitPlane,
xInitPlane, 0, zInitPlane, 0, 1, 0, GL20.GL_TRIANGLES,
new Material(new ColorAttribute(ColorAttribute.createDiffuse(Color.GREEN)),
new BlendingAttribute(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA)),
VertexAttributes.Usage.Position | VertexAttributes.Usage.TextureCoordinates);
plane = new ModelInstance(planeModel);
/* instances the objects of the 2D game room */
objetos = new HashMap<>();
for (Objeto obj : room.objetos) {
ModelInstance model = null;
boolean insert = false;
if (obj instanceof Player) {
insert = true;
model = new ModelInstance(bombermanModel);
model.transform.translate(0, height / 2, 0);
model.transform.translate(obj.x, 0, obj.y + logic.misc.Map.fixpos);
}
if (obj instanceof Block) {
insert = true;
model = new ModelInstance(boxModel);
model.transform.translate(0, height / 2, 0);
model.transform.translate(obj.x, 0, obj.y);
}
if (obj instanceof DestroyableBlock) {
insert = true;
model = new ModelInstance(destroyableModel);
model.transform.translate(0, height / 2, 0);
model.transform.translate(obj.x, 0, obj.y);
}
if (obj instanceof Enemy) {
insert = true;
model = new ModelInstance(enemyModel);
model.transform.translate(0, height / 2, 0);
model.transform.translate(obj.x, 0, obj.y + logic.misc.Map.fixpos);
}
if (insert) {
objetos.put(obj, model);
}
}
}
/**
* Initializes the environment
*/
private void environment() {
env = new Environment();
env.set(new ColorAttribute(ColorAttribute.AmbientLight, 0.2f, 0.2f, 0.2f, 1f));
env.add(new DirectionalLight().set(0.8f, 0.8f, 0.8f, -1f, -0.8f, -0.2f));
}
@Override
public void render() {
step();
Collection<ModelInstance> objetosLista = objetos.values();
camController.update();
Gdx.gl.glViewport(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight());
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT | GL20.GL_DEPTH_BUFFER_BIT);
modelBatch.begin(cam);
modelBatch.render(objetosLista, env);
modelBatch.render(plane, env);
modelBatch.end();
}
/**
* Updates objects' positions, destroy the objects that needs to be
* destroyed and creates the new ones
*/
public void step() {
/* previous position */
Map<Objeto, Point2D> lastPos = new HashMap<>();
for (Objeto obj : objetos.keySet()) {
lastPos.put(obj, new Point2D(obj.x, obj.y));
}
/* key handling */
KEY dir = KEY.NO_KEY;
KEY keyPressed = KEY.NO_KEY;
if (Gdx.input.isKeyPressed(Input.Keys.UP)) {
dir = KEY.UP;
}
if (Gdx.input.isKeyPressed(Input.Keys.DOWN)) {
dir = KEY.DOWN;
}
if (Gdx.input.isKeyPressed(Input.Keys.LEFT)) {
dir = KEY.LEFT;
}
if (Gdx.input.isKeyPressed(Input.Keys.RIGHT)) {
dir = KEY.RIGHT;
}
if (Gdx.input.isKeyJustPressed(Input.Keys.SPACE)) {
keyPressed = KEY.BOMB;
}
/* step of the 2D Game */
room.step(keyPressed, dir);
/* objects to be destroyed */
List<Objeto> destroy = new LinkedList<Objeto>();
for (Objeto obj : objetos.keySet()) {
if (!room.objetos.contains(obj)) {
destroy.add(obj);
}
}
for (Objeto obj : destroy) {
objetos.remove(obj);
}
/* creates new objects */
for (Objeto obj : room.objetos) {
obj.render(null);
if (objetos.containsKey(obj)) {
;
} else {
if (obj instanceof Bomb) {
ModelInstance model = new ModelInstance(bombModel);
model.transform.translate(0, height / 2, 0);
model.transform.translate(obj.x, 0, obj.y);
objetos.put(obj, model);
}
if (obj instanceof ExplosionPart) {
ModelInstance model = new ModelInstance(explosionModel);
model.transform.translate(0, height / 2, 0);
model.transform.translate(obj.x + width / 2, 0, obj.y + height / 2);
objetos.put(obj, model);
}
if (obj instanceof Item) {
Item i = (Item) obj;
ModelInstance model = null;
switch(i.getType()){
case SPEED:
model = new ModelInstance(itemModelS);
break;
case BOMB:
model = new ModelInstance(itemModelB);
break;
case POWER:
model = new ModelInstance(itemModelP);
break;
default:
break;
}
model.transform.translate(0, height / 2, 0);
model.transform.translate(obj.x, 0, obj.y);
objetos.put(obj, model);
}
}
}
/* updates objects' positions */
for (Map.Entry<Objeto, ModelInstance> entry : objetos.entrySet()) {
Objeto key = entry.getKey();
ModelInstance value = entry.getValue();
Point2D last = lastPos.get(key);
if (last != null) {
value.transform.translate(key.x - last.getX(), 0, key.y - last.getY());
}
}
if (room.state == STATE.DESTRUCTION || room.state == STATE.VICTORY) {
Gdx.app.exit();
}
}
@Override
public void dispose() {
bombermanModel.dispose();
planeModel.dispose();
boxModel.dispose();
bombModel.dispose();
explosionModel.dispose();
enemyModel.dispose();
room.destroy();
modelBatch.dispose();
}
}
|
package edu.uib.info310.model.imp;
import org.springframework.stereotype.Component;
import edu.uib.info310.model.Event;
import edu.uib.info310.model.Track;
@Component
public class TrackImp implements Track {
private String trackNr;
private String name;
private String length;
private String artist;
private String preview;
public String getTrackNr() {
return this.trackNr;
}
public String getName() {
return this.name;
}
public String getLength() {
return this.length;
}
public String getArtist() {
return this.artist;
}
public void setTrackNr(String trackNr) {
if(trackNr.length() == 1){
this.trackNr = "0" + trackNr;
}else{
this.trackNr = trackNr;
}
}
public void setName(String name) {
this.name = name;
}
public void setLength(String length) {
this.length = length;
}
public void setArtist(String artist) {
this.artist = artist;
}
public int compareTo(Track o) {
return this.trackNr.compareTo(o.getTrackNr());
}
public String getPreview() {
return this.preview;
}
public void setPreview(String preview) {
this.preview = preview;
}
}
|
package frc.team4215.stronghold;
import edu.wpi.first.wpilibj.Victor;
/**
* This is used to control the drive-train
*
* @author Waweru
*/
public class DriveTrain {
Victor leftMotor;
Victor rightMotor;
Victor rightMotor2;
Victor leftMotor2;
double coeff = .85;
DriveTrain(Victor leftMotor_, Victor leftMotor_2,
Victor rightMotor_, Victor rightMotor_2) {
leftMotor = leftMotor_;
rightMotor = rightMotor_;
leftMotor2 = leftMotor_2;
rightMotor2 = rightMotor_2;
}
/**
* Set Drive train speed Inputs from -1 to 1
*
* @param leftSpeed
* @param rightSpeed
*/
public void drive(double leftSpeed, double rightSpeed) {
/*
* The Victors don't respond to a voltage of less then 4%
* either direction so I provided some scaling.
*/
/*
* The scaling part is moved into a new function to simplify
* the code. - James
*/
leftSpeed = coeff*scaling(leftSpeed);
rightSpeed = coeff*scaling(rightSpeed);
leftMotor.set(-leftSpeed);
leftMotor2.set(-leftSpeed);
rightMotor.set(rightSpeed);
rightMotor2.set(rightSpeed);
}
public void driveNonScaled(double leftSpeed, double rightSpeed) {
/*
* The Victors don't respond to a voltage of less then 4%
* either direction so I provided some scaling.
*/
/*
* The scaling part is moved into a new function to simplify
* the code. - James
*/
leftSpeed = scaling(leftSpeed);
rightSpeed = scaling(rightSpeed);
leftMotor.set(-leftSpeed);
leftMotor2.set(-leftSpeed);
rightMotor.set(rightSpeed);
rightMotor2.set(rightSpeed);
}
/**
* Scaling because Victor does not response to volts less than 4%
* either direction.
*
* @param speed
* @return scaled speed
*/
private static double scaling(double speed) {
if (speed == 0) return 0d;
else return Math.signum(speed)
* ((Math.abs(speed) * .96) + .04);
}
/**
* You can use this function when left speed and right speed are
* the same.
*
* @author James
* @param speed
*/
public void drive(double speed) {
drive(speed, speed);
}
}
|
package hex.deeplearning;
import static java.lang.Double.isNaN;
import hex.FrameTask.DataInfo;
import hex.VarImp;
import water.*;
import water.api.*;
import water.api.Request.API;
import water.fvec.Frame;
import water.fvec.Vec;
import water.util.*;
import java.util.*;
/**
* The Deep Learning model
* It contains a DeepLearningModelInfo with the most up-to-date model,
* a scoring history, as well as some helpers to indicated the progress
*/
public class DeepLearningModel extends Model {
static final int API_WEAVER = 1; // This file has auto-gen'd doc & json fields
static public DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code.
@API(help="Model info", json = true)
private volatile DeepLearningModelInfo model_info;
void set_model_info(DeepLearningModelInfo mi) { model_info = mi; }
final public DeepLearningModelInfo model_info() { return model_info; }
@API(help="Job that built the model", json = true)
final private Key jobKey;
@API(help="Time to build the model", json = true)
private long run_time;
final private long start_time;
@API(help="Number of training epochs", json = true)
public double epoch_counter;
@API(help="Number of rows in training data", json = true)
public long training_rows;
@API(help = "Scoring during model building")
private Errors[] errors;
// return the most up-to-date model metrics
Errors last_scored() { return errors[errors.length-1]; }
Errors second_last_scored() { return errors[errors.length-2]; }
public final DeepLearning get_params() { return model_info.get_params(); }
public final Request2 job() { return get_params(); }
public static class Errors extends Iced {
static final int API_WEAVER = 1;
static public DocGen.FieldDoc[] DOC_FIELDS;
@API(help = "How many epochs the algorithm has processed")
public double epoch_counter;
@API(help = "How many rows the algorithm has processed")
public long training_samples;
@API(help = "How long the algorithm ran in ms")
public long training_time_ms;
//training/validation sets
@API(help = "Whether a validation set was provided")
boolean validation;
@API(help = "Number of training set samples for scoring")
public long score_training_samples;
@API(help = "Number of validation set samples for scoring")
public long score_validation_samples;
@API(help="Do classification or regression")
public boolean classification;
@API(help = "Variable importances")
VarImp variable_importances;
// classification
@API(help = "Confusion matrix on training data")
public water.api.ConfusionMatrix train_confusion_matrix;
@API(help = "Confusion matrix on validation data")
public water.api.ConfusionMatrix valid_confusion_matrix;
@API(help = "Classification error on training data")
public double train_err = 1;
@API(help = "Classification error on validation data")
public double valid_err = 1;
@API(help = "AUC on training data")
public AUC trainAUC;
@API(help = "AUC on validation data")
public AUC validAUC;
@API(help = "Hit ratio on training data")
public water.api.HitRatio train_hitratio;
@API(help = "Hit ratio on validation data")
public water.api.HitRatio valid_hitratio;
// regression
@API(help = "Training MSE")
public double train_mse = Double.POSITIVE_INFINITY;
@API(help = "Validation MSE")
public double valid_mse = Double.POSITIVE_INFINITY;
// @API(help = "Training MCE")
// public double train_mce = Double.POSITIVE_INFINITY;
// @API(help = "Validation MCE")
// public double valid_mce = Double.POSITIVE_INFINITY;
@API(help = "Time taken for scoring")
public long scoring_time;
@Override public String toString() {
StringBuilder sb = new StringBuilder();
if (classification) {
sb.append("Error on training data (misclassification)"
+ (trainAUC != null ? " [using threshold for " + trainAUC.threshold_criterion.toString().replace("_"," ") +"]: ": ": ")
+ String.format("%.2f", 100*train_err) + "%");
if (trainAUC != null) sb.append(", AUC on training data: " + String.format("%.4f", 100*trainAUC.AUC) + "%");
if (validation) sb.append("\nError on validation data (misclassification)"
+ (validAUC != null ? " [using threshold for " + validAUC.threshold_criterion.toString().replace("_"," ") +"]: ": ": ")
+ String.format("%.2f", (100*valid_err)) + "%");
if (validAUC != null) sb.append(", AUC on validation data: " + String.format("%.4f", 100*validAUC.AUC) + "%");
} else if (!Double.isInfinite(train_mse)) {
sb.append("Error on training data (MSE): " + train_mse);
if (validation) sb.append("\nError on validation data (MSE): " + valid_mse);
}
return sb.toString();
}
}
final private static class ConfMat extends hex.ConfusionMatrix {
final private double _err;
final private double _f1;
public ConfMat(double err, double f1) {
super(null);
_err=err;
_f1=f1;
}
@Override public double err() { return _err; }
@Override public double F1() { return _f1; }
@Override public double[] classErr() { return null; }
}
/** for grid search error reporting */
@Override
public hex.ConfusionMatrix cm() {
final Errors lasterror = last_scored();
if (errors == null) return null;
water.api.ConfusionMatrix cm = lasterror.validation ?
lasterror.valid_confusion_matrix :
lasterror.train_confusion_matrix;
if (cm == null || cm.cm == null) {
if (lasterror.validation) {
return new ConfMat(lasterror.valid_err, lasterror.validAUC != null ? lasterror.validAUC.F1() : 0);
} else {
return new ConfMat(lasterror.train_err, lasterror.trainAUC != null ? lasterror.trainAUC.F1() : 0);
}
}
return new hex.ConfusionMatrix(cm.cm);
}
@Override
public double mse() {
if (errors == null) return super.mse();
return last_scored().validation ? last_scored().valid_mse : last_scored().train_mse;
}
@Override
public VarImp varimp() {
if (errors == null) return null;
return last_scored().variable_importances;
}
// This describes the model, together with the parameters
// This will be shared: one per node
public static class DeepLearningModelInfo extends Iced {
static final int API_WEAVER = 1; // This file has auto-gen'd doc & json fields
static public DocGen.FieldDoc[] DOC_FIELDS; // Initialized from Auto-Gen code.
@API(help="Input data info")
final private DataInfo data_info;
public DataInfo data_info() { return data_info; }
/*cached version of data_info.coefNames() in case data_info.adaptedFrame is not available (e.g., after a checkpoint restart)*/
public String [] _featureNames;
// model is described by parameters and the following 2 arrays
private Neurons.DenseRowMatrix[] dense_row_weights; //one 2D weight matrix per layer (stored as a 1D array each)
private Neurons.DenseColMatrix[] dense_col_weights; //one 2D weight matrix per layer (stored as a 1D array each)
final private Neurons.DenseVector[] biases; //one 1D bias array per layer
// helpers for storing previous step deltas
// Note: These two arrays *could* be made transient and then initialized freshly in makeNeurons() and in DeepLearningTask.initLocal()
// But then, after each reduction, the weights would be lost and would have to restart afresh -> not *exactly* right, but close...
private Neurons.DenseRowMatrix[] dense_row_weights_momenta;
private Neurons.DenseColMatrix[] dense_col_weights_momenta;
private Neurons.DenseVector[] biases_momenta;
// helpers for AdaDelta
private Neurons.DenseRowMatrix[] dense_row_ada_dx;
private Neurons.DenseRowMatrix[] dense_row_ada_g;
private Neurons.DenseColMatrix[] dense_col_ada_dx;
private Neurons.DenseColMatrix[] dense_col_ada_g;
private Neurons.DenseVector[] biases_ada_dx;
private Neurons.DenseVector[] biases_ada_g;
// compute model size (number of model parameters required for making predictions)
// momenta are not counted here, but they are needed for model building
public long size() {
long siz = 0;
for (Neurons.Matrix w : dense_row_weights) if (w != null) siz += w.size();
for (Neurons.Matrix w : dense_col_weights) if (w != null) siz += w.size();
for (Neurons.Vector b : biases) siz += b.size();
return siz;
}
// accessors to (shared) weights and biases - those will be updated racily (c.f. Hogwild!)
boolean has_momenta() { return get_params().momentum_start != 0 || get_params().momentum_stable != 0; }
boolean adaDelta() { return get_params().adaptive_rate; }
public final Neurons.Matrix get_weights(int i) { return dense_row_weights[i] == null ? dense_col_weights[i] : dense_row_weights[i]; }
public final Neurons.DenseVector get_biases(int i) { return biases[i]; }
public final Neurons.Matrix get_weights_momenta(int i) { return dense_row_weights_momenta[i] == null ? dense_col_weights_momenta[i] : dense_row_weights_momenta[i]; }
public final Neurons.DenseVector get_biases_momenta(int i) { return biases_momenta[i]; }
public final Neurons.Matrix get_ada_dx(int i) { return dense_row_ada_dx[i] == null ? dense_col_ada_dx[i] : dense_row_ada_dx[i]; }
public final Neurons.Matrix get_ada_g(int i) { return dense_row_ada_g[i] == null ? dense_col_ada_g[i] : dense_row_ada_g[i]; }
public final Neurons.DenseVector get_biases_ada_g(int i) { return biases_ada_g[i]; }
public final Neurons.DenseVector get_biases_ada_dx(int i) { return biases_ada_dx[i]; }
@API(help = "Model parameters", json = true)
final private DeepLearning parameters;
public final DeepLearning get_params() { return parameters; }
@API(help = "Mean rate", json = true)
private float[] mean_rate;
@API(help = "RMS rate", json = true)
private float[] rms_rate;
@API(help = "Mean bias", json = true)
private float[] mean_bias;
@API(help = "RMS bias", json = true)
private float[] rms_bias;
@API(help = "Mean weight", json = true)
private float[] mean_weight;
@API(help = "RMS weight", json = true)
public float[] rms_weight;
@API(help = "Unstable", json = true)
private volatile boolean unstable = false;
public boolean unstable() { return unstable; }
public void set_unstable() { if (!unstable) computeStats(); unstable = true; }
@API(help = "Processed samples", json = true)
private long processed_global;
public synchronized long get_processed_global() { return processed_global; }
public synchronized void set_processed_global(long p) { processed_global = p; }
public synchronized void add_processed_global(long p) { processed_global += p; }
private long processed_local;
public synchronized long get_processed_local() { return processed_local; }
public synchronized void set_processed_local(long p) { processed_local = p; }
public synchronized void add_processed_local(long p) { processed_local += p; }
public synchronized long get_processed_total() { return processed_global + processed_local; }
// package local helpers
final int[] units; //number of neurons per layer, extracted from parameters and from datainfo
public DeepLearningModelInfo(final DeepLearning params, final DataInfo dinfo) {
data_info = dinfo;
final int num_input = dinfo.fullN();
final int num_output = params.classification ? dinfo._adaptedFrame.domains()[dinfo._adaptedFrame.domains().length-1].length : 1;
assert(num_input > 0);
assert(num_output > 0);
parameters = params;
if (has_momenta() && adaDelta()) throw new IllegalArgumentException("Cannot have non-zero momentum and adaptive rate at the same time.");
final int layers=get_params().hidden.length;
// units (# neurons for each layer)
units = new int[layers+2];
units[0] = num_input;
System.arraycopy(get_params().hidden, 0, units, 1, layers);
units[layers+1] = num_output;
// weights (to connect layers)
dense_row_weights = new Neurons.DenseRowMatrix[layers+1];
dense_col_weights = new Neurons.DenseColMatrix[layers+1];
// decide format of weight matrices row-major or col-major
boolean input_col_major = false; //FIXME: should be automatically tuned for whichever is faster
if (input_col_major) dense_col_weights[0] = new Neurons.DenseColMatrix(units[1], units[0]);
else dense_row_weights[0] = new Neurons.DenseRowMatrix(units[1], units[0]);
for (int i=1; i<=layers; ++i)
dense_row_weights[i] = new Neurons.DenseRowMatrix(units[i+1] /*rows*/, units[i] /*cols*/);
// biases (only for hidden layers and output layer)
biases = new Neurons.DenseVector[layers+1];
for (int i=0; i<=layers; ++i) biases[i] = new Neurons.DenseVector(units[i+1]);
fillHelpers();
// for diagnostics
mean_rate = new float[units.length];
rms_rate = new float[units.length];
mean_bias = new float[units.length];
rms_bias = new float[units.length];
mean_weight = new float[units.length];
rms_weight = new float[units.length];
}
void fillHelpers() {
if (has_momenta()) {
dense_row_weights_momenta = new Neurons.DenseRowMatrix[dense_row_weights.length];
dense_col_weights_momenta = new Neurons.DenseColMatrix[dense_col_weights.length];
if (dense_row_weights[0] != null)
dense_row_weights_momenta[0] = new Neurons.DenseRowMatrix(units[1], units[0]);
else
dense_col_weights_momenta[0] = new Neurons.DenseColMatrix(units[1], units[0]);
for (int i=1; i<dense_row_weights_momenta.length; ++i) dense_row_weights_momenta[i] = new Neurons.DenseRowMatrix(units[i+1], units[i]);
biases_momenta = new Neurons.DenseVector[biases.length];
for (int i=0; i<biases_momenta.length; ++i) biases_momenta[i] = new Neurons.DenseVector(units[i+1]);
}
else if (adaDelta()) {
dense_row_ada_dx = new Neurons.DenseRowMatrix[dense_row_weights.length];
dense_row_ada_g = new Neurons.DenseRowMatrix[dense_row_weights.length];
dense_col_ada_dx = new Neurons.DenseColMatrix[dense_col_weights.length];
dense_col_ada_g = new Neurons.DenseColMatrix[dense_col_weights.length];
//AdaGrad
if (dense_row_weights[0] != null) {
dense_row_ada_dx[0] = new Neurons.DenseRowMatrix(units[1], units[0]);
dense_row_ada_g[0] = new Neurons.DenseRowMatrix(units[1], units[0]);
} else {
dense_col_ada_dx[0] = new Neurons.DenseColMatrix(units[1], units[0]);
dense_col_ada_g[0] = new Neurons.DenseColMatrix(units[1], units[0]);
}
for (int i=1; i<dense_row_ada_dx.length; ++i) {
dense_row_ada_dx[i] = new Neurons.DenseRowMatrix(units[i+1], units[i]);
dense_row_ada_g[i] = new Neurons.DenseRowMatrix(units[i+1], units[i]);
}
biases_ada_dx = new Neurons.DenseVector[biases.length];
biases_ada_g = new Neurons.DenseVector[biases.length];
for (int i=0; i<biases_ada_dx.length; ++i) {
biases_ada_dx[i] = new Neurons.DenseVector(units[i+1]);
biases_ada_g[i] = new Neurons.DenseVector(units[i+1]);
}
}
}
@Override public String toString() {
StringBuilder sb = new StringBuilder();
if (get_params().diagnostics && !get_params().quiet_mode) {
Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(this);
sb.append("Status of Neuron Layers:\n");
sb.append("# Units Type Dropout L1 L2 " + (get_params().adaptive_rate ? " Rate (Mean,RMS) " : " Rate Momentum") + " Weight (Mean, RMS) Bias (Mean,RMS)\n");
final String format = "%7g";
for (int i=0; i<neurons.length; ++i) {
sb.append((i+1) + " " + String.format("%6d", neurons[i].units)
+ " " + String.format("%16s", neurons[i].getClass().getSimpleName()));
if (i == 0) {
sb.append(" " + formatPct(neurons[i].params.input_dropout_ratio) + " \n");
continue;
}
else if (i < neurons.length-1) {
sb.append(" " + formatPct(neurons[i].params.hidden_dropout_ratios[i-1]) + " ");
} else {
sb.append(" ");
}
sb.append(
" " + String.format("%5f", neurons[i].params.l1)
+ " " + String.format("%5f", neurons[i].params.l2)
+ " " + (get_params().adaptive_rate ? (" (" + String.format(format, mean_rate[i]) + ", " + String.format(format, rms_rate[i]) + ")" )
: (String.format("%10g", neurons[i].rate(get_processed_total())) + " " + String.format("%5f", neurons[i].momentum(get_processed_total()))))
+ " (" + String.format(format, mean_weight[i])
+ ", " + String.format(format, rms_weight[i]) + ")"
+ " (" + String.format(format, mean_bias[i])
+ ", " + String.format(format, rms_bias[i]) + ")\n");
}
}
return sb.toString();
}
// DEBUGGING
public String toStringAll() {
StringBuilder sb = new StringBuilder();
sb.append(toString());
// sb.append(weights.toString());
// for (int i=0; i<weights.length; ++i)
// sb.append("\nweights["+i+"][]="+Arrays.toString(weights[i].raw()));
// for (int i=0; i<biases.length; ++i)
// sb.append("\nbiases["+i+"][]="+Arrays.toString(biases[i].raw()));
// if (weights_momenta != null) {
// for (int i=0; i<weights_momenta.length; ++i)
// sb.append("\nweights_momenta["+i+"][]="+Arrays.toString(weights_momenta[i].raw()));
if (biases_momenta != null) {
for (int i=0; i<biases_momenta.length; ++i)
sb.append("\nbiases_momenta["+i+"][]="+Arrays.toString(biases_momenta[i].raw()));
}
sb.append("\nunits[]="+Arrays.toString(units));
sb.append("\nprocessed global: "+get_processed_global());
sb.append("\nprocessed local: "+get_processed_local());
sb.append("\nprocessed total: " + get_processed_total());
sb.append("\n");
return sb.toString();
}
void initializeMembers() {
if (get_params().variable_importances) _featureNames = data_info().coefNames();
randomizeWeights();
//TODO: determine good/optimal/best initialization scheme for biases
// hidden layers
for (int i=0; i<get_params().hidden.length; ++i) {
if (get_params().activation == DeepLearning.Activation.Rectifier
|| get_params().activation == DeepLearning.Activation.RectifierWithDropout
|| get_params().activation == DeepLearning.Activation.Maxout
|| get_params().activation == DeepLearning.Activation.MaxoutWithDropout
) {
// Arrays.fill(biases[i], 1.); //old behavior
Arrays.fill(biases[i].raw(), i == 0 ? 0.5f : 1f); //new behavior, might be slightly better
}
else if (get_params().activation == DeepLearning.Activation.Tanh || get_params().activation == DeepLearning.Activation.TanhWithDropout) {
Arrays.fill(biases[i].raw(), 0f);
}
}
Arrays.fill(biases[biases.length-1].raw(), 0f); //output layer
}
public void add(DeepLearningModelInfo other) {
for (int i=0;i<dense_row_weights.length;++i)
Utils.add(get_weights(i).raw(), other.get_weights(i).raw());
for (int i=0;i<biases.length;++i) Utils.add(biases[i].raw(), other.biases[i].raw());
if (has_momenta()) {
assert(other.has_momenta());
for (int i=0;i<dense_row_weights_momenta.length;++i)
Utils.add(get_weights_momenta(i).raw(), other.get_weights_momenta(i).raw());
for (int i=0;i<biases_momenta.length;++i)
Utils.add(biases_momenta[i].raw(), other.biases_momenta[i].raw());
}
if (adaDelta()) {
assert(other.adaDelta());
for (int i=0;i<dense_row_ada_dx.length;++i) {
Utils.add(get_ada_dx(i).raw(), other.get_ada_dx(i).raw());
Utils.add(get_ada_g(i).raw(), other.get_ada_g(i).raw());
}
}
add_processed_local(other.get_processed_local());
}
protected void div(float N) {
for (int i=0; i<dense_row_weights.length; ++i)
Utils.div(get_weights(i).raw(), N);
for (Neurons.Vector bias : biases) Utils.div(bias.raw(), N);
if (has_momenta()) {
for (int i=0; i<dense_row_weights_momenta.length; ++i)
Utils.div(get_weights_momenta(i).raw(), N);
for (Neurons.Vector bias_momenta : biases_momenta) Utils.div(bias_momenta.raw(), N);
}
if (adaDelta()) {
for (int i=0;i<dense_row_ada_dx.length;++i) {
Utils.div(get_ada_dx(i).raw(), N);
Utils.div(get_ada_g(i).raw(), N);
}
}
}
double uniformDist(Random rand, double min, double max) {
return min + rand.nextFloat() * (max - min);
}
void randomizeWeights() {
for (int w=0; w<dense_row_weights.length; ++w) {
final Random rng = water.util.Utils.getDeterRNG(get_params().seed + 0xBAD5EED + w+1); //to match NeuralNet behavior
final double range = Math.sqrt(6. / (units[w] + units[w+1]));
for( int i = 0; i < get_weights(w).rows(); i++ ) {
for( int j = 0; j < get_weights(w).cols(); j++ ) {
if (get_params().initial_weight_distribution == DeepLearning.InitialWeightDistribution.UniformAdaptive) {
if (w==dense_row_weights.length-1 && get_params().classification)
get_weights(w).set(i,j, (float)(4.*uniformDist(rng, -range, range))); //Softmax might need an extra factor 4, since it's like a sigmoid
else
get_weights(w).set(i,j, (float)uniformDist(rng, -range, range));
}
else if (get_params().initial_weight_distribution == DeepLearning.InitialWeightDistribution.Uniform) {
get_weights(w).set(i,j, (float)uniformDist(rng, -get_params().initial_weight_scale, parameters.initial_weight_scale));
}
else if (get_params().initial_weight_distribution == DeepLearning.InitialWeightDistribution.Normal) {
get_weights(w).set(i,j, (float)(rng.nextGaussian() * get_params().initial_weight_scale));
}
}
}
}
}
// TODO: Add "subset randomize" function
// int count = Math.min(15, _previous.units);
// double min = -.1f, max = +.1f;
// //double min = -1f, max = +1f;
// for( int o = 0; o < units; o++ ) {
// for( int n = 0; n < count; n++ ) {
// int i = rand.nextInt(_previous.units);
// int w = o * _previous.units + i;
// _w[w] = uniformDist(rand, min, max);
/**
* Compute Variable Importance, based on
* GEDEON: DATA MINING OF INPUTS: ANALYSING MAGNITUDE AND FUNCTIONAL MEASURES
* @return variable importances for input features
*/
public float[] computeVariableImportances() {
float[] vi = new float[units[0]];
Arrays.fill(vi, 0f);
float[][] Qik = new float[units[0]][units[2]]; //importance of input i on output k
float[] sum_wj = new float[units[1]]; //sum of incoming weights into first hidden layer
float[] sum_wk = new float[units[2]]; //sum of incoming weights into output layer (or second hidden layer)
for (float[] Qi : Qik) Arrays.fill(Qi, 0f);
Arrays.fill(sum_wj, 0f);
Arrays.fill(sum_wk, 0f);
// compute sum of absolute incoming weights
for( int j = 0; j < units[1]; j++ ) {
for( int i = 0; i < units[0]; i++ ) {
float wij = get_weights(0).get(j, i);
sum_wj[j] += Math.abs(wij);
}
}
for( int k = 0; k < units[2]; k++ ) {
for( int j = 0; j < units[1]; j++ ) {
float wjk = get_weights(1).get(k,j);
sum_wk[k] += Math.abs(wjk);
}
}
// compute importance of input i on output k as product of connecting weights going through j
for( int i = 0; i < units[0]; i++ ) {
for( int k = 0; k < units[2]; k++ ) {
for( int j = 0; j < units[1]; j++ ) {
float wij = get_weights(0).get(j,i);
float wjk = get_weights(1).get(k,j);
//Qik[i][k] += Math.abs(wij)/sum_wj[j] * wjk; //Wong,Gedeon,Taggart '95
Qik[i][k] += Math.abs(wij)/sum_wj[j] * Math.abs(wjk)/sum_wk[k]; //Gedeon '97
}
}
}
// normalize Qik over all outputs k
for( int k = 0; k < units[2]; k++ ) {
float sumQk = 0;
for( int i = 0; i < units[0]; i++ ) sumQk += Qik[i][k];
for( int i = 0; i < units[0]; i++ ) Qik[i][k] /= sumQk;
}
// importance for feature i is the sum over k of i->k importances
for( int i = 0; i < units[0]; i++ ) vi[i] = Utils.sum(Qik[i]);
//normalize importances such that max(vi) = 1
Utils.div(vi, Utils.maxValue(vi));
return vi;
}
// compute stats on all nodes
public void computeStats() {
float[][] rate = get_params().adaptive_rate ? new float[units.length-1][] : null;
for( int y = 1; y < units.length; y++ ) {
mean_rate[y] = rms_rate[y] = 0;
mean_bias[y] = rms_bias[y] = 0;
mean_weight[y] = rms_weight[y] = 0;
for(int u = 0; u < biases[y-1].size(); u++) {
mean_bias[y] += biases[y-1].get(u);
}
if (rate != null) rate[y-1] = new float[get_weights(y-1).raw().length];
for(int u = 0; u < get_weights(y-1).raw().length; u++) {
mean_weight[y] += get_weights(y-1).raw()[u];
if (rate != null) {
// final float RMS_dx = (float)Math.sqrt(ada[y-1][2*u]+(float)get_params().epsilon);
// final float invRMS_g = (float)(1/Math.sqrt(ada[y-1][2*u+1]+(float)get_params().epsilon));
final float RMS_dx = Utils.approxSqrt(get_ada_dx(y-1).raw()[u]+(float)get_params().epsilon);
final float invRMS_g = Utils.approxInvSqrt(get_ada_g(y-1).raw()[u]+(float)get_params().epsilon);
rate[y-1][u] = RMS_dx*invRMS_g; //not exactly right, RMS_dx should be from the previous time step -> but close enough for diagnostics.
mean_rate[y] += rate[y-1][u];
}
}
mean_bias[y] /= biases[y-1].size();
mean_weight[y] /= get_weights(y-1).size();
if (rate != null) mean_rate[y] /= rate[y-1].length;
for(int u = 0; u < biases[y-1].size(); u++) {
final double db = biases[y-1].get(u) - mean_bias[y];
rms_bias[y] += db * db;
}
for(int u = 0; u < get_weights(y-1).size(); u++) {
final double dw = get_weights(y-1).raw()[u] - mean_weight[y];
rms_weight[y] += dw * dw;
if (rate != null) {
final double drate = rate[y-1][u] - mean_rate[y];
rms_rate[y] += drate * drate;
}
}
rms_bias[y] = Utils.approxSqrt(rms_bias[y]/biases[y-1].size());
rms_weight[y] = Utils.approxSqrt(rms_weight[y]/get_weights(y-1).size());
if (rate != null) rms_rate[y] = Utils.approxSqrt(rms_rate[y]/rate[y-1].length);
// rms_bias[y] = (float)Math.sqrt(rms_bias[y]/biases[y-1].length);
// rms_weight[y] = (float)Math.sqrt(rms_weight[y]/weights[y-1].length);
// if (rate != null) rms_rate[y] = (float)Math.sqrt(rms_rate[y]/rate[y-1].length);
// Abort the run if weights or biases are unreasonably large (Note that all input values are normalized upfront)
// This can happen with Rectifier units when L1/L2/max_w2 are all set to 0, especially when using more than 1 hidden layer.
final double thresh = 1e10;
unstable |= mean_bias[y] > thresh || isNaN(mean_bias[y])
|| rms_bias[y] > thresh || isNaN(rms_bias[y])
|| mean_weight[y] > thresh || isNaN(mean_weight[y])
|| rms_weight[y] > thresh || isNaN(rms_weight[y]);
}
}
}
/**
* Constructor to restart from a checkpointed model
* @param cp Checkpoint to restart from
* @param selfKey New destination key for the model
* @param jobKey New job key (job which updates the model)
*/
public DeepLearningModel(DeepLearningModel cp, Key selfKey, Key jobKey) {
super(selfKey, cp._dataKey, cp.model_info().data_info()._adaptedFrame, cp._priorClassDist);
this.jobKey = jobKey;
model_info = (DeepLearningModelInfo)cp.model_info.clone();
get_params().destination_key = selfKey;
get_params().job_key = jobKey;
start_time = cp.start_time;
run_time = cp.run_time;
errors = cp.errors.clone();
training_rows = cp.training_rows; //copy the value to display the right number on the model page before training has started
get_params().start_time = System.currentTimeMillis(); //for displaying the model progress
_timeLastScoreEnter = System.currentTimeMillis();
_timeLastScoreStart = 0;
_timeLastScoreEnd = 0;
_timeLastPrintStart = 0;
}
public DeepLearningModel(Key selfKey, Key jobKey, Key dataKey, DataInfo dinfo, DeepLearning params, float[] priorDist) {
super(selfKey, dataKey, dinfo._adaptedFrame, priorDist);
this.jobKey = jobKey;
run_time = 0;
start_time = System.currentTimeMillis();
_timeLastScoreEnter = start_time;
model_info = new DeepLearningModelInfo(params, dinfo);
errors = new Errors[1];
errors[0] = new Errors();
errors[0].validation = (params.validation != null);
}
private long _timeLastScoreEnter; //not transient: needed for HTML display page
transient private long _timeLastScoreStart;
transient private long _timeLastScoreEnd;
transient private long _timeLastPrintStart;
/**
*
* @param train training data from which the model is built (for epoch counting only)
* @param ftrain potentially downsampled training data for scoring
* @param ftest potentially downsampled validation data for scoring
* @param job_key key of the owning job
* @return true if model building is ongoing
*/
boolean doScoring(Frame train, Frame ftrain, Frame ftest, Key job_key, Job.ValidatedJob.Response2CMAdaptor vadaptor) {
try {
final long now = System.currentTimeMillis();
epoch_counter = (float)model_info().get_processed_total()/train.numRows();
run_time += now-_timeLastScoreEnter;
_timeLastScoreEnter = now;
boolean keep_running = (epoch_counter < get_params().epochs);
final long sinceLastScore = now -_timeLastScoreStart;
final long sinceLastPrint = now -_timeLastPrintStart;
final long samples = model_info().get_processed_total();
if (!keep_running || sinceLastPrint > get_params().score_interval*1000) {
_timeLastPrintStart = now;
Log.info("Training time: " + PrettyPrint.msecs(run_time, true)
+ ". Processed " + String.format("%,d", samples) + " samples" + " (" + String.format("%.3f", epoch_counter) + " epochs)."
+ " Speed: " + String.format("%.3f", 1000.*samples/run_time) + " samples/sec.");
}
// this is potentially slow - only do every so often
if( !keep_running ||
(sinceLastScore > get_params().score_interval*1000 //don't score too often
&&(double)(_timeLastScoreEnd-_timeLastScoreStart)/sinceLastScore < get_params().score_duty_cycle) ) { //duty cycle
final boolean printme = !get_params().quiet_mode;
if (printme) Log.info("Scoring the model.");
_timeLastScoreStart = now;
// compute errors
Errors err = new Errors();
err.classification = isClassifier();
assert(err.classification == get_params().classification);
err.training_time_ms = run_time;
err.epoch_counter = epoch_counter;
err.validation = ftest != null;
err.training_samples = model_info().get_processed_total();
err.score_training_samples = ftrain.numRows();
err.train_confusion_matrix = new ConfusionMatrix();
final int hit_k = Math.min(nclasses(), get_params().max_hit_ratio_k);
if (err.classification && nclasses()==2) err.trainAUC = new AUC();
if (err.classification && nclasses() > 2 && hit_k > 0) {
err.train_hitratio = new HitRatio();
err.train_hitratio.set_max_k(hit_k);
}
if (get_params().diagnostics) model_info().computeStats();
final String m = model_info().toString();
if (m.length() > 0) Log.info(m);
final Frame trainPredict = score(ftrain, false);
final double trainErr = calcError(ftrain, ftrain.lastVec(), trainPredict, trainPredict, "training",
printme, get_params().max_confusion_matrix_size, err.train_confusion_matrix, err.trainAUC, err.train_hitratio);
if (isClassifier()) err.train_err = trainErr;
else err.train_mse = trainErr;
trainPredict.delete();
if (err.validation) {
assert ftest != null;
err.score_validation_samples = ftest.numRows();
err.valid_confusion_matrix = new ConfusionMatrix();
if (err.classification && nclasses()==2) err.validAUC = new AUC();
if (err.classification && nclasses() > 2 && hit_k > 0) {
err.valid_hitratio = new HitRatio();
err.valid_hitratio.set_max_k(hit_k);
}
final boolean adaptCM = (isClassifier() && vadaptor.needsAdaptation2CM());
final String adaptRespName = vadaptor.adaptedValidationResponse(responseName());
Vec adaptCMresp = null;
if (adaptCM) {
Vec[] v = ftest.vecs();
assert(ftest.find(adaptRespName) == v.length-1); //make sure to have (adapted) response in the test set
adaptCMresp = ftest.remove(v.length-1); //model would remove any extra columns anyway (need to keep it here for later)
}
final Frame validPredict = score(ftest, adaptCM);
final Frame hitratio_validPredict = new Frame(validPredict);
// Adapt output response domain, in case validation domain is different from training domain
// Note: doesn't change predictions, just the *possible* label domain
if (adaptCM) {
assert(adaptCMresp != null);
assert(ftest.find(adaptRespName) == -1);
ftest.add(adaptRespName, adaptCMresp);
final Vec CMadapted = vadaptor.adaptModelResponse2CM(validPredict.vecs()[0]);
validPredict.replace(0, CMadapted); //replace label
validPredict.add("to_be_deleted", CMadapted); //keep the Vec around to be deleted later (no leak)
}
final double validErr = calcError(ftest, ftest.lastVec(), validPredict, hitratio_validPredict, "validation",
printme, get_params().max_confusion_matrix_size, err.valid_confusion_matrix, err.validAUC, err.valid_hitratio);
if (isClassifier()) err.valid_err = validErr;
else err.valid_mse = validErr;
validPredict.delete();
}
if (get_params().variable_importances) {
if (!get_params().quiet_mode) Log.info("Computing variable importances.");
final float [] vi = model_info().computeVariableImportances();
err.variable_importances = new VarImp(vi, Arrays.copyOfRange(model_info()._featureNames, 0, vi.length));
}
// keep output JSON small
if (errors.length > 2) {
if (second_last_scored().trainAUC != null) second_last_scored().trainAUC.clear();
if (second_last_scored().validAUC != null) second_last_scored().validAUC.clear();
second_last_scored().variable_importances = null;
}
// only keep confusion matrices for the last step if there are fewer than specified number of output classes
if (err.train_confusion_matrix.cm != null
&& err.train_confusion_matrix.cm.length >= get_params().max_confusion_matrix_size) {
err.train_confusion_matrix = null;
err.valid_confusion_matrix = null;
}
_timeLastScoreEnd = System.currentTimeMillis();
err.scoring_time = System.currentTimeMillis() - now;
// enlarge the error array by one, push latest score back
if (errors == null) {
errors = new Errors[]{err};
} else {
Errors[] err2 = new Errors[errors.length+1];
System.arraycopy(errors, 0, err2, 0, errors.length);
err2[err2.length-1] = err;
errors = err2;
}
// print the freshly scored model to ASCII
for (String s : toString().split("\n")) Log.info(s);
if (printme) Log.info("Time taken for scoring and diagnostics: " + PrettyPrint.msecs(err.scoring_time, true));
}
if (model_info().unstable()) {
Log.err("Canceling job since the model is unstable (exponential growth observed).");
Log.err("Try a bounded activation function or regularization with L1, L2 or max_w2 and/or use a smaller learning rate or faster annealing.");
keep_running = false;
} else if ( (isClassifier() && last_scored().train_err <= get_params().classification_stop)
|| (!isClassifier() && last_scored().train_mse <= get_params().regression_stop) ) {
Log.info("Achieved requested predictive accuracy on the training data. Model building completed.");
keep_running = false;
}
update(job_key);
// System.out.println(this);
return keep_running;
}
catch (Exception ex) {
return false;
}
}
@Override public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(model_info.toString());
sb.append(last_scored().toString());
return sb.toString();
}
public String toStringAll() {
StringBuilder sb = new StringBuilder();
sb.append(model_info.toStringAll());
sb.append(last_scored().toString());
return sb.toString();
}
/**
* Predict from raw double values representing
* @param data raw array containing categorical values (horizontalized to 1,0,0,1,0,0 etc.) and numerical values (0.35,1.24,5.3234,etc), both can contain NaNs
* @param preds predicted label and per-class probabilities (for classification), predicted target (regression), can contain NaNs
* @return preds, can contain NaNs
*/
@Override public float[] score0(double[] data, float[] preds) {
if (model_info().unstable()) {
throw new UnsupportedOperationException("Trying to predict with an unstable model.");
}
Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info);
((Neurons.Input)neurons[0]).setInput(-1, data);
DeepLearningTask.step(-1, neurons, model_info, false, null);
float[] out = neurons[neurons.length - 1]._a.raw();
if (isClassifier()) {
assert(preds.length == out.length+1);
for (int i=0; i<preds.length-1; ++i) {
preds[i+1] = out[i];
if (Float.isNaN(preds[i+1])) throw new RuntimeException("Predicted class probability NaN!");
}
preds[0] = ModelUtils.getPrediction(preds, data);
} else {
assert(preds.length == 1 && out.length == 1);
if (model_info().data_info()._normRespMul != null)
preds[0] = (float)(out[0] / model_info().data_info()._normRespMul[0] + model_info().data_info()._normRespSub[0]);
else
preds[0] = out[0];
if (Float.isNaN(preds[0])) throw new RuntimeException("Predicted regression target NaN!");
}
return preds;
}
public boolean generateHTML(String title, StringBuilder sb) {
if (_key == null) {
DocGen.HTML.title(sb, "No model yet");
return true;
}
final String mse_format = "%g";
// final String cross_entropy_format = "%2.6f";
// stats for training and validation
final Errors error = last_scored();
DocGen.HTML.title(sb, title);
job().toHTML(sb);
final Key val_key = get_params().validation != null ? get_params().validation._key : null;
sb.append("<div class='alert'>Actions: "
+ (Job.isRunning(jobKey) ? "<i class=\"icon-stop\"></i>" + Cancel.link(jobKey, "Stop training") + ", " : "")
+ Inspect2.link("Inspect training data (" + _dataKey + ")", _dataKey) + ", "
+ (val_key != null ? (Inspect2.link("Inspect validation data (" + val_key + ")", val_key) + ", ") : "")
+ water.api.Predict.link(_key, "Score on dataset") + ", "
+ DeepLearning.link(_dataKey, "Compute new model", null, responseName(), val_key) + ", "
+ (Job.isEnded(jobKey) ? "<i class=\"icon-play\"></i>" + DeepLearning.link(_dataKey, "Continue training this model", _key, responseName(), val_key) : "")
+ "</div>");
DocGen.HTML.paragraph(sb, "Model Key: " + _key);
DocGen.HTML.paragraph(sb, "Job Key: " + jobKey);
DocGen.HTML.paragraph(sb, "Model type: " + (get_params().classification ? " Classification" : " Regression") + ", predicting: " + responseName());
DocGen.HTML.paragraph(sb, "Number of model parameters (weights/biases): " + String.format("%,d", model_info().size()));
if (model_info.unstable()) {
final String msg = "Job was aborted due to observed numerical instability (exponential growth)."
+ " Try a bounded activation function or regularization with L1, L2 or max_w2 and/or use a smaller learning rate or faster annealing.";
DocGen.HTML.section(sb, "=======================================================================================");
DocGen.HTML.section(sb, msg);
DocGen.HTML.section(sb, "=======================================================================================");
}
DocGen.HTML.title(sb, "Progress");
// update epoch counter every time the website is displayed
epoch_counter = training_rows > 0 ? (float)model_info().get_processed_total()/training_rows : 0;
final double progress = get_params().progress();
if (get_params() != null && get_params().diagnostics) {
DocGen.HTML.section(sb, "Status of Neuron Layers");
sb.append("<table class='table table-striped table-bordered table-condensed'>");
sb.append("<tr>");
sb.append("<th>").append("#").append("</th>");
sb.append("<th>").append("Units").append("</th>");
sb.append("<th>").append("Type").append("</th>");
sb.append("<th>").append("Dropout").append("</th>");
sb.append("<th>").append("L1").append("</th>");
sb.append("<th>").append("L2").append("</th>");
if (get_params().adaptive_rate) {
sb.append("<th>").append("Rate (Mean, RMS)").append("</th>");
} else {
sb.append("<th>").append("Rate").append("</th>");
sb.append("<th>").append("Momentum").append("</th>");
}
sb.append("<th>").append("Weight (Mean, RMS)").append("</th>");
sb.append("<th>").append("Bias (Mean, RMS)").append("</th>");
sb.append("</tr>");
Neurons[] neurons = DeepLearningTask.makeNeuronsForTesting(model_info()); //link the weights to the neurons, for easy access
for (int i=0; i<neurons.length; ++i) {
sb.append("<tr>");
sb.append("<td>").append("<b>").append(i+1).append("</b>").append("</td>");
sb.append("<td>").append("<b>").append(neurons[i].units).append("</b>").append("</td>");
sb.append("<td>").append(neurons[i].getClass().getSimpleName()).append("</td>");
if (i == 0) {
sb.append("<td>");
sb.append(formatPct(neurons[i].params.input_dropout_ratio));
sb.append("</td>");
sb.append("<td></td>");
sb.append("<td></td>");
sb.append("<td></td>");
if (!get_params().adaptive_rate) sb.append("<td></td>");
sb.append("<td></td>");
sb.append("<td></td>");
sb.append("</tr>");
continue;
}
else if (i < neurons.length-1) {
sb.append("<td>");
sb.append(formatPct(neurons[i].params.hidden_dropout_ratios[i-1]));
sb.append("</td>");
} else {
sb.append("<td></td>");
}
final String format = "%g";
sb.append("<td>").append(neurons[i].params.l1).append("</td>");
sb.append("<td>").append(neurons[i].params.l2).append("</td>");
if (get_params().adaptive_rate) {
sb.append("<td>(").append(String.format(format, model_info.mean_rate[i])).
append(", ").append(String.format(format, model_info.rms_rate[i])).append(")</td>");
} else {
sb.append("<td>").append(String.format("%.5g", neurons[i].rate(error.training_samples))).append("</td>");
sb.append("<td>").append(String.format("%.5f", neurons[i].momentum(error.training_samples))).append("</td>");
}
sb.append("<td>(").append(String.format(format, model_info.mean_weight[i])).
append(", ").append(String.format(format, model_info.rms_weight[i])).append(")</td>");
sb.append("<td>(").append(String.format(format, model_info.mean_bias[i])).
append(", ").append(String.format(format, model_info.rms_bias[i])).append(")</td>");
sb.append("</tr>");
}
sb.append("</table>");
}
if (isClassifier()) {
DocGen.HTML.section(sb, "Classification error on training data: " + formatPct(error.train_err));
// DocGen.HTML.section(sb, "Training cross entropy: " + String.format(cross_entropy_format, error.train_mce));
if(error.validation) {
DocGen.HTML.section(sb, "Classification error on validation data: " + formatPct(error.valid_err));
// DocGen.HTML.section(sb, "Validation mean cross entropy: " + String.format(cross_entropy_format, error.valid_mce));
}
} else {
DocGen.HTML.section(sb, "MSE on training data: " + String.format(mse_format, error.train_mse));
if(error.validation) {
DocGen.HTML.section(sb, "MSE on validation data: " + String.format(mse_format, error.valid_mse));
}
}
DocGen.HTML.paragraph(sb, "Training samples: " + String.format("%,d", model_info().get_processed_total()));
DocGen.HTML.paragraph(sb, "Epochs: " + String.format("%.3f", epoch_counter) + " / " + String.format("%.3f", get_params().epochs));
int cores = 0; for (H2ONode n : H2O.CLOUD._memary) cores += n._heartbeat._num_cpus;
DocGen.HTML.paragraph(sb, "Number of compute nodes: " + (model_info.get_params().single_node_mode ? ("1 (" + H2O.NUMCPUS + " threads)") : (H2O.CLOUD.size() + " (" + cores + " threads)")));
DocGen.HTML.paragraph(sb, "Training samples per iteration: " + String.format("%,d", get_params().actual_train_samples_per_iteration));
final boolean isEnded = Job.isEnded(get_params().self());
final long time_so_far = isEnded ? run_time : run_time + System.currentTimeMillis() - _timeLastScoreEnter;
if (time_so_far > 0) {
DocGen.HTML.paragraph(sb, "Training speed: " + String.format("%,d", model_info().get_processed_total() * 1000 / time_so_far) + " samples/s");
}
DocGen.HTML.paragraph(sb, "Training time: " + PrettyPrint.msecs(time_so_far, true));
if (progress > 0 && !isEnded)
DocGen.HTML.paragraph(sb, "Estimated time left: " +PrettyPrint.msecs((long)(time_so_far*(1-progress)/progress), true));
long score_train = error.score_training_samples;
long score_valid = error.score_validation_samples;
final boolean fulltrain = score_train==0 || score_train == training_rows;
final boolean fullvalid = score_valid==0 || score_valid == get_params().validation.numRows();
final String toolarge = " Confusion matrix not shown here - too large: number of classes (" + model_info.units[model_info.units.length-1]
+ ") is greater than the specified limit of " + get_params().max_confusion_matrix_size + ".";
boolean smallenough = model_info.units[model_info.units.length-1] <= get_params().max_confusion_matrix_size;
if (isClassifier()) {
// print AUC
if (error.validAUC != null) {
error.validAUC.toHTML(sb);
}
else if (error.trainAUC != null) {
error.trainAUC.toHTML(sb);
}
else {
if (error.validation) {
RString v_rs = new RString("<a href='Inspect2.html?src_key=%$key'>%key</a>");
v_rs.replace("key", get_params().validation._key);
String cmTitle = "<div class=\"alert\">Scoring results reported on validation data " + v_rs.toString() + (fullvalid ? "" : " (" + score_valid + " samples)") + ":</div>";
sb.append("<h5>" + cmTitle);
if (error.valid_confusion_matrix != null && smallenough) {
sb.append("</h5>");
error.valid_confusion_matrix.toHTML(sb);
} else if (smallenough) sb.append(" Confusion matrix not yet computed.</h5>");
else sb.append(toolarge + "</h5>");
} else {
RString t_rs = new RString("<a href='Inspect2.html?src_key=%$key'>%key</a>");
t_rs.replace("key", get_params().source._key);
String cmTitle = "<div class=\"alert\">Scoring results reported on training data " + t_rs.toString() + (fulltrain ? "" : " (" + score_train + " samples)") + ":</div>";
sb.append("<h5>" + cmTitle);
if (error.train_confusion_matrix != null && smallenough) {
sb.append("</h5>");
error.train_confusion_matrix.toHTML(sb);
} else if (smallenough) sb.append(" Confusion matrix not yet computed.</h5>");
else sb.append(toolarge + "</h5>");
}
}
}
// Hit ratio
if (error.valid_hitratio != null) {
error.valid_hitratio.toHTML(sb);
} else if (error.train_hitratio != null) {
error.train_hitratio.toHTML(sb);
}
// Variable importance
if (error.variable_importances != null) {
error.variable_importances.toHTML(sb);
}
DocGen.HTML.title(sb, "Scoring history");
if (errors.length > 1) {
DocGen.HTML.paragraph(sb, "Time taken for last scoring and diagnostics: " + PrettyPrint.msecs(errors[errors.length-1].scoring_time, true));
// training
{
final long pts = fulltrain ? training_rows : score_train;
String training = "Number of training data samples for scoring: " + (fulltrain ? "all " : "") + pts;
if (pts < 1000 && training_rows >= 1000) training += " (low, scoring might be inaccurate -> consider increasing this number in the expert mode)";
if (pts > 100000 && errors[errors.length-1].scoring_time > 10000) training += " (large, scoring can be slow -> consider reducing this number in the expert mode or scoring manually)";
DocGen.HTML.paragraph(sb, training);
}
// validation
if (error.validation) {
final long ptsv = fullvalid ? get_params().validation.numRows() : score_valid;
String validation = "Number of validation data samples for scoring: " + (fullvalid ? "all " : "") + ptsv;
if (ptsv < 1000 && get_params().validation.numRows() >= 1000) validation += " (low, scoring might be inaccurate -> consider increasing this number in the expert mode)";
if (ptsv > 100000 && errors[errors.length-1].scoring_time > 10000) validation += " (large, scoring can be slow -> consider reducing this number in the expert mode or scoring manually)";
DocGen.HTML.paragraph(sb, validation);
}
if (isClassifier() && nclasses() != 2 /*binary classifier has its own conflicting D3 object (AUC)*/) {
// Plot training error
float[] err = new float[errors.length];
float[] samples = new float[errors.length];
for (int i=0; i<err.length; ++i) {
err[i] = (float)errors[i].train_err;
samples[i] = errors[i].training_samples;
}
new D3Plot(samples, err, "training samples", "classification error",
"classification error on training data").generate(sb);
// Plot validation error
if (get_params().validation != null) {
for (int i=0; i<err.length; ++i) {
err[i] = (float)errors[i].valid_err;
}
new D3Plot(samples, err, "training samples", "classification error",
"classification error on validation set").generate(sb);
}
}
// regression
else if (!isClassifier()) {
// Plot training MSE
float[] err = new float[errors.length-1];
float[] samples = new float[errors.length-1];
for (int i=0; i<err.length; ++i) {
err[i] = (float)errors[i+1].train_mse;
samples[i] = errors[i+1].training_samples;
}
new D3Plot(samples, err, "training samples", "MSE",
"regression error on training data").generate(sb);
// Plot validation MSE
if (get_params().validation != null) {
for (int i=0; i<err.length; ++i) {
err[i] = (float)errors[i+1].valid_mse;
}
new D3Plot(samples, err, "training samples", "MSE",
"regression error on validation data").generate(sb);
}
}
}
// String training = "Number of training set samples for scoring: " + error.score_training;
if (error.validation) {
// String validation = "Number of validation set samples for scoring: " + error.score_validation;
}
sb.append("<table class='table table-striped table-bordered table-condensed'>");
sb.append("<tr>");
sb.append("<th>Training Time</th>");
sb.append("<th>Training Epochs</th>");
sb.append("<th>Training Samples</th>");
if (isClassifier()) {
// sb.append("<th>Training MCE</th>");
sb.append("<th>Training Error</th>");
if (nclasses()==2) sb.append("<th>Training AUC</th>");
} else {
sb.append("<th>Training MSE</th>");
}
if (error.validation) {
if (isClassifier()) {
// sb.append("<th>Validation MCE</th>");
sb.append("<th>Validation Error</th>");
if (nclasses()==2) sb.append("<th>Validation AUC</th>");
} else {
sb.append("<th>Validation MSE</th>");
}
}
sb.append("</tr>");
for( int i = errors.length - 1; i >= 0; i
final Errors e = errors[i];
sb.append("<tr>");
sb.append("<td>" + PrettyPrint.msecs(e.training_time_ms, true) + "</td>");
sb.append("<td>" + String.format("%g", e.epoch_counter) + "</td>");
sb.append("<td>" + String.format("%,d", e.training_samples) + "</td>");
if (isClassifier()) {
// sb.append("<td>" + String.format(cross_entropy_format, e.train_mce) + "</td>");
sb.append("<td>" + formatPct(e.train_err) + "</td>");
if (nclasses()==2) {
if (e.trainAUC != null) sb.append("<td>" + formatPct(e.trainAUC.AUC()) + "</td>");
else sb.append("<td>" + "N/A" + "</td>");
}
} else {
sb.append("<td>" + String.format(mse_format, e.train_mse) + "</td>");
}
if(e.validation) {
if (isClassifier()) {
// sb.append("<td>" + String.format(cross_entropy_format, e.valid_mce) + "</td>");
sb.append("<td>" + formatPct(e.valid_err) + "</td>");
if (nclasses()==2) {
if (e.validAUC != null) sb.append("<td>" + formatPct(e.validAUC.AUC()) + "</td>");
else sb.append("<td>" + "N/A" + "</td>");
}
} else {
sb.append("<td>" + String.format(mse_format, e.valid_mse) + "</td>");
}
}
sb.append("</tr>");
}
sb.append("</table>");
return true;
}
private static String formatPct(double pct) {
String s = "N/A";
if( !isNaN(pct) )
s = String.format("%5.2f %%", 100 * pct);
return s;
}
public boolean toJavaHtml(StringBuilder sb) { return false; }
@Override public String toJava() { return "Not yet implemented."; }
}
|
package hudson.remoting;
import javax.annotation.Nonnull;
import javax.annotation.concurrent.GuardedBy;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* {@link JarCache} that stores files in a single directory.
*
* @author Kohsuke Kawaguchi
* @since 2.24
*/
public class FileSystemJarCache extends JarCacheSupport {
public final File rootDir;
private final boolean touch;
/**
* We've reported these checksums as present on this side.
*/
private final Set<Checksum> notified = Collections.synchronizedSet(new HashSet<Checksum>());
/**
* Cache of computer checksums for cached jars.
*/
@GuardedBy("itself")
private final Map<String, Checksum> checksumsByPath = new HashMap<>();
/**
* @param touch
* True to touch the cached jar file that's used. This enables external LRU based cache
* eviction at the expense of increased I/O.
*/
public FileSystemJarCache(File rootDir, boolean touch) {
this.rootDir = rootDir;
this.touch = touch;
if (rootDir==null)
throw new IllegalArgumentException();
try {
Util.mkdirs(rootDir);
} catch (IOException ex) {
throw new RuntimeException("Root directory not writable: " + rootDir);
}
}
@Override
protected URL lookInCache(Channel channel, long sum1, long sum2) throws IOException, InterruptedException {
File jar = map(sum1, sum2);
if (jar.exists()) {
LOGGER.log(Level.FINER, String.format("Jar file cache hit %16X%16X",sum1,sum2));
if (touch) jar.setLastModified(System.currentTimeMillis());
if (notified.add(new Checksum(sum1,sum2)))
getJarLoader(channel).notifyJarPresence(sum1,sum2);
return jar.toURI().toURL();
}
return null;
}
@Override
protected URL retrieve(Channel channel, long sum1, long sum2) throws IOException, InterruptedException {
Checksum expected = new Checksum(sum1, sum2);
File target = map(sum1, sum2);
if (target.exists()) {
Checksum actual = fileChecksum(target);
if (expected.equals(actual)) {
LOGGER.fine(String.format("Jar file already exists: %s", expected));
return target.toURI().toURL();
}
LOGGER.warning(String.format(
"Cached file checksum mismatch: %s%nExpected: %s%n Actual: %s",
target.getAbsolutePath(), expected, actual
));
target.delete();
synchronized (checksumsByPath) {
checksumsByPath.remove(target.getCanonicalPath());
}
}
try {
File tmp = createTempJar(target);
try {
RemoteOutputStream o = new RemoteOutputStream(new FileOutputStream(tmp));
try {
LOGGER.log(Level.FINE, String.format("Retrieving jar file %16X%16X",sum1,sum2));
getJarLoader(channel).writeJarTo(sum1, sum2, o);
} finally {
o.close();
}
// Verify the checksum of the download.
Checksum actual = Checksum.forFile(tmp);
if (!expected.equals(actual)) {
throw new IOException(String.format(
"Incorrect checksum of retrieved jar: %s%nExpected: %s%nActual: %s",
tmp.getAbsolutePath(), expected, actual));
}
if (!tmp.renameTo(target)) {
if (!target.exists()) {
throw new IOException("Unable to create " + target + " from " + tmp);
}
// Even if we fail to rename, we are OK as long as the target actually exists at
// this point. This can happen if two FileSystemJarCache instances share the
// same cache dir.
// Verify the checksum to be sure the target is correct.
actual = fileChecksum(target);
if (!expected.equals(actual)) {
throw new IOException(String.format(
"Incorrect checksum of previous jar: %s%nExpected: %s%nActual: %s",
target.getAbsolutePath(), expected, actual));
}
}
return target.toURI().toURL();
} finally {
tmp.delete();
}
} catch (IOException e) {
throw (IOException)new IOException("Failed to write to "+target).initCause(e);
}
}
/**
* Get file checksum calculating it or retrieving from cache.
*/
private Checksum fileChecksum(File file) throws IOException {
String location = file.getCanonicalPath();
// When callers all request the checksum of a large jar, the first thread
// will calculate the checksum and the other treads will be blocked here
// until calculated to be picked up from cache right away.
synchronized (checksumsByPath) {
Checksum checksum = checksumsByPath.get(location);
if (checksum != null) return checksum;
checksum = Checksum.forFile(file);
checksumsByPath.put(location, checksum);
return checksum;
}
}
/*package for testing*/ File createTempJar(@Nonnull File target) throws IOException {
File parent = target.getParentFile();
Util.mkdirs(parent);
return File.createTempFile(target.getName(), "tmp", parent);
}
/**
* Map to the cache jar file name.
*/
File map(long sum1, long sum2) {
return new File(rootDir,String.format("%02X/%014X%016X.jar",
(int)(sum1>>>(64-8)),
sum1&0x00FFFFFFFFFFFFFFL, sum2));
}
private static final Logger LOGGER = Logger.getLogger(FileSystemJarCache.class.getName());
}
|
package info.faceland.strife.data;
import info.faceland.strife.attributes.AttributeHandler;
import info.faceland.strife.attributes.StrifeAttribute;
import info.faceland.strife.stats.StrifeStat;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
public class Champion {
private UUID uniqueId;
private Map<StrifeStat, Integer> levelMap;
private int unusedStatPoints;
private int highestReachedLevel;
public Champion(UUID uniqueId) {
this.uniqueId = uniqueId;
this.levelMap = new HashMap<>();
}
public UUID getUniqueId() {
return uniqueId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Champion)) {
return false;
}
Champion champion = (Champion) o;
return !(uniqueId != null ? !uniqueId.equals(champion.uniqueId) : champion.uniqueId != null);
}
@Override
public int hashCode() {
return uniqueId != null ? uniqueId.hashCode() : 0;
}
public Map<StrifeStat, Integer> getLevelMap() {
return new HashMap<>(levelMap);
}
public int getLevel(StrifeStat stat) {
if (levelMap.containsKey(stat)) {
return levelMap.get(stat);
}
return 0;
}
public void setLevel(StrifeStat stat, int level) {
levelMap.put(stat, level);
}
public Player getPlayer() {
return Bukkit.getPlayer(getUniqueId());
}
public Map<StrifeAttribute, Double> getAttributeValues() {
Map<StrifeAttribute, Double> attributeDoubleMap = new HashMap<>();
for (Map.Entry<StrifeStat, Integer> entry : getLevelMap().entrySet()) {
for (StrifeAttribute attr : StrifeAttribute.values()) {
attributeDoubleMap.put(attr, entry.getKey().getAttribute(attr) * entry.getValue());
}
}
for (ItemStack itemStack : getPlayer().getEquipment().getArmorContents()) {
if (itemStack == null || itemStack.getType() == Material.AIR) {
continue;
}
for (StrifeAttribute attr : StrifeAttribute.values()) {
double val = attributeDoubleMap.containsKey(attr) ? attributeDoubleMap.get(attr) : 0;
if (!attributeDoubleMap.containsKey(attr)) {
val += attr.getBaseValue();
}
attributeDoubleMap.put(attr, val + AttributeHandler.getValue(itemStack, attr));
}
}
if (getPlayer().getEquipment().getItemInHand() != null && getPlayer().getEquipment().getItemInHand().getType() != Material.AIR) {
ItemStack itemStack = getPlayer().getEquipment().getItemInHand();
for (StrifeAttribute attr : StrifeAttribute.values()) {
double val = attributeDoubleMap.containsKey(attr) ? attributeDoubleMap.get(attr) : 0;
if (!attributeDoubleMap.containsKey(attr)) {
val += attr.getBaseValue();
}
attributeDoubleMap.put(attr, val + AttributeHandler.getValue(itemStack, attr));
}
}
return attributeDoubleMap;
}
public int getUnusedStatPoints() {
return unusedStatPoints;
}
public void setUnusedStatPoints(int unusedStatPoints) {
this.unusedStatPoints = unusedStatPoints;
}
public int getMaximumStatLevel() {
return 5 + (getHighestReachedLevel() / 5);
}
public int getHighestReachedLevel() {
return highestReachedLevel;
}
public void setHighestReachedLevel(int highestReachedLevel) {
this.highestReachedLevel = highestReachedLevel;
}
}
|
package info.iconmaster.typhon.model;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import info.iconmaster.typhon.TyphonInput;
import info.iconmaster.typhon.antlr.TyphonParser.ExprContext;
import info.iconmaster.typhon.antlr.TyphonParser.TypeContext;
import info.iconmaster.typhon.compiler.CodeBlock;
import info.iconmaster.typhon.plugins.PluginLoader;
import info.iconmaster.typhon.plugins.TyphonPlugin;
import info.iconmaster.typhon.types.TemplateType;
import info.iconmaster.typhon.types.Type;
import info.iconmaster.typhon.types.TypeRef;
import info.iconmaster.typhon.util.SourceInfo;
import info.iconmaster.typhon.util.TemplateUtils;
/**
* This represents a Typhon field- Either a global variable, or a member of a class.
*
* @author iconmaster
*
*/
public class Field extends TyphonModelEntity implements MemberAccess {
/**
* The name of this field. Must be a valid Typhon identifier.
*/
public String name;
/**
* The type of this field.
*/
public TypeRef type;
/**
* This code is run before static initializers, and returns the initial value of this field.
*/
public CodeBlock value;
/**
* The ANTLR rule representing the type of this field.
*/
public TypeContext rawType;
/**
* The ANTLR rule representing the initial value of this field.
*/
public ExprContext rawValue;
public Field(TyphonInput input, String name) {
super(input);
this.name = name;
}
public Field(TyphonInput input, SourceInfo source, String name) {
super(input, source);
this.name = name;
}
/**
* Create a library field.
*
* @param name
* @param type
*/
public Field(String name, TypeRef type) {
super(type.tni);
this.name = name;
this.type = type;
markAsLibrary();
}
/**
* @return The name of this field.
*/
public String getName() {
return name;
}
/**
* @return The type of this field.
*/
public TypeRef getType() {
return type;
}
/**
* @param type The new type of this field.
*/
public void setType(TypeRef type) {
this.type = type;
}
/**
* This {@link CodeBlock} is run before static initializers, and returns the initial value of this field.
*
* @return The initial value of this field.
*/
public CodeBlock getValue() {
return value;
}
/**
* This {@link CodeBlock} is run before static initializers, and returns the initial value of this field.
*
* @return The new initial value of this field.
*/
public void setValue(CodeBlock value) {
this.value = value;
}
/**
* Sets the raw ANTLR data for this field.
*
* @param rawType The ANTLR rule representing the type of this field.
* @param rawValue The ANTLR rule representing the initial value of this field.
*/
public void setRawData(TypeContext rawType, ExprContext rawValue) {
super.setRawData();
this.rawType = rawType;
this.rawValue = rawValue;
}
/**
* @return The ANTLR rule representing the type of this field.
*/
public TypeContext getRawType() {
return rawType;
}
/**
* @return The ANTLR rule representing the initial value of this field.
*/
public ExprContext getRawValue() {
return rawValue;
}
/**
* The package this field belongs to.
*/
private Package parent;
/**
* @return The package this field belongs to.
*/
public Package getParent() {
return parent;
}
/**
* NOTE: Don't call this, call <tt>{@link Package}.addField()</tt> instead.
*
* @param parent The new package this field belongs to.
*/
public void setParent(Package parent) {
this.parent = parent;
}
@Override
public List<MemberAccess> getMembers(Map<TemplateType, TypeRef> templateMap) {
if (type == null) {
return Arrays.asList();
}
return TemplateUtils.replaceTemplates(getType(), templateMap).getMembers(templateMap);
}
@Override
public MemberAccess getMemberParent() {
return getParent();
}
/**
* The getter function for this field.
*/
private Function getter;
/**
* The library function that is the default getter function for this field.
*/
private Function defaultGetter;
/**
* False if this field is write-only.
*/
private boolean hasGetter = true;
/**
* @return The getter function for this field. May be null if this field is write-only.
*/
public Function getGetter() {
if (!hasGetter) return null;
return getter == null ? defaultGetter() : getter;
}
/**
* @param f The getter function for this field. May be null if this field is write-only.
*/
public void setGetter(Function f) {
getter = f;
hasGetter = (f != null);
if (setter == null) {
hasSetter = false;
}
}
/**
* @return The library function that is the default getter function for this field.
*/
public Function defaultGetter() {
if (defaultGetter == null) {
// make the default getter function
defaultGetter = new Function(tni, getName(), new TemplateType[0], new Parameter[0], new TypeRef[] {type});
defaultGetter.markAsLibrary();
if (getParent() != null) getParent().addFunction(defaultGetter);
PluginLoader.runHook(TyphonPlugin.OnInitGetter.class, this);
}
return defaultGetter;
}
/**
* The setter function for this field.
*/
private Function setter;
/**
* The library function that is the default setter function for this field.
*/
private Function defaultSetter;
/**
* False if this field is read-only.
*/
private boolean hasSetter = true;
/**
* @return The setter function for this field. May be null if this field is read-only.
*/
public Function getSetter() {
if (!hasSetter) return null;
return setter == null ? defaultSetter() : setter;
}
/**
* @param f The setter function for this field. May be null if this field is read-only.
*/
public void setSetter(Function f) {
setter = f;
hasSetter = (f != null);
if (getter == null) {
hasGetter = false;
}
}
/**
* @return The library function that is the default setter function for this field.
*/
public Function defaultSetter() {
if (defaultSetter == null) {
// make the default setter function
defaultSetter = new Function(tni, getName(), new TemplateType[0], new Parameter[] {new Parameter(tni, name, type, false)}, new TypeRef[0]);
defaultSetter.markAsLibrary();
if (getParent() != null) getParent().addFunction(defaultSetter);
PluginLoader.runHook(TyphonPlugin.OnInitSetter.class, this);
}
return defaultSetter;
}
/**
* @return If this is an instance field: The type this field is part of. If this is a static field: Null.
*/
public Type getFieldOf() {
if (hasAnnot(tni.corePackage.ANNOT_STATIC)) {
return null;
}
MemberAccess access = this;
while (access != null) {
if (access instanceof Type) {
return (Type) access;
}
access = access.getMemberParent();
}
return null;
}
@Override
public Map<TemplateType, TypeRef> getTemplateMap(Map<TemplateType, TypeRef> templateMap) {
return type.getTemplateMap(templateMap);
}
@Override
public String toString() {
return "Field("+type+" "+name+")";
}
/**
* @return True if this field is static. False if it belongs to an instance of some type.
*/
public boolean isStatic() {
return getFieldOf() == null;
}
/**
* @return True if this field is real; that is, it takes up storage space in whatever this compiles to.
* False if this field is defined by getters and/or setters, or is otherwise nonexistent in reality.
*/
public boolean isActualField() {
return getter == null && setter == null;
}
}
|
package io.github.cdelmas.frp.cyclops;
import cyclops.async.Future;
import cyclops.async.adapters.Topic;
import cyclops.collections.mutable.ListX;
import cyclops.control.Try;
import cyclops.function.Fn1;
import cyclops.stream.ReactiveSeq;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.ToString;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
//reactive();
reactiveStreams();
}
private static Try<ListX<String>, IOException> readFile(Path path) {
return Try.withCatch(() -> Files.readAllLines(path))
.map(ListX::fromIterable);
}
private static void reactive() {
readBatchFile()
.map(lines -> lines.map(line -> process.apply(line)))
.map(Future::sequence)
.forEach(f -> f.forEach(ps -> ps.forEach(p -> System.out.println("Processed " + p))));
}
private static Try<ListX<String>, Exception> readBatchFile() {
return findBatchFile()
.flatMap(Main::readFile);
}
private static Try<Path, Exception> findBatchFile() {
return Try.withCatch(() -> {
URI data = Main.class.getResource("/data").toURI();
return Paths.get(data);
});
}
private static Fn1<String, Future<Parcel>> process = input -> {
// return Future.narrowK(Comprehensions.of(Future.Instances.monad())
// .forEach2(
// locate(input),
// __ -> computePrice(input),
// (a, p) -> new Parcel(p, a)));
Future<Price> price = computePrice(input);
Future<Address> address = locate(input);
return price.flatMap(p -> address.map(a -> new Parcel(p, a)));
};
@AllArgsConstructor
@Getter
@ToString
private static class Parcel {
private Price price;
private Address address;
}
@AllArgsConstructor
@ToString
private static class Price {
@Getter
private long price;
}
@AllArgsConstructor
@ToString
private static class Address {
@Getter
private String address;
}
private static Future<Address> locate(String id) {
return Future.of(() -> locateEager(id));
}
private static Address locateEager(String id) {
System.out.println("Locating " + id);
try {
Thread.sleep(100);
} catch (InterruptedException e1) {
Thread.currentThread().interrupt();
}
return new Address("Address$" + id);
}
private static Future<Price> computePrice(String id) {
return Future.of(() -> computePriceEager(id));
}
private static Price computePriceEager(String id) {
System.out.println("Computing price");
return new Price(Long.parseLong(id) / 1000000);
}
private static void reactiveStreams() {
System.out.println("REACTIVE");
ExecutorService mainEs = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
readBatchFile()
.forEach(content -> {
ReactiveSeq<String> idStream = content.stream();
Topic<String> topic = idStream.broadcast();
ReactiveSeq<String> notifs = topic.stream();
ReactiveSeq<String> process = topic.stream();
ReactiveSeq<Parcel> parcels = process.fanOutZipIn(
seq -> seq.map(Main::locateEager),
seq -> seq.map(Main::computePriceEager),
(a, p) -> new Parcel(p,a));
mainEs.submit(() -> notifs.forEach(x -> System.out.println("notif to customer for " + x)));
mainEs.submit(() -> parcels.forEach(System.out::println));
});
}
private static void integrations() {
// Use Vavr Try as a monad
// create a Flux from a SortedSetX
// create an Observable from a ReactiveSeq
}
}
|
package javasnack.snacks;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.List;
public class NetworkInterface1 implements Runnable {
@Override
public void run() {
try {
final InetAddress loopbackAddress = InetAddress.getLoopbackAddress();
System.out.println("=============== InetAddress.getLoopbackAddress()");
dumpInetAddress(loopbackAddress);
final InetAddress localhostAddress = InetAddress.getLocalHost();
System.out.println("=============== InetAddress.getLocalHost()");
dumpInetAddress(localhostAddress);
Enumeration<NetworkInterface> nics = NetworkInterface.getNetworkInterfaces();
while (nics.hasMoreElements()) {
dumpNetworkInterfaceInformation(nics.nextElement());
}
} catch (SocketException | UnknownHostException e) {
e.printStackTrace();
}
}
static void dumpInetAddress(final InetAddress ia) {
System.out.println("getHostAddress()=" + ia.getHostAddress());
System.out.println("getHostName()=" + ia.getHostName());
System.out.println("getCanonicalHostName()=" + ia.getCanonicalHostName());
System.out.println("isAnyLocalAddress()=" + ia.isAnyLocalAddress());
System.out.println("isLinkLocalAddress()=" + ia.isLinkLocalAddress());
System.out.println("isLoopbackAddress()=" + ia.isLoopbackAddress());
System.out.println("isMCGlobal()=" + ia.isMCGlobal());
System.out.println("isMCLinkLocal()=" + ia.isMCLinkLocal());
System.out.println("isMCNodeLocal()=" + ia.isMCNodeLocal());
System.out.println("isMCOrgLocal()=" + ia.isMCOrgLocal());
System.out.println("isMCSiteLocal()=" + ia.isMCSiteLocal());
System.out.println("isMulticastAddress()=" + ia.isMulticastAddress());
System.out.println("isSiteLocalAddress()=" + ia.isSiteLocalAddress());
}
static void dumpNetworkInterfaceInformation(NetworkInterface nic) throws SocketException {
System.out.println("
System.out.println("Name: " + nic.getName());
System.out.println("DisplayName: " + nic.getDisplayName());
List<InterfaceAddress> iaddresses = nic.getInterfaceAddresses();
for (InterfaceAddress iaddr : iaddresses) {
System.out.println(" ==========================");
System.out.println(" Address: " + iaddr.getAddress());
System.out.println(" Broadcast: " + iaddr.getBroadcast());
System.out.println(" Prefix Length: " + iaddr.getNetworkPrefixLength());
}
System.out.println(" ==========================");
Enumeration<NetworkInterface> subInterfaces = nic.getSubInterfaces();
while (subInterfaces.hasMoreElements()) {
System.out.println("Sub Interface: " + subInterfaces.nextElement().getDisplayName());
}
NetworkInterface parent = nic.getParent();
if (null != parent) {
System.out.println("Parent Interface: " + parent.getDisplayName());
}
System.out.println("Status : " + (nic.isUp() ? "UP" : "DOWN"));
System.out.println(nic.isLoopback() ? "Loopback" : "NO Loopback");
System.out.println(nic.isPointToPoint() ? "PPP" : "NO PPP");
System.out.println(nic.supportsMulticast() ? "MULTICAST Supported" : "MULTICAST NOT Supported");
byte[] hwAddress = nic.getHardwareAddress();
if (null != hwAddress) {
System.out.print("MAC Address: ");
for (byte segment : hwAddress) {
System.out.printf("%02x ", segment);
}
System.out.println();
}
System.out.println("MTU: " + nic.getMTU());
System.out.println(nic.isVirtual() ? "Virtual Interface" : "Physical Interface");
}
}
|
package jbyoshi.blockdodge.core;
import java.awt.*;
import java.awt.image.*;
import java.util.*;
import javax.swing.*;
import jbyoshi.blockdodge.*;
public final class BlockDodge extends JPanel {
private final int width, height;
final Random rand = new Random();
private static final Color[] COLORS = new Color[] { Color.BLUE, Color.CYAN, Color.GREEN, Color.MAGENTA,
Color.ORANGE, Color.PINK, Color.RED, Color.YELLOW };
private static final int FRAME_TIME = 1000 / 75;
private BufferedImage buffer;
private final Set<DodgeShape> shapes = new HashSet<DodgeShape>();
private final PlayerDodgeShape player = new PlayerDodgeShape(this);
public BlockDodge(int width, int height) {
this.width = width;
this.height = height;
this.buffer = createBuffer();
addKeyListener(player);
}
private BufferedImage createBuffer() {
return new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
}
public void add(DodgeShape shape) {
shapes.add(shape);
}
public void remove(DodgeShape shape) {
shapes.remove(shape);
if (shape.getDropCount() == 0) {
shape.onRemoved();
}
}
public boolean contains(DodgeShape shape) {
return shapes.contains(shape);
}
public PlayerDodgeShape getPlayer() {
return player;
}
public void go() {
player.reset();
shapes.clear();
shapes.add(player);
int timer = 0;
while (true) {
long start = System.currentTimeMillis();
for (DodgeShape shape : new HashSet<DodgeShape>(shapes)) {
shape.move();
}
for (DodgeShape one : new HashSet<DodgeShape>(shapes)) {
if (!shapes.contains(one)) {
continue; // Removed during a previous iteration
}
for (DodgeShape two : new HashSet<DodgeShape>(shapes)) {
if (!shapes.contains(two) || one == two) {
continue;
}
if (one.collides(two)) {
// Drops take care of it themselves.
boolean handled = false;
if (one instanceof DodgeShape.Drop) {
one.onCollided(two);
handled = true;
}
if (two instanceof DodgeShape.Drop) {
two.onCollided(one);
handled = true;
}
if (!handled) {
one.onCollided(two);
two.onCollided(one);
}
}
}
}
if (timer % 100 == 0) {
int w = rand.nextInt(25) + 8;
int h = rand.nextInt(25) + 8;
int pos = rand.nextInt(width + w + width + w + height + h + height + h);
int x, y;
float dirChg;
if (pos < width + w) {
// From top
x = pos - w;
y = -h;
dirChg = 0.25f;
} else {
pos -= width + w;
if (pos < width + w) {
// From bottom
x = pos - w;
y = height;
dirChg = 0.75f;
} else {
pos -= width + w;
if (pos < height + h) {
// From left
x = -w;
y = pos - h;
dirChg = 0;
} else {
// From right
pos -= height + h;
x = width;
y = pos - h;
dirChg = 0.5f;
}
}
}
float dir = (rand.nextFloat() / 2 + dirChg) % 1;
Color c = COLORS[rand.nextInt(COLORS.length)];
add(new BadDodgeShape(this, x, y, w, h, c, (float) (dir * 2 * Math.PI)));
}
BufferedImage buffer = createBuffer();
Graphics2D g = buffer.createGraphics();
for (DodgeShape shape : shapes) {
g.setColor(shape.color);
g.fill(shape.shape);
}
g.dispose();
this.buffer = buffer;
repaint();
timer++;
if (contains(player)) {
requestFocusInWindow();
} else if (player.getDropCount() == 0) {
return;
}
long sleep = FRAME_TIME - (System.currentTimeMillis() - start);
if (sleep > 0) {
try {
Thread.sleep(sleep);
} catch (InterruptedException e) {
}
}
}
}
@Override
public void paintComponent(Graphics g) {
g.drawImage(buffer, 0, 0, null);
}
@Override
public Dimension getPreferredSize() {
return new Dimension(width, height);
}
@Override
public Dimension getMinimumSize() {
return new Dimension(width, height);
}
@Override
public Dimension getMaximumSize() {
return new Dimension(width, height);
}
public static void main(String[] args) {
JFrame frame = new JFrame("Block Dodge");
BlockDodge game = new BlockDodge(800, 600);
frame.setContentPane(game);
frame.pack();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setVisible(true);
game.go();
}
}
|
// -*- mode:java; encoding:utf-8 -*-
// vim:set fileencoding=utf-8:
// @homepage@
package example;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
import javax.accessibility.Accessible;
import javax.swing.*;
import javax.swing.plaf.basic.ComboPopup;
public final class MainPanel extends JPanel {
private MainPanel() {
super(new BorderLayout());
CheckableItem[] m = {
new CheckableItem("aaa", false),
new CheckableItem("bb", true),
new CheckableItem("111", false),
new CheckableItem("33333", true),
new CheckableItem("2222", true),
new CheckableItem("c", false)
};
JPanel p = new JPanel(new GridLayout(0, 1));
p.setBorder(BorderFactory.createEmptyBorder(5, 20, 5, 20));
p.add(new JLabel("Default:"));
p.add(new JComboBox<>(m));
p.add(Box.createVerticalStrut(20));
p.add(new JLabel("CheckedComboBox:"));
p.add(new CheckedComboBox<>(new DefaultComboBoxModel<>(m)));
// p.add(new CheckedComboBox<>(new CheckableComboBoxModel<>(m)));
add(p, BorderLayout.NORTH);
setPreferredSize(new Dimension(320, 240));
}
public static void main(String[] args) {
EventQueue.invokeLater(MainPanel::createAndShowGui);
}
private static void createAndShowGui() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
Toolkit.getDefaultToolkit().beep();
}
JFrame frame = new JFrame("@title@");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.getContentPane().add(new MainPanel());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
// class CheckableComboBoxModel<E> extends DefaultComboBoxModel<E> {
// protected CheckableComboBoxModel(E[] items) {
// super(items);
// public void fireContentsChanged(int index) {
// super.fireContentsChanged(this, index, index);
class CheckableItem {
private final String text;
private boolean selected;
protected CheckableItem(String text, boolean selected) {
this.text = text;
this.selected = selected;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
@Override public String toString() {
return text;
}
}
// class CheckBoxCellRenderer<E extends CheckableItem> implements ListCellRenderer<E> {
// private final JLabel label = new JLabel(" ");
// private final JCheckBox check = new JCheckBox(" ");
// @Override public Component getListCellRendererComponent(JList<? extends E> list, E value, int index, boolean isSelected, boolean cellHasFocus) {
// if (index < 0) {
// String txt = getCheckedItemString(list.getModel());
// label.setText(txt.isEmpty() ? " " : txt);
// return label;
// } else {
// check.setText(Objects.toString(value, ""));
// check.setSelected(value.isSelected());
// if (isSelected) {
// check.setBackground(list.getSelectionBackground());
// check.setForeground(list.getSelectionForeground());
// } else {
// check.setBackground(list.getBackground());
// check.setForeground(list.getForeground());
// return check;
// private static <E extends CheckableItem> String getCheckedItemString(ListModel<E> model) {
// return IntStream.range(0, model.getSize())
// .mapToObj(model::getElementAt)
// .filter(CheckableItem::isSelected)
// .map(Objects::toString)
// .sorted()
// .collect(Collectors.joining(", "));
// // List<String> sl = new ArrayList<>();
// // for (int i = 0; i < model.getSize(); i++) {
// // CheckableItem v = model.getElementAt(i);
// // if (v.isSelected()) {
// // sl.add(v.toString());
// // if (sl.isEmpty()) {
// // return " "; // When returning the empty string, the height of JComboBox may become 0 in some cases.
// // } else {
// // return sl.stream().sorted().collect(Collectors.joining(", "));
class CheckedComboBox<E extends CheckableItem> extends JComboBox<E> {
private boolean keepOpen;
private transient ActionListener listener;
protected CheckedComboBox() {
super();
}
protected CheckedComboBox(ComboBoxModel<E> model) {
super(model);
}
// protected CheckedComboBox(E[] m) {
// super(m);
@Override public Dimension getPreferredSize() {
return new Dimension(200, 20);
}
@Override public void updateUI() {
setRenderer(null);
removeActionListener(listener);
super.updateUI();
listener = e -> {
if ((e.getModifiers() & AWTEvent.MOUSE_EVENT_MASK) != 0) {
updateItem(getSelectedIndex());
keepOpen = true;
}
};
JLabel label = new JLabel(" ");
JCheckBox check = new JCheckBox(" ");
setRenderer((list, value, index, isSelected, cellHasFocus) -> {
if (index < 0) {
String txt = getCheckedItemString(list.getModel());
label.setText(txt.isEmpty() ? " " : txt);
return label;
} else {
check.setText(Objects.toString(value, ""));
check.setSelected(value.isSelected());
if (isSelected) {
check.setBackground(list.getSelectionBackground());
check.setForeground(list.getSelectionForeground());
} else {
check.setBackground(list.getBackground());
check.setForeground(list.getForeground());
}
return check;
}
});
addActionListener(listener);
getInputMap(JComponent.WHEN_FOCUSED).put(KeyStroke.getKeyStroke(KeyEvent.VK_SPACE, 0), "checkbox-select");
getActionMap().put("checkbox-select", new AbstractAction() {
@Override public void actionPerformed(ActionEvent e) {
Accessible a = getAccessibleContext().getAccessibleChild(0);
if (a instanceof ComboPopup) {
updateItem(((ComboPopup) a).getList().getSelectedIndex());
}
}
});
}
private static <E extends CheckableItem> String getCheckedItemString(ListModel<E> model) {
return IntStream.range(0, model.getSize())
.mapToObj(model::getElementAt)
.filter(CheckableItem::isSelected)
.map(Objects::toString)
.sorted()
.collect(Collectors.joining(", "));
}
protected void updateItem(int index) {
if (isPopupVisible()) {
E item = getItemAt(index);
item.setSelected(!item.isSelected());
// item.selected ^= true;
// ComboBoxModel m = getModel();
// if (m instanceof CheckableComboBoxModel) {
// ((CheckableComboBoxModel) m).fireContentsChanged(index);
// removeItemAt(index);
// insertItemAt(item, index);
setSelectedIndex(-1);
setSelectedItem(item);
}
}
@Override public void setPopupVisible(boolean v) {
if (keepOpen) {
keepOpen = false;
} else {
super.setPopupVisible(v);
}
}
}
|
package mariculture.fishery;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Random;
import mariculture.api.core.Environment.Salinity;
import mariculture.api.core.MaricultureHandlers;
import mariculture.api.fishery.Fishing;
import mariculture.api.fishery.ICaughtAliveModifier;
import mariculture.api.fishery.IFishing;
import mariculture.api.fishery.Loot;
import mariculture.api.fishery.Loot.Rarity;
import mariculture.api.fishery.RodType;
import mariculture.api.fishery.fish.FishSpecies;
import mariculture.core.config.FishMechanics;
import mariculture.core.config.Vanilla;
import mariculture.core.util.RecipeItem;
import mariculture.fishery.items.ItemVanillaRod;
import net.minecraft.enchantment.Enchantment;
import net.minecraft.enchantment.EnchantmentHelper;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.WeightedRandomFishable;
import net.minecraft.world.World;
import net.minecraftforge.common.FishingHooks;
import net.minecraftforge.oredict.OreDictionary;
public class FishingHandler implements IFishing {
// Registering Fishing Rods
private static final HashMap<Item, RodType> registry = new HashMap();
@Override
public RodType getRodType(ItemStack stack) {
return stack != null ? registry.get(stack.getItem()) : null;
}
@Override
public void registerRod(Item item, RodType type) {
registry.put(item, type);
}
private boolean isVanillaRod(ItemStack stack) {
return stack.getItem() instanceof ItemVanillaRod;
}
// Handling Fishing Rods
@Override
public ItemStack handleRightClick(ItemStack stack, World world, EntityPlayer player) {
RodType rodType = getRodType(stack);
if (!world.isRemote && !rodType.canFish(world, (int) player.posX, (int) player.posY, (int) player.posZ, player, stack)) return stack;
int baitQuality = getBait(player, stack)[0];
int baitSlot = getBait(player, stack)[1];
if (player.fishEntity != null) {
rodType.damage(world, player, stack, player.fishEntity.func_146034_e(), world.rand);
player.swingItem();
} else if (baitSlot != -1 || !Vanilla.VANILLA_FORCE && stack.getItem() instanceof ItemVanillaRod) {
world.playSoundAtEntity(player, "random.bow", 0.5F, 0.4F / (world.rand.nextFloat() * 0.4F + 0.8F));
if (!Vanilla.VANILLA_POOR && isVanillaRod(stack)) {
baitQuality = 35;
}
EntityHook hook = new EntityHook(world, player, rodType.getDamage(), baitQuality);
if (!world.isRemote) {
world.spawnEntityInWorld(hook);
}
if (!player.capabilities.isCreativeMode && baitSlot != -1) {
if (baitQuality > 0) {
player.inventory.decrStackSize(baitSlot, 1);
}
}
player.swingItem();
}
return stack;
}
private int[] getBait(EntityPlayer player, ItemStack rod) {
int baitQuality = 0;
int currentSlot = player.inventory.currentItem;
int foundSlot = -1;
if (currentSlot > 0) {
int leftSlot = currentSlot - 1;
if (player.inventory.getStackInSlot(leftSlot) != null) if (canUseBait(rod, player.inventory.getStackInSlot(leftSlot))) {
baitQuality = getBaitQuality(player.inventory.getStackInSlot(leftSlot));
foundSlot = leftSlot;
}
}
if (foundSlot == -1 && currentSlot < 8) {
int rightSlot = currentSlot + 1;
if (player.inventory.getStackInSlot(rightSlot) != null) if (canUseBait(rod, player.inventory.getStackInSlot(rightSlot))) {
baitQuality = getBaitQuality(player.inventory.getStackInSlot(rightSlot));
foundSlot = rightSlot;
}
}
return new int[] { baitQuality, foundSlot };
}
// Bait Related Handling
private static final HashMap<RodType, ArrayList<ItemStack>> canUse = new HashMap();
private static final HashMap<List, Integer> baits = new HashMap();
@Override
public void addBait(ItemStack bait, Integer catchRate) {
baits.put(Arrays.asList(bait.getItem(), bait.getItemDamage()), catchRate);
}
@Override
public void addBaitForQuality(ItemStack bait, List<RodType> rods) {
for (RodType type : rods) {
addBaitForQuality(bait, type);
}
}
@Override
public void addBaitForQuality(ItemStack bait, RodType quality) {
ArrayList<ItemStack> baitList = canUse.get(quality);
if (baitList == null) {
baitList = new ArrayList();
}
baitList.add(bait);
canUse.put(quality, baitList);
}
@Override
public int getBaitQuality(ItemStack bait) {
Integer i = baits.get(Arrays.asList(bait.getItem(), bait.getItemDamage()));
if (i == null) i = baits.get(Arrays.asList(bait.getItem(), OreDictionary.WILDCARD_VALUE));
return i == null ? 0 : i;
}
@Override
public boolean canUseBait(ItemStack rod, ItemStack bait) {
RodType quality = getRodType(rod);
if (canUse.containsKey(quality)) {
ArrayList<ItemStack> baitList = canUse.get(quality);
if (baitList != null && baitList.size() > 0) {
for (ItemStack l : baitList)
if (RecipeItem.equals(bait, l)) return true;
return false;
} else return false;
} else return false;
}
@Override
public ArrayList<ItemStack> getCanUseList(RodType quality) {
return canUse.get(quality);
}
private static final HashMap<Rarity, ArrayList<Loot>> fishing_loot = new HashMap();
@Override
public void addLoot(Loot loot) {
ArrayList<Loot> lootList = fishing_loot.get(loot.rarity);
if (lootList == null) {
lootList = new ArrayList();
}
lootList.add(loot);
fishing_loot.put(loot.rarity, lootList);
if (loot.quality == null) {
addVanillaLoot(loot.rarity, new WeightedRandomFishable(loot.loot, (int) Math.max(loot.chance / 10, 1)));
}
}
// Add Vanilla Junk + Good Loot
private void addVanillaLoot(Rarity rarity, WeightedRandomFishable loot) {
if (rarity == Rarity.GOOD || rarity == Rarity.RARE) {
FishingHooks.addTreasure(loot);
} else {
FishingHooks.addJunk(loot);
}
}
//Returns whether this dimension is valid or not
private boolean isDimensionValid(World world, int id) {
if (id == Short.MAX_VALUE) return true;
else if (id == 0) return !world.provider.isHellWorld && world.provider.dimensionId != 1;
else return id == world.provider.dimensionId;
}
//Returns whether this fishing rod is valid to catch the loot
private boolean isFishingRodValid(RodType rod, RodType quality, boolean exact) {
if (quality == null) return true;
else if (exact) return rod == quality;
else return rod.getQuality() >= quality.getQuality();
}
//Returns a fishing loot catch for this location
private ItemStack getLoot(World world, RodType rod, Rarity rarity) {
ArrayList<Loot> loots = fishing_loot.get(rarity);
Collections.shuffle(loots);
for (Loot loot : loots) {
if (loot.loot.getItem() != null) {
if (isDimensionValid(world, loot.dimension) && isFishingRodValid(rod, loot.quality, loot.exact)) {
double chance = loot.chance * 10;
if (world.rand.nextInt(1000) < chance) return loot.loot.copy();
}
}
}
return rarity == Rarity.JUNK ? FishingHooks.getRandomFishable(world.rand, 0.05F) : FishingHooks.getRandomFishable(world.rand, 0.1F);
}
private ItemStack getVanillaLoot(World world, EntityPlayer player, ItemStack stack) {
float f = world.rand.nextFloat();
int i = EnchantmentHelper.getEnchantmentLevel(Enchantment.field_151370_z.effectId, stack);
int j = EnchantmentHelper.getEnchantmentLevel(Enchantment.field_151369_A.effectId, stack);
if(player != null) {
player.addStat(net.minecraftforge.common.FishingHooks.getFishableCategory(f, i, j).stat, 1);
}
return net.minecraftforge.common.FishingHooks.getRandomFishable(world.rand, f, i, j);
}
@Override
public ItemStack getCatch(World world, int x, int y, int z, EntityPlayer player, ItemStack stack) {
if (stack == null) return getFishForLocation(player, world, x, y, z, RodType.NET);
else {
RodType type = getRodType(stack);
if (Vanilla.VANILLA_LOOT && type == RodType.DIRE) return getVanillaLoot(world, player, stack);
if (type != null) {
ItemStack loot = null;
int lootBonus = EnchantmentHelper.getEnchantmentLevel(Enchantment.field_151370_z.effectId, stack);
if (lootBonus > 0 && world.rand.nextInt(200) < lootBonus * 10 || world.rand.nextInt(1000) < Math.max(0.01D, type.getChances().get(0))) {
loot = getLoot(world, type, Rarity.RARE);
} else {
double chance = Math.max(0.01D, type.getChances().get(1));
if (lootBonus > 0 && world.rand.nextInt(250) < lootBonus * 10 || world.rand.nextInt(1000) < Math.max(0.01D, type.getChances().get(1))) {
loot = getLoot(world, type, Rarity.GOOD);
} else if (lootBonus > 0 && world.rand.nextInt(300) < lootBonus * 10 || world.rand.nextInt(1000) < Math.max(0.01D, type.getChances().get(2))) {
loot = getLoot(world, type, Rarity.JUNK);
}
}
if (loot == null) return getFishForLocation(player, world, x, y, z, type);
else {
if (loot.isItemEnchantable()) if (world.rand.nextInt(100) < type.getQuality()) {
int chance = type.getLootEnchantmentChance();
if (chance > 0) {
EnchantmentHelper.addRandomEnchantment(world.rand, loot, world.rand.nextInt(chance));
}
}
return loot;
}
} else return new ItemStack(Items.stick);
}
}
public static ArrayList<FishSpecies> catchables;
private ItemStack getFishForLocation(EntityPlayer player, World world, int x, int y, int z, RodType type) {
double modifier = 10D;
if (player != null) {
for (ItemStack stack : player.inventory.armorInventory) {
if (stack != null && stack.getItem() != null && stack.getItem() instanceof ICaughtAliveModifier) {
modifier += ((ICaughtAliveModifier) stack.getItem()).getModifier();
}
}
}
//Creates the catchable fish list if it doesn't exist
if (catchables == null) {
catchables = new ArrayList();
for (Entry<Integer, FishSpecies> species : FishSpecies.species.entrySet()) {
catchables.add(species.getValue());
}
}
Salinity salt = MaricultureHandlers.environment.getSalinity(world, x, z);
int temperature = MaricultureHandlers.environment.getTemperature(world, x, y, z);
for (int i = 0; i < 20; i++) {
Collections.shuffle(catchables);
for (FishSpecies fish : catchables) {
double catchChance = fish.getCatchChance(world, x, y, z, salt, temperature);
if (catchChance > 0 && type.getQuality() >= fish.getRodNeeded().getQuality() && world.rand.nextInt(1000) < catchChance) {
if (FishMechanics.IGNORE_BIOMES) catchFish(world.rand, fish, type, fish.getCaughtAliveChance(world, y) * (modifier * 1.5D));
else return catchFish(world.rand, fish, type, fish.getCaughtAliveChance(world, x, y, z, salt, temperature) * (modifier));
}
}
}
return new ItemStack(Items.stick);
}
private ItemStack catchFish(Random rand, FishSpecies fish, RodType quality, double chance) {
boolean alive = false;
if (rand.nextInt(1000) < chance * FishMechanics.ALIVE_MODIFIER) {
alive = true;
}
boolean catchAlive = quality.caughtAlive(fish.getSpecies());
if (!catchAlive && !alive) return fish.getRawForm(1);
return Fishing.fishHelper.makePureFish(fish);
}
}
|
package me.math;
import org.ejml.data.DenseMatrix64F;
import org.ejml.factory.DecompositionFactory;
import org.ejml.interfaces.decomposition.SingularValueDecomposition;
import org.ejml.ops.SingularOps;
public class PrincipalComponentAnalyzer implements ComponentAnalyzer {
// Sampling ratio value
private double ratio;
// Sampling seed value
private long seed;
/**
* A constructor initiating the sampling options of the analyzer.
*
* @param ratio the sampling ratio on the data to consider.
* @param seed the sampling seed value.
*/
public PrincipalComponentAnalyzer(double ratio, long seed) {
this.ratio = ratio;
this.seed = seed;
}
public double getRatio() {
return ratio;
}
public void setRatio(double ratio) {
this.ratio = ratio;
}
public long getSeed() {
return seed;
}
public void setSeed(long seed) {
this.seed = seed;
}
/**
* A method applies the principal component analysis on a sample of vectors,
* adjusting the sample by subtracting with the component's mean values and
* returns a projection matrix extended by the adjustment vector.
*
* @param data the vector list of the dataset.
* @return a projection map produced by the analysis.
* @exception Exception throws unknown error exceptions.
*/
@Override
public double[][] analyze(double[][] data) throws Exception {
// Building random permutations regarding total number of data items
RandomPermutation permutations = new RandomPermutation(data.length, seed);
// Sampling permutation indexed items regarding ratio
int[] indices = permutations.sample(ratio);
double[][] sample = new double[indices.length][];
for (int j = 0; j < indices.length; j++) {
int index = indices[j];
sample[j] = data[index];
}
DenseMatrix64F A = new DenseMatrix64F(data);
// Calculating the adjustment mean vector
double[] mean = new double[A.numCols];
for (int i = 0; i < A.getNumRows(); i++) {
for (int j = 0; j < mean.length; j++) {
mean[j] += A.get(i, j);
}
}
for (int j = 0; j < mean.length; j++) {
mean[j] /= A.getNumRows();
}
// Adjusting by subtracting each component by component's mean
for (int i = 0; i < A.numRows; i++) {
for (int j = 0; j < A.numCols; j++) {
A.set(i, j, A.get(i, j) - mean[j]);
}
}
// Applying PCA on adjusted data using SVD
SingularValueDecomposition<DenseMatrix64F> svd = DecompositionFactory.svd(A.numRows, A.numCols, false, true, true);
// Decomposing the original data matrix
boolean success = svd.decompose(A);
// Checking if the decomposition process failed
if (!success) {
throw new RuntimeException("Unable to decompose the original matrix, analysis failed.");
}
// Getting the singular values, square roots of the eigenvalues
DenseMatrix64F S = svd.getW(null);
// Getting all the eigenvectors, eigen space
DenseMatrix64F V = svd.getV(null, false);
// Ordering singular values and eigenvectors in a descending order
SingularOps.descendingOrder(null, false, S, V, false);
// Copying the projection matrix to 2d double array
double[][] projection = new double[V.numRows][V.numCols];
for (int i = 0; i < V.numRows; i++) {
for (int j = 0; j < V.numCols; j++) {
projection[i][j] = V.get(i, j);
}
}
// Creating a 2d array as the projection map
double[][] map = new double[projection.length + 1][];
// Adding the adjustment vector, first row
map[0] = mean;
// Adding the projection matrix, rest rows
for (int i = 1; i < map.length; i++) {
map[i] = projection[i - 1];
}
return map;
}
}
|
package model.transform.tasks;
import model.transform.base.ImageTransformTask;
public class StoreOptions extends ImageTransformTask {
// Constructor left public because this task can be used with default options
public StoreOptions() {
super("store");
}
public static class Builder {
private StoreOptions storeOptions;
public Builder() {
this.storeOptions = new StoreOptions();
}
public Builder filename(String filename) {
storeOptions.addOption("filename", filename);
return this;
}
public Builder location(String location) {
storeOptions.addOption("location", location);
return this;
}
public Builder path(String path) {
storeOptions.addOption("path", path);
return this;
}
public Builder container(String container) {
storeOptions.addOption("container", container);
return this;
}
public Builder region(String region) {
storeOptions.addOption("region", region);
return this;
}
public Builder access(String access) {
storeOptions.addOption("access", access);
return this;
}
public Builder base64Decode(boolean base64Decode) {
storeOptions.addOption("base64decode", base64Decode);
return this;
}
public StoreOptions build() {
return storeOptions;
}
}
}
|
package net.techcable.techutils;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.bukkit.Bukkit;
public class Reflection {
public static Class<?> getNmsClass(String name) {
String className = "net.minecraft.server." + getVersion() + "." + name;
return getClass(className);
}
public static Class<?> getCbClass(String name) {
String className = "org.bukkit.craftbukkit." + getVersion() + "." + name;
return getClass(className);
}
public static Class<?> getUtilClass(String name) {
try {
return Class.forName(name); //Try before 1.8 first
} catch (ClassNotFoundException ex) {
try {
return Class.forName("net.minecraft.util." + name); //Not 1.8
} catch (ClassNotFoundException ex2) {
return null;
}
}
}
public static String getVersion() {
String packageName = Bukkit.getServer().getClass().getPackage().getName();
return packageName.substring(packageName.lastIndexOf('.') + 1);
}
public static Object getHandle(Object wrapper) {
Method getHandle = makeMethod(wrapper.getClass(), "getHandle");
return callMethod(getHandle, wrapper);
}
//Utils
public static Method makeMethod(Class<?> clazz, String methodName, Class<?>... paramaters) {
try {
return clazz.getDeclaredMethod(methodName, paramaters);
} catch (NoSuchMethodException ex) {
return null;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@SuppressWarnings("unchecked")
public static <T> T callMethod(Method method, Object instance, Object... paramaters) {
if (method == null) throw new RuntimeException("No such method");
method.setAccessible(true);
try {
return (T) method.invoke(instance, paramaters);
} catch (InvocationTargetException ex) {
throw new RuntimeException(ex.getCause());
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@SuppressWarnings("unchecked")
public static <T> Constructor<T> makeConstructor(Class<?> clazz, Class<?>... paramaterTypes) {
try {
return (Constructor<T>) clazz.getConstructor(paramaterTypes);
} catch (NoSuchMethodException ex) {
return null;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static <T> T callConstructor(Constructor<T> constructor, Object... paramaters) {
if (constructor == null) throw new RuntimeException("No such constructor");
constructor.setAccessible(true);
try {
return (T) constructor.newInstance(paramaters);
} catch (InvocationTargetException ex) {
throw new RuntimeException(ex.getCause());
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static Field makeField(Class<?> clazz, String name) {
try {
return clazz.getDeclaredField(name);
} catch (NoSuchFieldException ex) {
return null;
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@SuppressWarnings("unchecked")
public static <T> T getField(Field field, Object instance) {
if (field == null) throw new RuntimeException("No such field");
field.setAccessible(true);
try {
return (T) field.get(instance);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static void setField(Field field, Object instance, Object value) {
if (field == null) throw new RuntimeException("No such field");
field.setAccessible(true);
try {
field.set(instance, value);
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
public static Class<?> getClass(String name) {
try {
return Class.forName(name);
} catch (ClassNotFoundException ex) {
return null;
}
}
public static <T> Class<? extends T> getClass(String name, Class<T> superClass) {
try {
return Class.forName(name).asSubclass(superClass);
} catch (ClassCastException | ClassNotFoundException ex) {
return null;
}
}
}
|
package nl.topicus.jdbc;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Logger;
import com.google.cloud.spanner.Spanner;
public class CloudSpannerDriver implements Driver
{
static
{
try
{
java.sql.DriverManager.registerDriver(new CloudSpannerDriver());
}
catch (SQLException e)
{
java.sql.DriverManager.println("Registering driver failed: " + e.getMessage());
}
}
static final int MAJOR_VERSION = 1;
static final int MINOR_VERSION = 0;
static final class ConnectionProperties
{
private static final String PROJECT_URL_PART = "Project=";
private static final String INSTANCE_URL_PART = "Instance=";
private static final String DATABASE_URL_PART = "Database=";
private static final String KEY_FILE_URL_PART = "PvtKeyPath=";
private static final String OAUTH_ACCESS_TOKEN_URL_PART = "OAuthAccessToken=";
private static final String SIMULATE_PRODUCT_NAME = "SimulateProductName=";
String project = null;
String instance = null;
String database = null;
String keyFile = null;
String oauthToken = null;
String productName = null;
static ConnectionProperties parse(String url) throws SQLException
{
ConnectionProperties res = new ConnectionProperties();
if (url != null)
{
String[] parts = url.split(":", 3);
String[] connectionParts = parts[2].split(";");
// Get connection properties from connection string
for (int i = 1; i < connectionParts.length; i++)
{
String conPart = connectionParts[i].replace(" ", "");
if (conPart.startsWith(PROJECT_URL_PART))
res.project = conPart.substring(PROJECT_URL_PART.length());
else if (conPart.startsWith(INSTANCE_URL_PART))
res.instance = conPart.substring(INSTANCE_URL_PART.length());
else if (conPart.startsWith(DATABASE_URL_PART))
res.database = conPart.substring(DATABASE_URL_PART.length());
else if (conPart.startsWith(KEY_FILE_URL_PART))
res.keyFile = conPart.substring(KEY_FILE_URL_PART.length());
else if (conPart.startsWith(OAUTH_ACCESS_TOKEN_URL_PART))
res.oauthToken = conPart.substring(OAUTH_ACCESS_TOKEN_URL_PART.length());
else if (conPart.startsWith(SIMULATE_PRODUCT_NAME))
res.productName = conPart.substring(SIMULATE_PRODUCT_NAME.length());
else
throw new SQLException("Unknown URL parameter " + conPart);
}
}
return res;
}
void setAdditionalConnectionProperties(Properties info)
{
if (info != null)
{
project = info.getProperty(PROJECT_URL_PART.substring(0, PROJECT_URL_PART.length() - 1), project);
instance = info.getProperty(INSTANCE_URL_PART.substring(0, INSTANCE_URL_PART.length() - 1), instance);
database = info.getProperty(DATABASE_URL_PART.substring(0, DATABASE_URL_PART.length() - 1), database);
keyFile = info.getProperty(KEY_FILE_URL_PART.substring(0, KEY_FILE_URL_PART.length() - 1), keyFile);
oauthToken = info.getProperty(
OAUTH_ACCESS_TOKEN_URL_PART.substring(0, OAUTH_ACCESS_TOKEN_URL_PART.length() - 1), oauthToken);
productName = info.getProperty(SIMULATE_PRODUCT_NAME.substring(0, SIMULATE_PRODUCT_NAME.length() - 1),
productName);
}
}
DriverPropertyInfo[] getPropertyInfo()
{
DriverPropertyInfo[] res = new DriverPropertyInfo[6];
res[0] = new DriverPropertyInfo(PROJECT_URL_PART.substring(0, PROJECT_URL_PART.length() - 1), project);
res[0].description = "Google Cloud Project id";
res[1] = new DriverPropertyInfo(INSTANCE_URL_PART.substring(0, INSTANCE_URL_PART.length() - 1), instance);
res[1].description = "Google Cloud Spanner Instance id";
res[2] = new DriverPropertyInfo(DATABASE_URL_PART.substring(0, DATABASE_URL_PART.length() - 1), database);
res[2].description = "Google Cloud Spanner Database name";
res[3] = new DriverPropertyInfo(KEY_FILE_URL_PART.substring(0, KEY_FILE_URL_PART.length() - 1), keyFile);
res[3].description = "Path to json key file to be used for authentication";
res[4] = new DriverPropertyInfo(
OAUTH_ACCESS_TOKEN_URL_PART.substring(0, OAUTH_ACCESS_TOKEN_URL_PART.length() - 1), oauthToken);
res[4].description = "OAuth access token to be used for authentication (optional, only to be used when no key file is specified)";
res[5] = new DriverPropertyInfo(SIMULATE_PRODUCT_NAME.substring(0, SIMULATE_PRODUCT_NAME.length() - 1),
productName);
res[5].description = "Use this property to make the driver return a different database product name than Google Cloud Spanner, for example if you are using a framework like Spring that use this property to determine how to a generate data model for Spring Batch";
return res;
}
}
/**
* Keep track of all connections that are opened, so that we know which
* Spanner instances to close.
*/
private Map<Spanner, List<CloudSpannerConnection>> connections = new HashMap<>();
/**
* Connects to a Google Cloud Spanner database.
*
* @param url
* Connection URL in the form
* jdbc:cloudspanner://localhost;Project
* =projectId;Instance=instanceId
* ;Database=databaseName;PvtKeyPath
* =path_to_key_file;SimulateProductName=product_name
* @param info
* not used
* @return A CloudSpannerConnection
* @throws SQLException
* if an error occurs while connecting to Google Cloud Spanner
*/
@Override
public Connection connect(String url, Properties info) throws SQLException
{
if (!acceptsURL(url))
return null;
// checkAndSetLogging();
// Parse URL
ConnectionProperties properties = ConnectionProperties.parse(url);
// Get connection properties from properties
properties.setAdditionalConnectionProperties(info);
CloudSpannerConnection connection = new CloudSpannerConnection(this, url, properties.project,
properties.instance, properties.database, properties.keyFile, properties.oauthToken);
connection.setSimulateProductName(properties.productName);
registerConnection(connection);
return connection;
}
private void registerConnection(CloudSpannerConnection connection)
{
List<CloudSpannerConnection> list = connections.get(connection.getSpanner());
if (list == null)
{
list = new ArrayList<>();
connections.put(connection.getSpanner(), list);
}
list.add(connection);
}
void closeConnection(CloudSpannerConnection connection)
{
List<CloudSpannerConnection> list = connections.get(connection.getSpanner());
if (list == null)
throw new IllegalStateException("Connection is not registered");
if (!list.remove(connection))
throw new IllegalStateException("Connection is not registered");
if (list.isEmpty())
{
Spanner spanner = connection.getSpanner();
connections.remove(spanner);
spanner.close();
}
}
@Override
public boolean acceptsURL(String url) throws SQLException
{
return url.startsWith("jdbc:cloudspanner:");
}
@Override
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException
{
if (!acceptsURL(url))
return new DriverPropertyInfo[0];
ConnectionProperties properties = ConnectionProperties.parse(url);
properties.setAdditionalConnectionProperties(info);
return properties.getPropertyInfo();
}
@Override
public int getMajorVersion()
{
return getDriverMajorVersion();
}
public static int getDriverMajorVersion()
{
return MAJOR_VERSION;
}
@Override
public int getMinorVersion()
{
return getDriverMinorVersion();
}
public static int getDriverMinorVersion()
{
return MINOR_VERSION;
}
@Override
public boolean jdbcCompliant()
{
return true;
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException
{
throw new SQLFeatureNotSupportedException("java.util.logging is not used");
}
}
|
package org.apdplat.word.segmentation;
import java.util.Objects;
/**
*
* Word
* @author
*/
public class Word implements Comparable{
private String text;
private PartOfSpeech partOfSpeech = PartOfSpeech.UNKNOWN;
private int frequency;
public Word(String text){
this.text = text;
}
public Word(String text, PartOfSpeech partOfSpeech, int frequency) {
this.text = text;
this.partOfSpeech = partOfSpeech;
this.frequency = frequency;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public PartOfSpeech getPartOfSpeech() {
return partOfSpeech;
}
public void setPartOfSpeech(PartOfSpeech partOfSpeech) {
this.partOfSpeech = partOfSpeech;
}
public int getFrequency() {
return frequency;
}
public void setFrequency(int frequency) {
this.frequency = frequency;
}
@Override
public int hashCode() {
return Objects.hashCode(this.text);
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Word other = (Word) obj;
return Objects.equals(this.text, other.text);
}
@Override
public String toString(){
return text+" "+partOfSpeech+" "+frequency;
}
@Override
public int compareTo(Object o) {
if(this == o){
return 0;
}
if(this.text == null){
return -1;
}
if(o == null){
return 1;
}
if(!(o instanceof Word)){
return 1;
}
String t = ((Word)o).getText();
if(t == null){
return 1;
}
return this.text.compareTo(t);
}
}
|
package org.arkanos.aos.api.servlets;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.arkanos.aos.api.controllers.Database;
import org.arkanos.aos.api.controllers.HTTP;
import org.arkanos.aos.api.controllers.Security;
import org.arkanos.aos.api.data.Goal;
/**
* Goals REST API.
*
* @version 1.0
* @author Matheus Borges Teixeira
*/
/** Default version number **/
/**
* @see HttpServlet#HttpServlet()
*/
public Goals() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
*/
@Override
protected void doDelete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Security.TokenInfo token = Security.authenticateToken(request);
if (token == null) {
response.sendError(403, "Token is not valid or not found.");
return;
}
HTTP.setUpDefaultHeaders(response);
//TODO move to default headers
response.setContentType("application/x-json");
String URI = request.getRequestURI();
if (URI.endsWith("/goals") || URI.endsWith("/goals/")) {
response.setHeader("Allow", "GET, POST");
response.sendError(405, "DELETE is not supported without a specific resource.");
return;
}
String resource = URI.substring(URI.lastIndexOf("/") + 1);
if (URI.endsWith("goals/" + resource)) {
int id = Integer.parseInt(resource);
Goal result = Goal.getGoal(token.getUsername(), id);
if (result != null) {
if (Goal.isUserGoal(token.getUsername(), id)) {
if (result.delete()) {
response.setStatus(204);
return;
}
else {
response.sendError(500, "Could not delete the goal.");
return;
}
}
else {
response.sendError(403, "Goal does not belong to user.");
return;
}
}
else {
response.sendError(404, "Goal not found.");
return;
}
}
else {
response.sendError(400, "Goal not properly identified.");
return;
}
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Security.TokenInfo token = Security.authenticateToken(request);
if (token == null) {
response.sendError(403, "Token is not valid or not found.");
return;
}
HTTP.setUpDefaultHeaders(response);
response.setContentType("application/x-json");
String goals = "{\"success\":true,\"goals\":[";
String user_name = token.getUsername();
int count = 0;
for (Goal g : Goal.getUserGoals(user_name)) {
goals += g + ",";
count++;
}
if (count > 0) {
goals = goals.substring(0, goals.lastIndexOf(","));
}
goals += "],\"count\":" + count + "}";
response.setStatus(200);
response.getWriter().print(goals);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Security.TokenInfo token = Security.authenticateToken(request);
if (token == null) {
response.sendError(403, "Token is not valid or not found.");
return;
}
HTTP.setUpDefaultHeaders(response);
String URI = request.getRequestURI();
if (!URI.endsWith("/goals") && !URI.endsWith("/goals/")) {
response.setHeader("Allow", "GET, PUT, DELETE");
response.sendError(405, "POST is not supported for a specific resource.");
return;
}
else {
if (!URI.endsWith("/")) {
URI += "/";
}
}
String title = Database.sanitizeString(request.getParameter(Goal.FIELD_TITLE));
int time_planned = Integer.parseInt(request.getParameter(Goal.FIELD_TIME_PLANNED));
/* In DB time_planned is stored as minutes */
time_planned *= 60;
String description = Database.sanitizeString(request.getParameter(Goal.FIELD_DESCRIPTION));
int id = Goal.createGoal(title, time_planned, description, token.getUsername());
Goal created = Goal.getGoal(token.getUsername(), id);
if (created != null) {
response.setHeader("Location", URI + id);
response.getWriter().print("{\"success\":true}");
response.setStatus(201);
return;
}
else {
response.sendError(500, "Task could not be created.");
return;
}
}
/**
* @see HttpServlet#doPut(HttpServletRequest request, HttpServletResponse response)
*/
@Override
protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Security.TokenInfo token = Security.authenticateToken(request);
if (token == null) {
response.sendError(403, "Token is not valid or not found.");
return;
}
HTTP.setUpDefaultHeaders(response);
//TODO move to default headers
response.setContentType("application/x-json");
String URI = request.getRequestURI();
if (URI.endsWith("/goals") || URI.endsWith("/goals/")) {
response.setHeader("Allow", "GET, POST");
response.sendError(405, "PUT is not supported without a specific resource.");
return;
}
String resource = URI.substring(URI.lastIndexOf("/") + 1);
if (URI.endsWith("goals/" + resource)) {
int id = Integer.parseInt(resource);
Goal result = Goal.getGoal(token.getUsername(), id);
if (result != null) {
try {
Goal contents = Goal.parseGoal(request.getReader(), token.getUsername());
if (contents != null) {
result.replaceContent(contents);
if (result.update()) {
response.getWriter().print("{\"success\":true,\"goals\":[" + result + "]}");
response.setStatus(200);
return;
}
else {
response.sendError(500, "Could not save the task.");
return;
}
}
else {
response.sendError(400, "Contents of the resquest could not be parsed.");
return;
}
}
catch (NumberFormatException e) {
response.sendError(400, "Something was wrong with the numeric parameters.");
return;
}
}
else {
response.sendError(404, "Goal not found, use POST on '/goals' to create.");
return;
}
}
else {
response.sendError(400, "Goal not properly identified.");
return;
}
}
}
|
package org.b3log.symphony.util;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.Socket;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.HashMap;
public class GeetestLib {
protected final String verName = "3.2.0";// SDK
protected final String sdkLang = "java";
protected final String apiUrl = "http://api.geetest.com"; //API URL
protected final String baseUrl = "api.geetest.com";
protected final String registerUrl = "/register.php"; //register url
protected final String validateUrl = "/validate.php"; //validate url
/**
* chllenge
*/
public static final String fn_geetest_challenge = "geetest_challenge";
/**
* validate
*/
public static final String fn_geetest_validate = "geetest_validate";
/**
* seccode
*/
public static final String fn_geetest_seccode = "geetest_seccode";
private String captchaId = "";
private String privateKey = "";
private String userId = "";
private String responseStr = "";
public boolean debugCode = false;
/**
* APISession Key
*/
public String gtServerStatusSessionKey = "gt_server_status";
/**
*
*
* @param captchaId
* @param privateKey
*/
public GeetestLib(String captchaId, String privateKey) {
this.captchaId = captchaId;
this.privateKey = privateKey;
}
/**
*
*
* @return
*/
public String getResponseStr() {
return responseStr;
}
public String getVersionInfo() {
return verName;
}
/**
*
*
* @return
*/
private String getFailPreProcessRes() {
Long rnd1 = Math.round(Math.random() * 100);
Long rnd2 = Math.round(Math.random() * 100);
String md5Str1 = md5Encode(rnd1 + "");
String md5Str2 = md5Encode(rnd2 + "");
String challenge = md5Str1 + md5Str2.substring(0, 2);
return String.format(
"{\"success\":%s,\"gt\":\"%s\",\"challenge\":\"%s\"}", 0,
this.captchaId, challenge);
}
private String getSuccessPreProcessRes(String challenge) {
gtlog("challenge:" + challenge);
return String.format(
"{\"success\":%s,\"gt\":\"%s\",\"challenge\":\"%s\"}", 1,
this.captchaId, challenge);
}
/**
*
*
* @return 10
*/
public int preProcess() {
if (registerChallenge() != 1) {
this.responseStr = this.getFailPreProcessRes();
return 0;
}
return 1;
}
/**
*
*
* @param userid
* @return 10
*/
public int preProcess(String userid) {
this.userId = userid;
return this.preProcess();
}
/**
* captchaIDchallenge
*
* @return 10
*/
private int registerChallenge() {
try {
String GET_URL = apiUrl + registerUrl + "?gt=" + this.captchaId;
if (this.userId != "") {
GET_URL = GET_URL + "&user_id=" + this.userId;
this.userId = "";
}
gtlog("GET_URL:" + GET_URL);
String result_str = readContentFromGet(GET_URL);
gtlog("register_result:" + result_str);
if (32 == result_str.length()) {
this.responseStr = this.getSuccessPreProcessRes(this.md5Encode(result_str + this.privateKey));
return 1;
} else {
gtlog("gtServer register challenge failed");
return 0;
}
} catch (Exception e) {
gtlog("exception:register api");
}
return 0;
}
/**
*
*
* @param getURL
* @return
* @throws IOException
*/
private String readContentFromGet(String getURL) throws IOException {
URL getUrl = new URL(getURL);
HttpURLConnection connection = (HttpURLConnection) getUrl
.openConnection();
connection.setConnectTimeout(2000);
connection.setReadTimeout(2000);
connection.connect();
// Reader
StringBuffer sBuffer = new StringBuffer();
InputStream inStream = null;
byte[] buf = new byte[1024];
inStream = connection.getInputStream();
for (int n; (n = inStream.read(buf)) != -1;) {
sBuffer.append(new String(buf, 0, n, "UTF-8"));
}
inStream.close();
connection.disconnect();
return sBuffer.toString();
}
/**
*
*
* @param gtObj
* @return
*/
protected boolean objIsEmpty(Object gtObj) {
if (gtObj == null) {
return true;
}
if (gtObj.toString().trim().length() == 0) {
return true;
}
return false;
}
/**
* ,
*
* @param request
* @return
*/
private boolean resquestIsLegal(String challenge, String validate, String seccode) {
if (objIsEmpty(challenge)) {
return false;
}
if (objIsEmpty(validate)) {
return false;
}
if (objIsEmpty(seccode)) {
return false;
}
return true;
}
/**
* ,gt-server,
*
* @param challenge
* @param validate
* @param seccode
* @return ,10
*/
public int enhencedValidateRequest(String challenge, String validate, String seccode) {
if (!resquestIsLegal(challenge, validate, seccode)) {
return 0;
}
gtlog("request legitimate");
String host = baseUrl;
String path = validateUrl;
int port = 80;
String query = String.format("seccode=%s&sdk=%s", seccode,
(this.sdkLang + "_" + this.verName));
String response = "";
if (this.userId != "") {
query = query + "&user_id=" + this.userId;
this.userId = "";
}
gtlog(query);
try {
if (validate.length() <= 0) {
return 0;
}
if (!checkResultByPrivate(challenge, validate)) {
return 0;
}
gtlog("checkResultByPrivate");
response = postValidate(host, path, query, port);
gtlog("response: " + response);
} catch (Exception e) {
e.printStackTrace();
}
gtlog("md5: " + md5Encode(seccode));
if (response.equals(md5Encode(seccode))) {
return 1;
} else {
return 0;
}
}
/**
* ,gt-server,
*
* @param challenge
* @param validate
* @param seccode
* @param userid
* @return ,10
*/
public int enhencedValidateRequest(String challenge, String validate, String seccode, String userid) {
this.userId = userid;
return this.enhencedValidateRequest(challenge, validate, seccode);
}
/**
* failback
*
* @param challenge
* @param validate
* @param seccode
* @return ,10
*/
public int failbackValidateRequest(String challenge, String validate, String seccode) {
gtlog("in failback validate");
if (!resquestIsLegal(challenge, validate, seccode)) {
return 0;
}
gtlog("request legitimate");
String[] validateStr = validate.split("_");
String encodeAns = validateStr[0];
String encodeFullBgImgIndex = validateStr[1];
String encodeImgGrpIndex = validateStr[2];
gtlog(String.format(
"encode----challenge:%s--ans:%s,bg_idx:%s,grp_idx:%s",
challenge, encodeAns, encodeFullBgImgIndex, encodeImgGrpIndex));
int decodeAns = decodeResponse(challenge, encodeAns);
int decodeFullBgImgIndex = decodeResponse(challenge, encodeFullBgImgIndex);
int decodeImgGrpIndex = decodeResponse(challenge, encodeImgGrpIndex);
gtlog(String.format("decode----ans:%s,bg_idx:%s,grp_idx:%s", decodeAns,
decodeFullBgImgIndex, decodeImgGrpIndex));
int validateResult = validateFailImage(decodeAns, decodeFullBgImgIndex, decodeImgGrpIndex);
return validateResult;
}
/**
*
* @param ans
* @param full_bg_index
* @param img_grp_index
* @return
*/
private int validateFailImage(int ans, int full_bg_index,
int img_grp_index) {
final int thread = 3;
String full_bg_name = md5Encode(full_bg_index + "").substring(0, 9);
String bg_name = md5Encode(img_grp_index + "").substring(10, 19);
String answer_decode = "";
for (int i = 0; i < 9; i++) {
if (i % 2 == 0) {
answer_decode += full_bg_name.charAt(i);
} else if (i % 2 == 1) {
answer_decode += bg_name.charAt(i);
} else {
gtlog("exception");
}
}
String x_decode = answer_decode.substring(4, answer_decode.length());
int x_int = Integer.valueOf(x_decode, 16);// 16 to 10
int result = x_int % 200;
if (result < 40) {
result = 40;
}
if (Math.abs(ans - result) <= thread) {
return 1;
} else {
return 0;
}
}
/**
*
*
* @param encodeStr
* @param challenge
* @return
*/
private int decodeResponse(String challenge, String string) {
if (string.length() > 100) {
return 0;
}
int[] shuzi = new int[]{1, 2, 5, 10, 50};
String chongfu = "";
HashMap<String, Integer> key = new HashMap<String, Integer>();
int count = 0;
for (int i = 0; i < challenge.length(); i++) {
String item = challenge.charAt(i) + "";
if (chongfu.contains(item) == true) {
continue;
} else {
int value = shuzi[count % 5];
chongfu += item;
count++;
key.put(item, value);
}
}
int res = 0;
for (int j = 0; j < string.length(); j++) {
res += key.get(string.charAt(j) + "");
}
res = res - decodeRandBase(challenge);
return res;
}
/**
* ,
*
* @param randStr
* @return
*/
private int decodeRandBase(String challenge) {
String base = challenge.substring(32, 34);
ArrayList<Integer> tempArray = new ArrayList<Integer>();
for (int i = 0; i < base.length(); i++) {
char tempChar = base.charAt(i);
Integer tempAscii = (int) (tempChar);
Integer result = (tempAscii > 57) ? (tempAscii - 87)
: (tempAscii - 48);
tempArray.add(result);
}
int decodeRes = tempArray.get(0) * 36 + tempArray.get(1);
return decodeRes;
}
/**
* debugdebugCode
*
* @param message
*/
public void gtlog(String message) {
if (debugCode) {
System.out.println("gtlog: " + message);
}
}
protected boolean checkResultByPrivate(String challenge, String validate) {
String encodeStr = md5Encode(privateKey + "geetest" + challenge);
return validate.equals(encodeStr);
}
/**
* Post
*
* @param host
* @param path
* @param data
* @param port
* @return
* @throws Exception
*/
protected String postValidate(String host, String path, String data,
int port) throws Exception {
String response = "error";
InetAddress addr = InetAddress.getByName(host);
Socket socket = new Socket(addr, port);
BufferedWriter wr = new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream(), "UTF8"));
wr.write("POST " + path + " HTTP/1.0\r\n");
wr.write("Host: " + host + "\r\n");
wr.write("Content-Type: application/x-www-form-urlencoded\r\n");
wr.write("Content-Length: " + data.length() + "\r\n");
wr.write("\r\n");
wr.write(data);
wr.flush();
BufferedReader rd = new BufferedReader(new InputStreamReader(
socket.getInputStream(), "UTF-8"));
String line;
while ((line = rd.readLine()) != null) {
response = line;
}
wr.close();
rd.close();
socket.close();
return response;
}
/**
* md5
*
* @time 2014710 3:30:01
* @param plainText
* @return
*/
private String md5Encode(String plainText) {
String re_md5 = "";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(plainText.getBytes());
byte b[] = md.digest();
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0) {
i += 256;
}
if (i < 16) {
buf.append("0");
}
buf.append(Integer.toHexString(i));
}
re_md5 = buf.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return re_md5;
}
}
|
package org.citygml4j.visitor;
import org.citygml4j.ADERegistry;
import org.citygml4j.model.ade.ADEObject;
import org.citygml4j.model.ade.ADEProperty;
import org.citygml4j.model.appearance.AbstractSurfaceData;
import org.citygml4j.model.appearance.AbstractSurfaceDataProperty;
import org.citygml4j.model.appearance.AbstractTexture;
import org.citygml4j.model.appearance.Appearance;
import org.citygml4j.model.appearance.GeoreferencedTexture;
import org.citygml4j.model.appearance.ParameterizedTexture;
import org.citygml4j.model.appearance.TextureAssociation;
import org.citygml4j.model.appearance.X3DMaterial;
import org.citygml4j.model.bridge.AbstractBridge;
import org.citygml4j.model.bridge.Bridge;
import org.citygml4j.model.bridge.BridgeConstructiveElement;
import org.citygml4j.model.bridge.BridgeConstructiveElementMember;
import org.citygml4j.model.bridge.BridgeFurniture;
import org.citygml4j.model.bridge.BridgeFurnitureMember;
import org.citygml4j.model.bridge.BridgeFurnitureProperty;
import org.citygml4j.model.bridge.BridgeInstallation;
import org.citygml4j.model.bridge.BridgeInstallationMember;
import org.citygml4j.model.bridge.BridgeInstallationProperty;
import org.citygml4j.model.bridge.BridgePart;
import org.citygml4j.model.bridge.BridgePartProperty;
import org.citygml4j.model.bridge.BridgeRoom;
import org.citygml4j.model.bridge.BridgeRoomMember;
import org.citygml4j.model.building.AbstractBuilding;
import org.citygml4j.model.building.AbstractBuildingSubdivision;
import org.citygml4j.model.building.AbstractBuildingSubdivisionMember;
import org.citygml4j.model.building.Building;
import org.citygml4j.model.building.BuildingConstructiveElement;
import org.citygml4j.model.building.BuildingConstructiveElementMember;
import org.citygml4j.model.building.BuildingFurniture;
import org.citygml4j.model.building.BuildingFurnitureMember;
import org.citygml4j.model.building.BuildingFurnitureProperty;
import org.citygml4j.model.building.BuildingInstallation;
import org.citygml4j.model.building.BuildingInstallationMember;
import org.citygml4j.model.building.BuildingInstallationProperty;
import org.citygml4j.model.building.BuildingPart;
import org.citygml4j.model.building.BuildingPartProperty;
import org.citygml4j.model.building.BuildingRoom;
import org.citygml4j.model.building.BuildingRoomMember;
import org.citygml4j.model.building.BuildingUnit;
import org.citygml4j.model.building.Storey;
import org.citygml4j.model.cityfurniture.CityFurniture;
import org.citygml4j.model.cityobjectgroup.CityObjectGroup;
import org.citygml4j.model.cityobjectgroup.Role;
import org.citygml4j.model.cityobjectgroup.RoleProperty;
import org.citygml4j.model.construction.AbstractConstruction;
import org.citygml4j.model.construction.AbstractConstructionSurface;
import org.citygml4j.model.construction.AbstractConstructiveElement;
import org.citygml4j.model.construction.AbstractFillingElement;
import org.citygml4j.model.construction.AbstractFillingElementProperty;
import org.citygml4j.model.construction.AbstractFillingSurface;
import org.citygml4j.model.construction.AbstractFillingSurfaceProperty;
import org.citygml4j.model.construction.AbstractFurniture;
import org.citygml4j.model.construction.AbstractInstallation;
import org.citygml4j.model.construction.CeilingSurface;
import org.citygml4j.model.construction.Door;
import org.citygml4j.model.construction.DoorSurface;
import org.citygml4j.model.construction.FloorSurface;
import org.citygml4j.model.construction.GroundSurface;
import org.citygml4j.model.construction.InteriorWallSurface;
import org.citygml4j.model.construction.OtherConstruction;
import org.citygml4j.model.construction.OuterCeilingSurface;
import org.citygml4j.model.construction.OuterFloorSurface;
import org.citygml4j.model.construction.RoofSurface;
import org.citygml4j.model.construction.WallSurface;
import org.citygml4j.model.construction.Window;
import org.citygml4j.model.construction.WindowSurface;
import org.citygml4j.model.core.AbstractAppearance;
import org.citygml4j.model.core.AbstractAppearanceProperty;
import org.citygml4j.model.core.AbstractCityObject;
import org.citygml4j.model.core.AbstractCityObjectProperty;
import org.citygml4j.model.core.AbstractDynamizer;
import org.citygml4j.model.core.AbstractDynamizerProperty;
import org.citygml4j.model.core.AbstractFeature;
import org.citygml4j.model.core.AbstractFeatureProperty;
import org.citygml4j.model.core.AbstractFeatureWithLifespan;
import org.citygml4j.model.core.AbstractFeatureWithLifespanProperty;
import org.citygml4j.model.core.AbstractLogicalSpace;
import org.citygml4j.model.core.AbstractOccupiedSpace;
import org.citygml4j.model.core.AbstractPhysicalSpace;
import org.citygml4j.model.core.AbstractPointCloud;
import org.citygml4j.model.core.AbstractSpace;
import org.citygml4j.model.core.AbstractSpaceBoundary;
import org.citygml4j.model.core.AbstractSpaceBoundaryProperty;
import org.citygml4j.model.core.AbstractThematicSurface;
import org.citygml4j.model.core.AbstractUnoccupiedSpace;
import org.citygml4j.model.core.AbstractVersion;
import org.citygml4j.model.core.AbstractVersionProperty;
import org.citygml4j.model.core.AbstractVersionTransition;
import org.citygml4j.model.core.AbstractVersionTransitionProperty;
import org.citygml4j.model.core.Address;
import org.citygml4j.model.core.AddressProperty;
import org.citygml4j.model.core.CityModel;
import org.citygml4j.model.core.CityObjectRelation;
import org.citygml4j.model.core.CityObjectRelationProperty;
import org.citygml4j.model.core.ClosureSurface;
import org.citygml4j.model.core.ImplicitGeometry;
import org.citygml4j.model.deprecated.bridge.DeprecatedPropertiesOfAbstractBridge;
import org.citygml4j.model.deprecated.bridge.DeprecatedPropertiesOfBridgeConstructiveElement;
import org.citygml4j.model.deprecated.bridge.DeprecatedPropertiesOfBridgeFurniture;
import org.citygml4j.model.deprecated.bridge.DeprecatedPropertiesOfBridgeInstallation;
import org.citygml4j.model.deprecated.bridge.DeprecatedPropertiesOfBridgeRoom;
import org.citygml4j.model.deprecated.building.DeprecatedPropertiesOfAbstractBuilding;
import org.citygml4j.model.deprecated.building.DeprecatedPropertiesOfBuildingFurniture;
import org.citygml4j.model.deprecated.building.DeprecatedPropertiesOfBuildingInstallation;
import org.citygml4j.model.deprecated.building.DeprecatedPropertiesOfBuildingRoom;
import org.citygml4j.model.deprecated.cityfurniture.DeprecatedPropertiesOfCityFurniture;
import org.citygml4j.model.deprecated.cityobjectgroup.DeprecatedPropertiesOfCityObjectGroup;
import org.citygml4j.model.deprecated.construction.DeprecatedPropertiesOfAbstractFillingSurface;
import org.citygml4j.model.deprecated.core.DeprecatedPropertiesOfAbstractCityObject;
import org.citygml4j.model.deprecated.core.DeprecatedPropertiesOfAbstractThematicSurface;
import org.citygml4j.model.deprecated.generics.DeprecatedPropertiesOfGenericOccupiedSpace;
import org.citygml4j.model.deprecated.transportation.DeprecatedPropertiesOfAbstractTransportationSpace;
import org.citygml4j.model.deprecated.transportation.TransportationComplex;
import org.citygml4j.model.deprecated.tunnel.DeprecatedPropertiesOfAbstractTunnel;
import org.citygml4j.model.deprecated.tunnel.DeprecatedPropertiesOfHollowSpace;
import org.citygml4j.model.deprecated.tunnel.DeprecatedPropertiesOfTunnelFurniture;
import org.citygml4j.model.deprecated.tunnel.DeprecatedPropertiesOfTunnelInstallation;
import org.citygml4j.model.deprecated.vegetation.DeprecatedPropertiesOfPlantCover;
import org.citygml4j.model.deprecated.vegetation.DeprecatedPropertiesOfSolitaryVegetationObject;
import org.citygml4j.model.deprecated.waterbody.DeprecatedPropertiesOfWaterBody;
import org.citygml4j.model.dynamizer.AbstractAtomicTimeseries;
import org.citygml4j.model.dynamizer.AbstractTimeseries;
import org.citygml4j.model.dynamizer.CompositeTimeseries;
import org.citygml4j.model.dynamizer.Dynamizer;
import org.citygml4j.model.dynamizer.GenericTimeseries;
import org.citygml4j.model.dynamizer.StandardFileTimeseries;
import org.citygml4j.model.dynamizer.TabulatedFileTimeseries;
import org.citygml4j.model.dynamizer.TimeValuePair;
import org.citygml4j.model.dynamizer.TimeValuePairProperty;
import org.citygml4j.model.dynamizer.TimeseriesComponentProperty;
import org.citygml4j.model.generics.GenericLogicalSpace;
import org.citygml4j.model.generics.GenericOccupiedSpace;
import org.citygml4j.model.generics.GenericThematicSurface;
import org.citygml4j.model.generics.GenericUnoccupiedSpace;
import org.citygml4j.model.landuse.LandUse;
import org.citygml4j.model.pointcloud.PointCloud;
import org.citygml4j.model.relief.AbstractReliefComponent;
import org.citygml4j.model.relief.AbstractReliefComponentProperty;
import org.citygml4j.model.relief.BreaklineRelief;
import org.citygml4j.model.relief.MassPointRelief;
import org.citygml4j.model.relief.RasterRelief;
import org.citygml4j.model.relief.ReliefFeature;
import org.citygml4j.model.relief.TINRelief;
import org.citygml4j.model.transportation.AbstractTransportationSpace;
import org.citygml4j.model.transportation.AuxiliaryTrafficArea;
import org.citygml4j.model.transportation.AuxiliaryTrafficSpace;
import org.citygml4j.model.transportation.AuxiliaryTrafficSpaceProperty;
import org.citygml4j.model.transportation.ClearanceSpace;
import org.citygml4j.model.transportation.ClearanceSpaceProperty;
import org.citygml4j.model.transportation.Hole;
import org.citygml4j.model.transportation.HoleProperty;
import org.citygml4j.model.transportation.HoleSurface;
import org.citygml4j.model.transportation.Intersection;
import org.citygml4j.model.transportation.IntersectionProperty;
import org.citygml4j.model.transportation.Marking;
import org.citygml4j.model.transportation.MarkingProperty;
import org.citygml4j.model.transportation.Railway;
import org.citygml4j.model.transportation.Road;
import org.citygml4j.model.transportation.Section;
import org.citygml4j.model.transportation.SectionProperty;
import org.citygml4j.model.transportation.Square;
import org.citygml4j.model.transportation.Track;
import org.citygml4j.model.transportation.TrafficArea;
import org.citygml4j.model.transportation.TrafficSpace;
import org.citygml4j.model.transportation.TrafficSpaceProperty;
import org.citygml4j.model.transportation.Waterway;
import org.citygml4j.model.tunnel.AbstractTunnel;
import org.citygml4j.model.tunnel.HollowSpace;
import org.citygml4j.model.tunnel.HollowSpaceMember;
import org.citygml4j.model.tunnel.Tunnel;
import org.citygml4j.model.tunnel.TunnelConstructiveElement;
import org.citygml4j.model.tunnel.TunnelConstructiveElementMember;
import org.citygml4j.model.tunnel.TunnelFurniture;
import org.citygml4j.model.tunnel.TunnelFurnitureMember;
import org.citygml4j.model.tunnel.TunnelFurnitureProperty;
import org.citygml4j.model.tunnel.TunnelInstallation;
import org.citygml4j.model.tunnel.TunnelInstallationMember;
import org.citygml4j.model.tunnel.TunnelInstallationProperty;
import org.citygml4j.model.tunnel.TunnelPart;
import org.citygml4j.model.tunnel.TunnelPartProperty;
import org.citygml4j.model.vegetation.AbstractVegetationObject;
import org.citygml4j.model.vegetation.PlantCover;
import org.citygml4j.model.vegetation.SolitaryVegetationObject;
import org.citygml4j.model.versioning.Version;
import org.citygml4j.model.versioning.VersionTransition;
import org.citygml4j.model.waterbody.AbstractWaterBoundarySurface;
import org.citygml4j.model.waterbody.WaterBody;
import org.citygml4j.model.waterbody.WaterGroundSurface;
import org.citygml4j.model.waterbody.WaterSurface;
import org.citygml4j.xml.ade.ADEContext;
import org.xmlobjects.gml.model.GMLObject;
import org.xmlobjects.gml.model.base.AbstractArrayProperty;
import org.xmlobjects.gml.model.base.AbstractAssociation;
import org.xmlobjects.gml.model.base.AbstractGML;
import org.xmlobjects.gml.model.base.AbstractInlineOrByReferenceProperty;
import org.xmlobjects.gml.model.base.AbstractInlineProperty;
import org.xmlobjects.gml.model.base.AbstractProperty;
import org.xmlobjects.gml.model.base.Reference;
import org.xmlobjects.gml.model.common.GenericElement;
import org.xmlobjects.gml.model.coverage.AbstractContinuousCoverage;
import org.xmlobjects.gml.model.coverage.AbstractCoverage;
import org.xmlobjects.gml.model.coverage.AbstractDiscreteCoverage;
import org.xmlobjects.gml.model.coverage.GridCoverage;
import org.xmlobjects.gml.model.coverage.MultiCurveCoverage;
import org.xmlobjects.gml.model.coverage.MultiPointCoverage;
import org.xmlobjects.gml.model.coverage.MultiSolidCoverage;
import org.xmlobjects.gml.model.coverage.MultiSurfaceCoverage;
import org.xmlobjects.gml.model.coverage.RectifiedGridCoverage;
import org.xmlobjects.gml.model.feature.AbstractFeatureMember;
import org.xmlobjects.gml.model.feature.FeatureProperty;
import org.xmlobjects.gml.model.geometry.AbstractGeometry;
import org.xmlobjects.gml.model.geometry.AbstractInlineGeometryProperty;
import org.xmlobjects.gml.model.geometry.GeometryArrayProperty;
import org.xmlobjects.gml.model.geometry.GeometryProperty;
import org.xmlobjects.gml.model.geometry.primitives.AbstractSurfacePatch;
import org.xmlobjects.gml.model.geometry.primitives.SurfacePatchArrayProperty;
import org.xmlobjects.gml.model.temporal.TimeInstant;
import org.xmlobjects.gml.model.temporal.TimeInstantProperty;
import org.xmlobjects.gml.model.temporal.TimePeriod;
import org.xmlobjects.gml.model.valueobjects.AbstractValue;
import org.xmlobjects.gml.model.valueobjects.CompositeValue;
import org.xmlobjects.gml.model.valueobjects.Value;
import org.xmlobjects.gml.model.valueobjects.ValueArray;
import org.xmlobjects.gml.model.valueobjects.ValueProperty;
import org.xmlobjects.gml.visitor.GeometryWalker;
import java.util.ArrayList;
public abstract class ObjectWalker extends GeometryWalker implements ObjectVisitor, Walker {
final ADEWalkerHelper adeWalkerHelper = new ADEWalkerHelper(this);
boolean shouldWalk = true;
public ObjectWalker() {
ADERegistry registry = ADERegistry.getInstance();
if (registry.hasADEContexts()) {
for (ADEContext context : registry.getADEContexts())
withADEWalker(context.getADEWalker());
}
}
public ObjectWalker withADEWalker(ADEWalker walker) {
if (walker != null) {
adeWalkerHelper.addADEWalker(walker);
walker.setParentWalker(this);
}
return this;
}
public boolean shouldWalk() {
return shouldWalk;
}
public void setShouldWalk(boolean shouldWalk) {
this.shouldWalk = shouldWalk;
}
public void reset() {
shouldWalk = true;
}
public void visit(AbstractGML object) {
}
@Override
public void visit(AbstractGeometry geometry) {
visit((AbstractGML) geometry);
}
public void visit(org.xmlobjects.gml.model.feature.AbstractFeature feature) {
visit((AbstractGML) feature);
if (feature.getLocation() != null)
visit(feature.getLocation());
for (GenericElement genericElement : feature.getGenericProperties())
visit(genericElement);
}
public void visit(AbstractFeature feature) {
visit((org.xmlobjects.gml.model.feature.AbstractFeature) feature);
for (ADEProperty<?> property : new ArrayList<>(feature.getADEPropertiesOfAbstractFeature()))
visit(property);
}
public void visit(AbstractAppearance appearance) {
visit((AbstractFeatureWithLifespan) appearance);
for (ADEProperty<?> property : new ArrayList<>(appearance.getADEPropertiesOfAbstractAppearance()))
visit(property);
}
public void visit(AbstractAtomicTimeseries atomicTimeseries) {
visit((AbstractTimeseries) atomicTimeseries);
for (ADEProperty<?> property : new ArrayList<>(atomicTimeseries.getADEPropertiesOfAbstractAtomicTimeseries()))
visit(property);
}
public void visit(AbstractBridge bridge) {
visit((AbstractConstruction) bridge);
for (BridgeConstructiveElementMember member : new ArrayList<>(bridge.getBridgeConstructiveElements()))
visit(member);
for (BridgeInstallationMember member : new ArrayList<>(bridge.getBridgeInstallations()))
visit(member);
for (BridgeRoomMember member : new ArrayList<>(bridge.getBridgeRooms()))
visit(member);
for (BridgeFurnitureMember member : new ArrayList<>(bridge.getBridgeFurniture()))
visit(member);
for (AddressProperty member : new ArrayList<>(bridge.getAddresses()))
visit(member);
if (bridge.hasDeprecatedProperties()) {
DeprecatedPropertiesOfAbstractBridge deprecatedProperties = bridge.getDeprecatedProperties();
for (Reference reference : new ArrayList<>(deprecatedProperties.getOuterBridgeConstructions()))
visit(reference);
for (Reference reference : new ArrayList<>(deprecatedProperties.getOuterBridgeInstallations()))
visit(reference);
for (Reference reference : new ArrayList<>(deprecatedProperties.getInteriorBridgeInstallations()))
visit(reference);
for (Reference reference : new ArrayList<>(deprecatedProperties.getInteriorBridgeRooms()))
visit(reference);
for (BridgePartProperty property : new ArrayList<>(deprecatedProperties.getConsistsOfBridgeParts()))
visit(property);
if (deprecatedProperties.getLod1MultiSurface() != null)
visit(deprecatedProperties.getLod1MultiSurface());
if (deprecatedProperties.getLod4MultiCurve() != null)
visit(deprecatedProperties.getLod4MultiCurve());
if (deprecatedProperties.getLod4MultiSurface() != null)
visit(deprecatedProperties.getLod4MultiSurface());
if (deprecatedProperties.getLod4Solid() != null)
visit(deprecatedProperties.getLod4Solid());
if (deprecatedProperties.getLod4TerrainIntersectionCurve() != null)
visit(deprecatedProperties.getLod4TerrainIntersectionCurve());
}
for (ADEProperty<?> property : new ArrayList<>(bridge.getADEPropertiesOfAbstractBridge()))
visit(property);
}
public void visit(AbstractBuilding building) {
visit((AbstractConstruction) building);
for (BuildingConstructiveElementMember member : new ArrayList<>(building.getBuildingConstructiveElements()))
visit(member);
for (BuildingInstallationMember member : new ArrayList<>(building.getBuildingInstallations()))
visit(member);
for (BuildingRoomMember member : new ArrayList<>(building.getBuildingRooms()))
visit(member);
for (BuildingFurnitureMember member : new ArrayList<>(building.getBuildingFurniture()))
visit(member);
for (AbstractBuildingSubdivisionMember member : new ArrayList<>(building.getBuildingSubdivisions()))
visit(member);
for (AddressProperty member : new ArrayList<>(building.getAddresses()))
visit(member);
if (building.hasDeprecatedProperties()) {
DeprecatedPropertiesOfAbstractBuilding deprecatedProperties = building.getDeprecatedProperties();
for (Reference reference : new ArrayList<>(deprecatedProperties.getOuterBuildingInstallations()))
visit(reference);
for (Reference reference : new ArrayList<>(deprecatedProperties.getInteriorBuildingInstallations()))
visit(reference);
for (Reference reference : new ArrayList<>(deprecatedProperties.getInteriorRooms()))
visit(reference);
for (BuildingPartProperty property : new ArrayList<>(deprecatedProperties.getConsistsOfBuildingParts()))
visit(property);
if (deprecatedProperties.getLod0RoofEdge() != null)
visit(deprecatedProperties.getLod0RoofEdge());
if (deprecatedProperties.getLod1MultiSurface() != null)
visit(deprecatedProperties.getLod1MultiSurface());
if (deprecatedProperties.getLod4MultiCurve() != null)
visit(deprecatedProperties.getLod4MultiCurve());
if (deprecatedProperties.getLod4MultiSurface() != null)
visit(deprecatedProperties.getLod4MultiSurface());
if (deprecatedProperties.getLod4Solid() != null)
visit(deprecatedProperties.getLod4Solid());
if (deprecatedProperties.getLod4TerrainIntersectionCurve() != null)
visit(deprecatedProperties.getLod4TerrainIntersectionCurve());
}
for (ADEProperty<?> property : new ArrayList<>(building.getADEPropertiesOfAbstractBuilding()))
visit(property);
}
public void visit(AbstractBuildingSubdivision buildingSubdivision) {
visit((AbstractLogicalSpace) buildingSubdivision);
for (Reference reference : new ArrayList<>(buildingSubdivision.getBuildingConstructiveElements()))
visit(reference);
for (Reference reference : new ArrayList<>(buildingSubdivision.getBuildingFurniture()))
visit(reference);
for (Reference reference : new ArrayList<>(buildingSubdivision.getBuildingInstallations()))
visit(reference);
for (Reference reference : new ArrayList<>(buildingSubdivision.getBuildingRooms()))
visit(reference);
for (ADEProperty<?> property : new ArrayList<>(buildingSubdivision.getADEPropertiesOfAbstractBuildingSubdivision()))
visit(property);
}
public void visit(AbstractCityObject cityObject) {
visit((AbstractFeatureWithLifespan) cityObject);
for (Reference reference : new ArrayList<>(cityObject.getGeneralizesTo()))
visit(reference);
for (CityObjectRelationProperty property : new ArrayList<>(cityObject.getRelatedTo()))
visit(property);
for (AbstractAppearanceProperty property : new ArrayList<>(cityObject.getAppearances()))
visit(property);
for (AbstractDynamizerProperty property : new ArrayList<>(cityObject.getDynamizers()))
visit(property);
if (cityObject.hasDeprecatedProperties()) {
DeprecatedPropertiesOfAbstractCityObject deprecatedProperties = cityObject.getDeprecatedProperties();
for (AbstractCityObjectProperty property : new ArrayList<>(deprecatedProperties.getGeneralizesTo()))
visit(property);
}
for (ADEProperty<?> property : new ArrayList<>(cityObject.getADEPropertiesOfAbstractCityObject()))
visit(property);
}
public void visit(AbstractConstruction construction) {
visit((AbstractOccupiedSpace) construction);
for (ADEProperty<?> property : new ArrayList<>(construction.getADEPropertiesOfAbstractConstruction()))
visit(property);
}
public void visit(AbstractConstructionSurface constructionSurface) {
visit((AbstractThematicSurface) constructionSurface);
for (AbstractFillingSurfaceProperty property : new ArrayList<>(constructionSurface.getFillingSurfaces()))
visit(property);
for (ADEProperty<?> property : new ArrayList<>(constructionSurface.getADEPropertiesOfAbstractConstructionSurface()))
visit(property);
}
public void visit(AbstractConstructiveElement constructiveElement) {
visit((AbstractOccupiedSpace) constructiveElement);
for (AbstractFillingElementProperty property : new ArrayList<>(constructiveElement.getFillings()))
visit(property);
for (ADEProperty<?> property : new ArrayList<>(constructiveElement.getADEPropertiesOfAbstractConstructiveElement()))
visit(property);
}
public void visit(AbstractContinuousCoverage<?> continuousCoverage) {
visit((AbstractCoverage<?>) continuousCoverage);
}
public void visit(AbstractCoverage<?> coverage) {
visit((org.xmlobjects.gml.model.feature.AbstractFeature) coverage);
if (coverage.getDomainSet() != null)
visit(coverage.getDomainSet());
if (coverage.getRangeSet() != null && coverage.getRangeSet().getValueArrays() != null) {
for (ValueArray valueArray : coverage.getRangeSet().getValueArrays()) {
if (valueArray != null)
visit(valueArray);
}
}
}
public void visit(AbstractDiscreteCoverage<?> discreteCoverage) {
visit((AbstractCoverage<?>) discreteCoverage);
}
public void visit(AbstractDynamizer dynamizer) {
visit((AbstractFeatureWithLifespan) dynamizer);
for (ADEProperty<?> property : new ArrayList<>(dynamizer.getADEPropertiesOfAbstractDynamizer()))
visit(property);
}
public void visit(AbstractFeatureWithLifespan featureWithLifespan) {
visit((AbstractFeature) featureWithLifespan);
for (ADEProperty<?> property : new ArrayList<>(featureWithLifespan.getADEPropertiesOfAbstractFeatureWithLifespan()))
visit(property);
}
public void visit(AbstractFillingElement fillingElement) {
visit((AbstractOccupiedSpace) fillingElement);
for (ADEProperty<?> property : new ArrayList<>(fillingElement.getADEPropertiesOfAbstractFillingElement()))
visit(property);
}
public void visit(AbstractFillingSurface fillingSurface) {
visit((AbstractThematicSurface) fillingSurface);
if (fillingSurface.hasDeprecatedProperties()) {
DeprecatedPropertiesOfAbstractFillingSurface deprecatedProperties = fillingSurface.getDeprecatedProperties();
if (deprecatedProperties.getLod3ImplicitRepresentation() != null)
visit(deprecatedProperties.getLod3ImplicitRepresentation());
if (deprecatedProperties.getLod4ImplicitRepresentation() != null)
visit(deprecatedProperties.getLod4ImplicitRepresentation());
}
for (ADEProperty<?> property : new ArrayList<>(fillingSurface.getADEPropertiesOfAbstractFillingSurface()))
visit(property);
}
public void visit(AbstractFurniture furniture) {
visit((AbstractOccupiedSpace) furniture);
for (ADEProperty<?> property : new ArrayList<>(furniture.getADEPropertiesOfAbstractFurniture()))
visit(property);
}
public void visit(AbstractInstallation installation) {
visit((AbstractOccupiedSpace) installation);
for (ADEProperty<?> property : new ArrayList<>(installation.getADEPropertiesOfAbstractInstallation()))
visit(property);
}
public void visit(AbstractLogicalSpace logicalSpace) {
visit((AbstractSpace) logicalSpace);
for (ADEProperty<?> property : new ArrayList<>(logicalSpace.getADEPropertiesOfAbstractLogicalSpace()))
visit(property);
}
public void visit(AbstractOccupiedSpace occupiedSpace) {
visit((AbstractPhysicalSpace) occupiedSpace);
if (occupiedSpace.getLod1ImplicitRepresentation() != null)
visit(occupiedSpace.getLod1ImplicitRepresentation());
if (occupiedSpace.getLod2ImplicitRepresentation() != null)
visit(occupiedSpace.getLod2ImplicitRepresentation());
if (occupiedSpace.getLod3ImplicitRepresentation() != null)
visit(occupiedSpace.getLod3ImplicitRepresentation());
for (ADEProperty<?> property : new ArrayList<>(occupiedSpace.getADEPropertiesOfAbstractOccupiedSpace()))
visit(property);
}
public void visit(AbstractPhysicalSpace physicalSpace) {
visit((AbstractSpace) physicalSpace);
if (physicalSpace.getPointCloud() != null)
visit(physicalSpace.getPointCloud());
if (physicalSpace.getLod1TerrainIntersectionCurve() != null)
visit(physicalSpace.getLod1TerrainIntersectionCurve());
if (physicalSpace.getLod2TerrainIntersectionCurve() != null)
visit(physicalSpace.getLod2TerrainIntersectionCurve());
if (physicalSpace.getLod3TerrainIntersectionCurve() != null)
visit(physicalSpace.getLod3TerrainIntersectionCurve());
for (ADEProperty<?> property : new ArrayList<>(physicalSpace.getADEPropertiesOfAbstractPhysicalSpace()))
visit(property);
}
public void visit(AbstractPointCloud pointCloud) {
visit((AbstractFeature) pointCloud);
for (ADEProperty<?> property : new ArrayList<>(pointCloud.getADEPropertiesOfAbstractPointCloud()))
visit(property);
}
public void visit(AbstractReliefComponent reliefComponent) {
visit((AbstractSpaceBoundary) reliefComponent);
if (reliefComponent.getExtent() != null)
visit(reliefComponent.getExtent());
for (ADEProperty<?> property : new ArrayList<>(reliefComponent.getADEPropertiesOfAbstractReliefComponent()))
visit(property);
}
public void visit(AbstractSpace space) {
visit((AbstractCityObject) space);
for (AbstractSpaceBoundaryProperty property : new ArrayList<>(space.getBoundaries()))
visit(property);
if (space.getLod0Point() != null)
visit(space.getLod0Point());
if (space.getLod0MultiSurface() != null)
visit(space.getLod0MultiSurface());
if (space.getLod0MultiCurve() != null)
visit(space.getLod0MultiCurve());
if (space.getLod1Solid() != null)
visit(space.getLod1Solid());
if (space.getLod2Solid() != null)
visit(space.getLod2Solid());
if (space.getLod2MultiSurface() != null)
visit(space.getLod2MultiSurface());
if (space.getLod2MultiCurve() != null)
visit(space.getLod2MultiCurve());
if (space.getLod3Solid() != null)
visit(space.getLod3Solid());
if (space.getLod3MultiSurface() != null)
visit(space.getLod3MultiSurface());
if (space.getLod3MultiCurve() != null)
visit(space.getLod3MultiCurve());
for (ADEProperty<?> property : new ArrayList<>(space.getADEPropertiesOfAbstractSpace()))
visit(property);
}
public void visit(AbstractSpaceBoundary spaceBoundary) {
visit((AbstractCityObject) spaceBoundary);
for (ADEProperty<?> property : new ArrayList<>(spaceBoundary.getADEPropertiesOfAbstractSpaceBoundary()))
visit(property);
}
public void visit(AbstractSurfaceData surfaceData) {
visit((AbstractFeature) surfaceData);
for (ADEProperty<?> property : new ArrayList<>(surfaceData.getADEPropertiesOfAbstractSurfaceData()))
visit(property);
}
public void visit(AbstractTexture texture) {
visit((AbstractSurfaceData) texture);
for (ADEProperty<?> property : new ArrayList<>(texture.getADEPropertiesOfAbstractTexture()))
visit(property);
}
public void visit(AbstractThematicSurface thematicSurface) {
visit((AbstractSpaceBoundary) thematicSurface);
if (thematicSurface.getPointCloud() != null)
visit(thematicSurface.getPointCloud());
if (thematicSurface.getLod0MultiCurve() != null)
visit(thematicSurface.getLod0MultiCurve());
if (thematicSurface.getLod0MultiSurface() != null)
visit(thematicSurface.getLod0MultiSurface());
if (thematicSurface.getLod1MultiSurface() != null)
visit(thematicSurface.getLod1MultiSurface());
if (thematicSurface.getLod2MultiSurface() != null)
visit(thematicSurface.getLod2MultiSurface());
if (thematicSurface.getLod3MultiSurface() != null)
visit(thematicSurface.getLod3MultiSurface());
if (thematicSurface.hasDeprecatedProperties()) {
DeprecatedPropertiesOfAbstractThematicSurface deprecatedProperties = thematicSurface.getDeprecatedProperties();
if (deprecatedProperties.getLod4MultiSurface() != null)
visit(deprecatedProperties.getLod4MultiSurface());
}
for (ADEProperty<?> property : new ArrayList<>(thematicSurface.getADEPropertiesOfAbstractThematicSurface()))
visit(property);
}
public void visit(AbstractTimeseries timeseries) {
visit((AbstractFeature) timeseries);
for (ADEProperty<?> property : new ArrayList<>(timeseries.getADEPropertiesOfAbstractTimeseries()))
visit(property);
}
public void visit(AbstractTransportationSpace transportationSpace) {
visit((AbstractUnoccupiedSpace) transportationSpace);
for (TrafficSpaceProperty property : new ArrayList<>(transportationSpace.getTrafficSpaces()))
visit(property);
for (AuxiliaryTrafficSpaceProperty property : new ArrayList<>(transportationSpace.getAuxiliaryTrafficSpaces()))
visit(property);
for (HoleProperty property : new ArrayList<>(transportationSpace.getHoles()))
visit(property);
for (MarkingProperty property : new ArrayList<>(transportationSpace.getMarkings()))
visit(property);
if (transportationSpace.hasDeprecatedProperties()) {
DeprecatedPropertiesOfAbstractTransportationSpace deprecatedProperties = transportationSpace.getDeprecatedProperties();
if (deprecatedProperties.getLod0Network() != null)
visit(deprecatedProperties.getLod0Network());
if (deprecatedProperties.getLod1MultiSurface() != null)
visit(deprecatedProperties.getLod1MultiSurface());
if (deprecatedProperties.getLod4MultiSurface() != null)
visit(deprecatedProperties.getLod4MultiSurface());
}
for (ADEProperty<?> property : new ArrayList<>(transportationSpace.getADEPropertiesOfAbstractTransportationSpace()))
visit(property);
}
public void visit(AbstractTunnel tunnel) {
visit((AbstractConstruction) tunnel);
for (TunnelConstructiveElementMember member : new ArrayList<>(tunnel.getTunnelConstructiveElements()))
visit(member);
for (TunnelInstallationMember member : new ArrayList<>(tunnel.getTunnelInstallations()))
visit(member);
for (HollowSpaceMember member : new ArrayList<>(tunnel.getHollowSpaces()))
visit(member);
for (TunnelFurnitureMember member : new ArrayList<>(tunnel.getTunnelFurniture()))
visit(member);
if (tunnel.hasDeprecatedProperties()) {
DeprecatedPropertiesOfAbstractTunnel deprecatedProperties = tunnel.getDeprecatedProperties();
for (Reference reference : new ArrayList<>(deprecatedProperties.getOuterTunnelInstallations()))
visit(reference);
for (Reference reference : new ArrayList<>(deprecatedProperties.getInteriorTunnelInstallations()))
visit(reference);
for (Reference reference : new ArrayList<>(deprecatedProperties.getInteriorHollowSpaces()))
visit(reference);
for (TunnelPartProperty property : new ArrayList<>(deprecatedProperties.getConsistsOfTunnelParts()))
visit(property);
if (deprecatedProperties.getLod1MultiSurface() != null)
visit(deprecatedProperties.getLod1MultiSurface());
if (deprecatedProperties.getLod4MultiCurve() != null)
visit(deprecatedProperties.getLod4MultiCurve());
if (deprecatedProperties.getLod4MultiSurface() != null)
visit(deprecatedProperties.getLod4MultiSurface());
if (deprecatedProperties.getLod4Solid() != null)
visit(deprecatedProperties.getLod4Solid());
if (deprecatedProperties.getLod4TerrainIntersectionCurve() != null)
visit(deprecatedProperties.getLod4TerrainIntersectionCurve());
}
for (ADEProperty<?> property : new ArrayList<>(tunnel.getADEPropertiesOfAbstractTunnel()))
visit(property);
}
public void visit(AbstractUnoccupiedSpace unoccupiedSpace) {
visit((AbstractPhysicalSpace) unoccupiedSpace);
for (ADEProperty<?> property : new ArrayList<>(unoccupiedSpace.getADEPropertiesOfAbstractUnoccupiedSpace()))
visit(property);
}
public void visit(AbstractVegetationObject vegetationObject) {
visit((AbstractOccupiedSpace) vegetationObject);
for (ADEProperty<?> property : new ArrayList<>(vegetationObject.getADEPropertiesOfAbstractVegetationObject()))
visit(property);
}
public void visit(AbstractVersion version) {
visit((AbstractFeatureWithLifespan) version);
for (ADEProperty<?> property : new ArrayList<>(version.getADEPropertiesOfAbstractVersion()))
visit(property);
}
public void visit(AbstractVersionTransition versionTransition) {
visit((AbstractFeatureWithLifespan) versionTransition);
for (ADEProperty<?> property : new ArrayList<>(versionTransition.getADEPropertiesOfAbstractVersionTransition()))
visit(property);
}
public void visit(AbstractWaterBoundarySurface waterBoundarySurface) {
visit((AbstractThematicSurface) waterBoundarySurface);
for (ADEProperty<?> property : new ArrayList<>(waterBoundarySurface.getADEPropertiesOfAbstractWaterBoundarySurface()))
visit(property);
}
@Override
public void visit(Address address) {
visit((AbstractFeature) address);
if (address.getMultiPoint() != null)
visit(address.getMultiPoint());
for (ADEProperty<?> property : new ArrayList<>(address.getADEPropertiesOfAddress()))
visit(property);
}
@Override
public void visit(Appearance appearance) {
visit((AbstractAppearance) appearance);
for (AbstractSurfaceDataProperty property : new ArrayList<>(appearance.getSurfaceData()))
visit(property);
for (ADEProperty<?> property : new ArrayList<>(appearance.getADEPropertiesOfAppearance()))
visit(property);
}
@Override
public void visit(AuxiliaryTrafficArea auxiliaryTrafficArea) {
visit((AbstractThematicSurface) auxiliaryTrafficArea);
for (ADEProperty<?> property : new ArrayList<>(auxiliaryTrafficArea.getADEPropertiesOfAuxiliaryTrafficArea()))
visit(property);
}
@Override
public void visit(AuxiliaryTrafficSpace auxiliaryTrafficSpace) {
visit((AbstractUnoccupiedSpace) auxiliaryTrafficSpace);
for (ADEProperty<?> property : new ArrayList<>(auxiliaryTrafficSpace.getADEPropertiesOfAuxiliaryTrafficSpace()))
visit(property);
}
@Override
public void visit(BreaklineRelief breaklineRelief) {
visit((AbstractReliefComponent) breaklineRelief);
if (breaklineRelief.getRidgeOrValleyLines() != null)
visit(breaklineRelief.getRidgeOrValleyLines());
if (breaklineRelief.getBreaklines() != null)
visit(breaklineRelief.getBreaklines());
for (ADEProperty<?> property : new ArrayList<>(breaklineRelief.getADEPropertiesOfBreaklineRelief()))
visit(property);
}
@Override
public void visit(Bridge bridge) {
visit((AbstractBridge) bridge);
for (BridgePartProperty property : new ArrayList<>(bridge.getBridgeParts()))
visit(property);
for (ADEProperty<?> property : new ArrayList<>(bridge.getADEPropertiesOfBridge()))
visit(property);
}
@Override
public void visit(BridgeConstructiveElement bridgeConstructiveElement) {
visit((AbstractConstructiveElement) bridgeConstructiveElement);
if (bridgeConstructiveElement.hasDeprecatedProperties()) {
DeprecatedPropertiesOfBridgeConstructiveElement deprecatedProperties = bridgeConstructiveElement.getDeprecatedProperties();
if (deprecatedProperties.getLod1Geometry() != null)
visit(deprecatedProperties.getLod1Geometry());
if (deprecatedProperties.getLod2Geometry() != null)
visit(deprecatedProperties.getLod2Geometry());
if (deprecatedProperties.getLod3Geometry() != null)
visit(deprecatedProperties.getLod3Geometry());
if (deprecatedProperties.getLod4Geometry() != null)
visit(deprecatedProperties.getLod4Geometry());
if (deprecatedProperties.getLod4TerrainIntersectionCurve() != null)
visit(deprecatedProperties.getLod4TerrainIntersectionCurve());
if (deprecatedProperties.getLod4ImplicitRepresentation() != null)
visit(deprecatedProperties.getLod4ImplicitRepresentation());
}
for (ADEProperty<?> property : new ArrayList<>(bridgeConstructiveElement.getADEPropertiesOfBridgeConstructiveElement()))
visit(property);
}
@Override
public void visit(BridgeFurniture bridgeFurniture) {
visit((AbstractFurniture) bridgeFurniture);
if (bridgeFurniture.hasDeprecatedProperties()) {
DeprecatedPropertiesOfBridgeFurniture deprecatedProperties = bridgeFurniture.getDeprecatedProperties();
if (deprecatedProperties.getLod4Geometry() != null)
visit(deprecatedProperties.getLod4Geometry());
if (deprecatedProperties.getLod4ImplicitRepresentation() != null)
visit(deprecatedProperties.getLod4ImplicitRepresentation());
}
for (ADEProperty<?> property : new ArrayList<>(bridgeFurniture.getADEPropertiesOfBridgeFurniture()))
visit(property);
}
@Override
public void visit(BridgeInstallation bridgeInstallation) {
visit((AbstractInstallation) bridgeInstallation);
if (bridgeInstallation.hasDeprecatedProperties()) {
DeprecatedPropertiesOfBridgeInstallation deprecatedProperties = bridgeInstallation.getDeprecatedProperties();
if (deprecatedProperties.getLod2Geometry() != null)
visit(deprecatedProperties.getLod2Geometry());
if (deprecatedProperties.getLod3Geometry() != null)
visit(deprecatedProperties.getLod3Geometry());
if (deprecatedProperties.getLod4Geometry() != null)
visit(deprecatedProperties.getLod4Geometry());
if (deprecatedProperties.getLod4ImplicitRepresentation() != null)
visit(deprecatedProperties.getLod4ImplicitRepresentation());
}
for (ADEProperty<?> property : new ArrayList<>(bridgeInstallation.getADEPropertiesOfBridgeInstallation()))
visit(property);
}
@Override
public void visit(BridgePart bridgePart) {
visit((AbstractBridge) bridgePart);
for (ADEProperty<?> property : new ArrayList<>(bridgePart.getADEPropertiesOfBridgePart()))
visit(property);
}
@Override
public void visit(BridgeRoom bridgeRoom) {
visit((AbstractUnoccupiedSpace) bridgeRoom);
for (BridgeFurnitureProperty property : new ArrayList<>(bridgeRoom.getBridgeFurniture()))
visit(property);
for (BridgeInstallationProperty property : new ArrayList<>(bridgeRoom.getBridgeInstallations()))
visit(property);
if (bridgeRoom.hasDeprecatedProperties()) {
DeprecatedPropertiesOfBridgeRoom deprecatedProperties = bridgeRoom.getDeprecatedProperties();
if (deprecatedProperties.getLod4Solid() != null)
visit(deprecatedProperties.getLod4Solid());
if (deprecatedProperties.getLod4MultiSurface() != null)
visit(deprecatedProperties.getLod4MultiSurface());
}
for (ADEProperty<?> property : new ArrayList<>(bridgeRoom.getADEPropertiesOfBridgeRoom()))
visit(property);
}
@Override
public void visit(Building building) {
visit((AbstractBuilding) building);
for (BuildingPartProperty property : new ArrayList<>(building.getBuildingParts()))
visit(property);
for (ADEProperty<?> property : new ArrayList<>(building.getADEPropertiesOfBuilding()))
visit(property);
}
@Override
public void visit(BuildingConstructiveElement buildingConstructiveElement) {
visit((AbstractConstructiveElement) buildingConstructiveElement);
for (ADEProperty<?> property : new ArrayList<>(buildingConstructiveElement.getADEPropertiesOfBuildingConstructiveElement()))
visit(property);
}
@Override
public void visit(BuildingFurniture buildingFurniture) {
visit((AbstractFurniture) buildingFurniture);
if (buildingFurniture.hasDeprecatedProperties()) {
DeprecatedPropertiesOfBuildingFurniture deprecatedProperties = buildingFurniture.getDeprecatedProperties();
if (deprecatedProperties.getLod4Geometry() != null)
visit(deprecatedProperties.getLod4Geometry());
if (deprecatedProperties.getLod4ImplicitRepresentation() != null)
visit(deprecatedProperties.getLod4ImplicitRepresentation());
}
for (ADEProperty<?> property : new ArrayList<>(buildingFurniture.getADEPropertiesOfBuildingFurniture()))
visit(property);
}
@Override
public void visit(BuildingInstallation buildingInstallation) {
visit((AbstractInstallation) buildingInstallation);
if (buildingInstallation.hasDeprecatedProperties()) {
DeprecatedPropertiesOfBuildingInstallation deprecatedProperties = buildingInstallation.getDeprecatedProperties();
if (deprecatedProperties.getLod2Geometry() != null)
visit(deprecatedProperties.getLod2Geometry());
if (deprecatedProperties.getLod3Geometry() != null)
visit(deprecatedProperties.getLod3Geometry());
if (deprecatedProperties.getLod4Geometry() != null)
visit(deprecatedProperties.getLod4Geometry());
if (deprecatedProperties.getLod4ImplicitRepresentation() != null)
visit(deprecatedProperties.getLod4ImplicitRepresentation());
}
for (ADEProperty<?> property : new ArrayList<>(buildingInstallation.getADEPropertiesOfBuildingInstallation()))
visit(property);
}
@Override
public void visit(BuildingPart buildingPart) {
visit((AbstractBuilding) buildingPart);
for (ADEProperty<?> property : new ArrayList<>(buildingPart.getADEPropertiesOfBuildingPart()))
visit(property);
}
@Override
public void visit(BuildingRoom buildingRoom) {
visit((AbstractUnoccupiedSpace) buildingRoom);
for (BuildingFurnitureProperty property : new ArrayList<>(buildingRoom.getBuildingFurniture()))
visit(property);
for (BuildingInstallationProperty property : new ArrayList<>(buildingRoom.getBuildingInstallations()))
visit(property);
if (buildingRoom.hasDeprecatedProperties()) {
DeprecatedPropertiesOfBuildingRoom deprecatedProperties = buildingRoom.getDeprecatedProperties();
if (deprecatedProperties.getLod4Solid() != null)
visit(deprecatedProperties.getLod4Solid());
if (deprecatedProperties.getLod4MultiSurface() != null)
visit(deprecatedProperties.getLod4MultiSurface());
}
for (ADEProperty<?> property : new ArrayList<>(buildingRoom.getADEPropertiesOfBuildingRoom()))
visit(property);
}
@Override
public void visit(BuildingUnit buildingUnit) {
visit((AbstractBuildingSubdivision) buildingUnit);
for (Reference reference : new ArrayList<>(buildingUnit.getStoreys()))
visit(reference);
for (AddressProperty property : new ArrayList<>(buildingUnit.getAddresses()))
visit(property);
for (ADEProperty<?> property : new ArrayList<>(buildingUnit.getADEPropertiesOfBuildingUnit()))
visit(property);
}
@Override
public void visit(CeilingSurface ceilingSurface) {
visit((AbstractConstructionSurface) ceilingSurface);
for (ADEProperty<?> property : new ArrayList<>(ceilingSurface.getADEPropertiesOfCeilingSurface()))
visit(property);
}
@Override
public void visit(CityFurniture cityFurniture) {
visit((AbstractOccupiedSpace) cityFurniture);
if (cityFurniture.hasDeprecatedProperties()) {
DeprecatedPropertiesOfCityFurniture deprecatedProperties = cityFurniture.getDeprecatedProperties();
if (deprecatedProperties.getLod1Geometry() != null)
visit(deprecatedProperties.getLod1Geometry());
if (deprecatedProperties.getLod2Geometry() != null)
visit(deprecatedProperties.getLod2Geometry());
if (deprecatedProperties.getLod3Geometry() != null)
visit(deprecatedProperties.getLod3Geometry());
if (deprecatedProperties.getLod4Geometry() != null)
visit(deprecatedProperties.getLod4Geometry());
if (deprecatedProperties.getLod4TerrainIntersectionCurve() != null)
visit(deprecatedProperties.getLod4TerrainIntersectionCurve());
if (deprecatedProperties.getLod4ImplicitRepresentation() != null)
visit(deprecatedProperties.getLod4ImplicitRepresentation());
}
for (ADEProperty<?> property : new ArrayList<>(cityFurniture.getADEPropertiesOfCityFurniture()))
visit(property);
}
@Override
public void visit(CityModel cityModel) {
visit((AbstractFeatureWithLifespan) cityModel);
for (AbstractCityObjectProperty property : new ArrayList<>(cityModel.getCityObjectMembers()))
visit(property);
for (AbstractAppearanceProperty property : new ArrayList<>(cityModel.getAppearanceMembers()))
visit(property);
for (AbstractFeatureProperty property : new ArrayList<>(cityModel.getFeatureMembers()))
visit(property);
for (AbstractVersionProperty property : new ArrayList<>(cityModel.getVersionMembers()))
visit(property);
for (AbstractVersionTransitionProperty property : new ArrayList<>(cityModel.getVersionTransitionMembers()))
visit(property);
for (ADEProperty<?> property : new ArrayList<>(cityModel.getADEPropertiesOfCityModel()))
visit(property);
}
@Override
public void visit(CityObjectGroup cityObjectGroup) {
visit((AbstractLogicalSpace) cityObjectGroup);
for (RoleProperty property : new ArrayList<>(cityObjectGroup.getGroupMembers()))
visit(property);
if (cityObjectGroup.getGroupParent() != null)
visit(cityObjectGroup.getGroupParent());
if (cityObjectGroup.hasDeprecatedProperties()) {
DeprecatedPropertiesOfCityObjectGroup deprecatedProperties = cityObjectGroup.getDeprecatedProperties();
if (deprecatedProperties.getGeometry() != null)
visit(deprecatedProperties.getGeometry());
}
for (ADEProperty<?> property : new ArrayList<>(cityObjectGroup.getADEPropertiesOfCityObjectGroup()))
visit(property);
}
@Override
public void visit(CityObjectRelation cityObjectRelation) {
visit((AbstractGML) cityObjectRelation);
if (cityObjectRelation.getRelatedTo() != null)
visit(cityObjectRelation.getRelatedTo());
}
@Override
public void visit(ClearanceSpace clearanceSpace) {
visit((AbstractUnoccupiedSpace) clearanceSpace);
for (ADEProperty<?> property : new ArrayList<>(clearanceSpace.getADEPropertiesOfClearanceSpace()))
visit(property);
}
@Override
public void visit(ClosureSurface closureSurface) {
visit((AbstractThematicSurface) closureSurface);
for (ADEProperty<?> property : new ArrayList<>(closureSurface.getADEPropertiesOfClosureSurface()))
visit(property);
}
@Override
public void visit(CompositeTimeseries compositeTimeseries) {
visit((AbstractTimeseries) compositeTimeseries);
for (TimeseriesComponentProperty property : new ArrayList<>(compositeTimeseries.getComponents()))
visit(property);
for (ADEProperty<?> property : new ArrayList<>(compositeTimeseries.getADEPropertiesOfCompositeTimeseries()))
visit(property);
}
@Override
public void visit(CompositeValue compositeValue) {
visit((AbstractGML) compositeValue);
for (ValueProperty property : new ArrayList<>(compositeValue.getValueComponent())) {
if (property.getObject() != null)
visit(property.getObject());
}
if (compositeValue.getValueComponents() != null) {
for (Value value : compositeValue.getValueComponents().getObjects()) {
if (value != null)
visit(value);
}
}
}
@Override
public void visit(Door door) {
visit((AbstractFillingElement) door);
for (AddressProperty property : new ArrayList<>(door.getAddresses()))
visit(property);
for (ADEProperty<?> property : new ArrayList<>(door.getADEPropertiesOfDoor()))
visit(property);
}
@Override
public void visit(DoorSurface doorSurface) {
visit((AbstractFillingSurface) doorSurface);
for (AddressProperty property : new ArrayList<>(doorSurface.getAddresses()))
visit(property);
for (ADEProperty<?> property : new ArrayList<>(doorSurface.getADEPropertiesOfDoorSurface()))
visit(property);
}
@Override
public void visit(Dynamizer dynamizer) {
visit((AbstractDynamizer) dynamizer);
if (dynamizer.getDynamicData() != null)
visit(dynamizer.getDynamicData());
for (ADEProperty<?> property : new ArrayList<>(dynamizer.getADEPropertiesOfDynamizer()))
visit(property);
}
@Override
public void visit(FloorSurface floorSurface) {
visit((AbstractConstructionSurface) floorSurface);
for (ADEProperty<?> property : new ArrayList<>(floorSurface.getADEPropertiesOfFloorSurface()))
visit(property);
}
@Override
public void visit(GenericLogicalSpace genericLogicalSpace) {
visit((AbstractLogicalSpace) genericLogicalSpace);
for (ADEProperty<?> property : new ArrayList<>(genericLogicalSpace.getADEPropertiesOfGenericLogicalSpace()))
visit(property);
}
@Override
public void visit(GenericOccupiedSpace genericOccupiedSpace) {
visit((AbstractOccupiedSpace) genericOccupiedSpace);
if (genericOccupiedSpace.hasDeprecatedProperties()) {
DeprecatedPropertiesOfGenericOccupiedSpace deprecatedProperties = genericOccupiedSpace.getDeprecatedProperties();
if (deprecatedProperties.getLod0Geometry() != null)
visit(deprecatedProperties.getLod0Geometry());
if (deprecatedProperties.getLod1Geometry() != null)
visit(deprecatedProperties.getLod1Geometry());
if (deprecatedProperties.getLod2Geometry() != null)
visit(deprecatedProperties.getLod2Geometry());
if (deprecatedProperties.getLod3Geometry() != null)
visit(deprecatedProperties.getLod3Geometry());
if (deprecatedProperties.getLod4Geometry() != null)
visit(deprecatedProperties.getLod4Geometry());
if (deprecatedProperties.getLod0TerrainIntersectionCurve() != null)
visit(deprecatedProperties.getLod0TerrainIntersectionCurve());
if (deprecatedProperties.getLod4TerrainIntersectionCurve() != null)
visit(deprecatedProperties.getLod4TerrainIntersectionCurve());
if (deprecatedProperties.getLod0ImplicitRepresentation() != null)
visit(deprecatedProperties.getLod0ImplicitRepresentation());
if (deprecatedProperties.getLod4ImplicitRepresentation() != null)
visit(deprecatedProperties.getLod4ImplicitRepresentation());
}
for (ADEProperty<?> property : new ArrayList<>(genericOccupiedSpace.getADEPropertiesOfGenericOccupiedSpace()))
visit(property);
}
@Override
public void visit(GenericThematicSurface genericThematicSurface) {
visit((AbstractThematicSurface) genericThematicSurface);
for (ADEProperty<?> property : new ArrayList<>(genericThematicSurface.getADEPropertiesOfGenericThematicSurface()))
visit(property);
}
@Override
public void visit(GenericTimeseries genericTimeseries) {
visit((AbstractAtomicTimeseries) genericTimeseries);
for (TimeValuePairProperty property : genericTimeseries.getTimeValuePairs()) {
if (property.getObject() != null)
visit(property.getObject());
}
for (ADEProperty<?> property : new ArrayList<>(genericTimeseries.getADEPropertiesOfGenericTimeseries()))
visit(property);
}
@Override
public void visit(GenericUnoccupiedSpace genericUnoccupiedSpace) {
visit((AbstractUnoccupiedSpace) genericUnoccupiedSpace);
for (ADEProperty<?> property : new ArrayList<>(genericUnoccupiedSpace.getADEPropertiesOfGenericUnoccupiedSpace()))
visit(property);
}
@Override
public void visit(GeoreferencedTexture georeferencedTexture) {
visit((AbstractTexture) georeferencedTexture);
if (georeferencedTexture.getReferencePoint() != null)
visit(georeferencedTexture.getReferencePoint());
for (ADEProperty<?> property : new ArrayList<>(georeferencedTexture.getADEPropertiesOfGeoreferencedTexture()))
visit(property);
}
@Override
public void visit(GridCoverage gridCoverage) {
visit((AbstractDiscreteCoverage<?>) gridCoverage);
}
@Override
public void visit(GroundSurface groundSurface) {
visit((AbstractConstructionSurface) groundSurface);
for (ADEProperty<?> property : new ArrayList<>(groundSurface.getADEPropertiesOfGroundSurface()))
visit(property);
}
@Override
public void visit(Hole hole) {
visit((AbstractUnoccupiedSpace) hole);
for (ADEProperty<?> property : new ArrayList<>(hole.getADEPropertiesOfHole()))
visit(property);
}
@Override
public void visit(HoleSurface holeSurface) {
visit((AbstractThematicSurface) holeSurface);
for (ADEProperty<?> property : new ArrayList<>(holeSurface.getADEPropertiesOfHoleSurface()))
visit(property);
}
@Override
public void visit(HollowSpace hollowSpace) {
visit((AbstractUnoccupiedSpace) hollowSpace);
for (TunnelFurnitureProperty property : new ArrayList<>(hollowSpace.getTunnelFurniture()))
visit(property);
for (TunnelInstallationProperty property : new ArrayList<>(hollowSpace.getTunnelInstallations()))
visit(property);
if (hollowSpace.hasDeprecatedProperties()) {
DeprecatedPropertiesOfHollowSpace deprecatedProperties = hollowSpace.getDeprecatedProperties();
if (deprecatedProperties.getLod4Solid() != null)
visit(deprecatedProperties.getLod4Solid());
if (deprecatedProperties.getLod4MultiSurface() != null)
visit(deprecatedProperties.getLod4MultiSurface());
}
for (ADEProperty<?> property : new ArrayList<>(hollowSpace.getADEPropertiesOfHollowSpace()))
visit(property);
}
@Override
public void visit(ImplicitGeometry implicitGeometry) {
visit((AbstractGML) implicitGeometry);
for (AbstractAppearanceProperty property : new ArrayList<>(implicitGeometry.getAppearances()))
visit(property);
if (implicitGeometry.getReferencePoint() != null)
visit(implicitGeometry.getReferencePoint());
if (implicitGeometry.getRelativeGeometry() != null)
visit(implicitGeometry.getRelativeGeometry());
}
@Override
public void visit(InteriorWallSurface interiorWallSurface) {
visit((AbstractConstructionSurface) interiorWallSurface);
for (ADEProperty<?> property : new ArrayList<>(interiorWallSurface.getADEPropertiesOfInteriorWallSurface()))
visit(property);
}
@Override
public void visit(Intersection intersection) {
visit((AbstractTransportationSpace) intersection);
for (ADEProperty<?> property : new ArrayList<>(intersection.getADEPropertiesOfIntersection()))
visit(property);
}
@Override
public void visit(LandUse landUse) {
visit((AbstractThematicSurface) landUse);
for (ADEProperty<?> property : new ArrayList<>(landUse.getADEPropertiesOfLandUse()))
visit(property);
}
@Override
public void visit(Marking marking) {
visit((AbstractThematicSurface) marking);
for (ADEProperty<?> property : new ArrayList<>(marking.getADEPropertiesOfMarking()))
visit(property);
}
@Override
public void visit(MassPointRelief massPointRelief) {
visit((AbstractReliefComponent) massPointRelief);
if (massPointRelief.getPointCloud() != null)
visit(massPointRelief.getPointCloud());
if (massPointRelief.getReliefPoints() != null)
visit(massPointRelief.getReliefPoints());
for (ADEProperty<?> property : new ArrayList<>(massPointRelief.getADEPropertiesOfMassPointRelief()))
visit(property);
}
@Override
public void visit(MultiCurveCoverage multiCurveCoverage) {
visit((AbstractDiscreteCoverage<?>) multiCurveCoverage);
}
@Override
public void visit(MultiPointCoverage multiPointCoverage) {
visit((AbstractDiscreteCoverage<?>) multiPointCoverage);
}
@Override
public void visit(MultiSolidCoverage multiSolidCoverage) {
visit((AbstractDiscreteCoverage<?>) multiSolidCoverage);
}
@Override
public void visit(MultiSurfaceCoverage multiSurfaceCoverage) {
visit((AbstractDiscreteCoverage<?>) multiSurfaceCoverage);
}
@Override
public void visit(OtherConstruction otherConstruction) {
visit((AbstractConstruction) otherConstruction);
for (ADEProperty<?> property : new ArrayList<>(otherConstruction.getADEPropertiesOfOtherConstruction()))
visit(property);
}
@Override
public void visit(OuterCeilingSurface outerCeilingSurface) {
visit((AbstractConstructionSurface) outerCeilingSurface);
for (ADEProperty<?> property : new ArrayList<>(outerCeilingSurface.getADEPropertiesOfOuterCeilingSurface()))
visit(property);
}
@Override
public void visit(OuterFloorSurface outerFloorSurface) {
visit((AbstractConstructionSurface) outerFloorSurface);
for (ADEProperty<?> property : new ArrayList<>(outerFloorSurface.getADEPropertiesOfOuterFloorSurface()))
visit(property);
}
@Override
public void visit(ParameterizedTexture parameterizedTexture) {
visit((AbstractTexture) parameterizedTexture);
for (ADEProperty<?> property : new ArrayList<>(parameterizedTexture.getADEPropertiesOfParameterizedTexture()))
visit(property);
}
@Override
public void visit(PlantCover plantCover) {
visit((AbstractVegetationObject) plantCover);
if (plantCover.hasDeprecatedProperties()) {
DeprecatedPropertiesOfPlantCover deprecatedProperties = plantCover.getDeprecatedProperties();
if (deprecatedProperties.getLod1MultiSurface() != null)
visit(deprecatedProperties.getLod1MultiSurface());
if (deprecatedProperties.getLod4MultiSurface() != null)
visit(deprecatedProperties.getLod4MultiSurface());
if (deprecatedProperties.getLod1MultiSolid() != null)
visit(deprecatedProperties.getLod1MultiSolid());
if (deprecatedProperties.getLod2MultiSolid() != null)
visit(deprecatedProperties.getLod2MultiSolid());
if (deprecatedProperties.getLod3MultiSolid() != null)
visit(deprecatedProperties.getLod3MultiSolid());
if (deprecatedProperties.getLod4MultiSolid() != null)
visit(deprecatedProperties.getLod4MultiSolid());
}
for (ADEProperty<?> property : new ArrayList<>(plantCover.getADEPropertiesOfPlantCover()))
visit(property);
}
@Override
public void visit(PointCloud pointCloud) {
visit((AbstractPointCloud) pointCloud);
if (pointCloud.getPoints() != null)
visit(pointCloud.getPoints());
for (ADEProperty<?> property : new ArrayList<>(pointCloud.getADEPropertiesOfPointCloud()))
visit(property);
}
@Override
public void visit(Railway railway) {
visit((AbstractTransportationSpace) railway);
for (SectionProperty property : new ArrayList<>(railway.getSections()))
visit(property);
for (IntersectionProperty property : new ArrayList<>(railway.getIntersections()))
visit(property);
for (ADEProperty<?> property : new ArrayList<>(railway.getADEPropertiesOfRailway()))
visit(property);
}
@Override
public void visit(RasterRelief rasterRelief) {
visit((AbstractReliefComponent) rasterRelief);
if (rasterRelief.getGrid() != null)
visit(rasterRelief.getGrid());
for (ADEProperty<?> property : new ArrayList<>(rasterRelief.getADEPropertiesOfRasterRelief()))
visit(property);
}
@Override
public void visit(RectifiedGridCoverage rectifiedGridCoverage) {
visit((AbstractDiscreteCoverage<?>) rectifiedGridCoverage);
}
@Override
public void visit(ReliefFeature reliefFeature) {
visit((AbstractSpaceBoundary) reliefFeature);
for (AbstractReliefComponentProperty property : new ArrayList<>(reliefFeature.getReliefComponents()))
visit(property);
for (ADEProperty<?> property : new ArrayList<>(reliefFeature.getADEPropertiesOfReliefFeature()))
visit(property);
}
@Override
public void visit(Road road) {
visit((AbstractTransportationSpace) road);
for (SectionProperty property : new ArrayList<>(road.getSections()))
visit(property);
for (IntersectionProperty property : new ArrayList<>(road.getIntersections()))
visit(property);
for (ADEProperty<?> property : new ArrayList<>(road.getADEPropertiesOfRoad()))
visit(property);
}
public void visit(Role role) {
visit((AbstractGML) role);
if (role.getGroupMember() != null)
visit(role.getGroupMember());
}
@Override
public void visit(RoofSurface roofSurface) {
visit((AbstractConstructionSurface) roofSurface);
for (ADEProperty<?> property : new ArrayList<>(roofSurface.getADEPropertiesOfRoofSurface()))
visit(property);
}
@Override
public void visit(Section section) {
visit((AbstractTransportationSpace) section);
for (ADEProperty<?> property : new ArrayList<>(section.getADEPropertiesOfSection()))
visit(property);
}
@Override
public void visit(SolitaryVegetationObject solitaryVegetationObject) {
visit((AbstractVegetationObject) solitaryVegetationObject);
if (solitaryVegetationObject.hasDeprecatedProperties()) {
DeprecatedPropertiesOfSolitaryVegetationObject deprecatedProperties = solitaryVegetationObject.getDeprecatedProperties();
if (deprecatedProperties.getLod1Geometry() != null)
visit(deprecatedProperties.getLod1Geometry());
if (deprecatedProperties.getLod2Geometry() != null)
visit(deprecatedProperties.getLod2Geometry());
if (deprecatedProperties.getLod3Geometry() != null)
visit(deprecatedProperties.getLod3Geometry());
if (deprecatedProperties.getLod4Geometry() != null)
visit(deprecatedProperties.getLod4Geometry());
if (deprecatedProperties.getLod4ImplicitRepresentation() != null)
visit(deprecatedProperties.getLod4ImplicitRepresentation());
}
for (ADEProperty<?> property : new ArrayList<>(solitaryVegetationObject.getADEPropertiesOfSolitaryVegetationObject()))
visit(property);
}
@Override
public void visit(Square square) {
visit((AbstractTransportationSpace) square);
for (ADEProperty<?> property : new ArrayList<>(square.getADEPropertiesOfSquare()))
visit(property);
}
@Override
public void visit(StandardFileTimeseries standardFileTimeseries) {
visit((AbstractAtomicTimeseries) standardFileTimeseries);
for (ADEProperty<?> property : new ArrayList<>(standardFileTimeseries.getADEPropertiesOfStandardFileTimeseries()))
visit(property);
}
@Override
public void visit(Storey storey) {
visit((AbstractBuildingSubdivision) storey);
for (Reference reference : new ArrayList<>(storey.getBuildingUnits()))
visit(reference);
for (ADEProperty<?> property : new ArrayList<>(storey.getADEPropertiesOfStorey()))
visit(property);
}
@Override
public void visit(TabulatedFileTimeseries tabulatedFileTimeseries) {
visit((AbstractAtomicTimeseries) tabulatedFileTimeseries);
for (ADEProperty<?> property : new ArrayList<>(tabulatedFileTimeseries.getADEPropertiesOfTabulatedFileTimeseries()))
visit(property);
}
@Override
public void visit(TextureAssociation textureAssociation) {
visit((AbstractGML) textureAssociation);
}
@Override
public void visit(TimeInstant timeInstant) {
visit((AbstractGML) timeInstant);
}
@Override
public void visit(TimePeriod timePeriod) {
visit((AbstractGML) timePeriod);
if (timePeriod.getBegin() != null)
visit(timePeriod.getBegin());
if (timePeriod.getEnd() != null)
visit(timePeriod.getEnd());
}
@Override
public void visit(TINRelief tinRelief) {
visit((AbstractReliefComponent) tinRelief);
if (tinRelief.getTin() != null)
visit(tinRelief.getTin());
for (ADEProperty<?> property : new ArrayList<>(tinRelief.getADEPropertiesOfTINRelief()))
visit(property);
}
@Override
public void visit(Track track) {
visit((AbstractTransportationSpace) track);
for (SectionProperty property : new ArrayList<>(track.getSections()))
visit(property);
for (IntersectionProperty property : new ArrayList<>(track.getIntersections()))
visit(property);
for (ADEProperty<?> property : new ArrayList<>(track.getADEPropertiesOfTrack()))
visit(property);
}
@Override
public void visit(TrafficArea trafficArea) {
visit((AbstractThematicSurface) trafficArea);
for (ADEProperty<?> property : new ArrayList<>(trafficArea.getADEPropertiesOfTrafficArea()))
visit(property);
}
@Override
public void visit(TrafficSpace trafficSpace) {
visit((AbstractUnoccupiedSpace) trafficSpace);
for (TrafficSpaceProperty property : new ArrayList<>(trafficSpace.getPredecessors()))
visit(property);
for (TrafficSpaceProperty property : new ArrayList<>(trafficSpace.getSuccessors()))
visit(property);
for (ClearanceSpaceProperty property : new ArrayList<>(trafficSpace.getClearanceSpaces()))
visit(property);
for (ADEProperty<?> property : new ArrayList<>(trafficSpace.getADEPropertiesOfTrafficSpace()))
visit(property);
}
@Override
public void visit(TransportationComplex transportationComplex) {
visit((AbstractTransportationSpace) transportationComplex);
for (ADEProperty<?> property : new ArrayList<>(transportationComplex.getADEPropertiesOfTransportationComplex()))
visit(property);
}
@Override
public void visit(Tunnel tunnel) {
visit((AbstractTunnel) tunnel);
for (TunnelPartProperty property : new ArrayList<>(tunnel.getTunnelParts()))
visit(property);
for (ADEProperty<?> property : new ArrayList<>(tunnel.getADEPropertiesOfTunnel()))
visit(property);
}
@Override
public void visit(TunnelConstructiveElement tunnelConstructiveElement) {
visit((AbstractConstructiveElement) tunnelConstructiveElement);
for (ADEProperty<?> property : new ArrayList<>(tunnelConstructiveElement.getADEPropertiesOfTunnelConstructiveElement()))
visit(property);
}
@Override
public void visit(TunnelFurniture tunnelFurniture) {
visit((AbstractFurniture) tunnelFurniture);
if (tunnelFurniture.hasDeprecatedProperties()) {
DeprecatedPropertiesOfTunnelFurniture deprecatedProperties = tunnelFurniture.getDeprecatedProperties();
if (deprecatedProperties.getLod4Geometry() != null)
visit(deprecatedProperties.getLod4Geometry());
if (deprecatedProperties.getLod4ImplicitRepresentation() != null)
visit(deprecatedProperties.getLod4ImplicitRepresentation());
}
for (ADEProperty<?> property : new ArrayList<>(tunnelFurniture.getADEPropertiesOfTunnelFurniture()))
visit(property);
}
@Override
public void visit(TunnelInstallation tunnelInstallation) {
visit((AbstractInstallation) tunnelInstallation);
if (tunnelInstallation.hasDeprecatedProperties()) {
DeprecatedPropertiesOfTunnelInstallation deprecatedProperties = tunnelInstallation.getDeprecatedProperties();
if (deprecatedProperties.getLod2Geometry() != null)
visit(deprecatedProperties.getLod2Geometry());
if (deprecatedProperties.getLod3Geometry() != null)
visit(deprecatedProperties.getLod3Geometry());
if (deprecatedProperties.getLod4Geometry() != null)
visit(deprecatedProperties.getLod4Geometry());
if (deprecatedProperties.getLod4ImplicitRepresentation() != null)
visit(deprecatedProperties.getLod4ImplicitRepresentation());
}
for (ADEProperty<?> property : new ArrayList<>(tunnelInstallation.getADEPropertiesOfTunnelInstallation()))
visit(property);
}
@Override
public void visit(TunnelPart tunnelPart) {
visit((AbstractTunnel) tunnelPart);
for (ADEProperty<?> property : new ArrayList<>(tunnelPart.getADEPropertiesOfTunnelPart()))
visit(property);
}
@Override
public void visit(ValueArray valueArray) {
visit((CompositeValue) valueArray);
}
@Override
public void visit(Version version) {
visit((AbstractVersion) version);
for (AbstractFeatureWithLifespanProperty property : new ArrayList<>(version.getVersionMembers()))
visit(property);
for (ADEProperty<?> property : new ArrayList<>(version.getADEPropertiesOfVersion()))
visit(property);
}
@Override
public void visit(VersionTransition versionTransition) {
visit((AbstractVersionTransition) versionTransition);
if (versionTransition.getFrom() != null)
visit(versionTransition.getFrom());
if (versionTransition.getTo() != null)
visit(versionTransition.getTo());
for (ADEProperty<?> property : new ArrayList<>(versionTransition.getADEPropertiesOfVersionTransition()))
visit(property);
}
@Override
public void visit(WallSurface wallSurface) {
visit((AbstractConstructionSurface) wallSurface);
for (ADEProperty<?> property : new ArrayList<>(wallSurface.getADEPropertiesOfWallSurface()))
visit(property);
}
@Override
public void visit(WaterBody waterBody) {
visit((AbstractOccupiedSpace) waterBody);
if (waterBody.hasDeprecatedProperties()) {
DeprecatedPropertiesOfWaterBody deprecatedProperties = waterBody.getDeprecatedProperties();
if (deprecatedProperties.getLod1MultiCurve() != null)
visit(deprecatedProperties.getLod1MultiCurve());
if (deprecatedProperties.getLod1MultiSurface() != null)
visit(deprecatedProperties.getLod1MultiSurface());
if (deprecatedProperties.getLod4Solid() != null)
visit(deprecatedProperties.getLod4Solid());
}
for (ADEProperty<?> property : new ArrayList<>(waterBody.getADEPropertiesOfWaterBody()))
visit(property);
}
@Override
public void visit(WaterGroundSurface waterGroundSurface) {
visit((AbstractWaterBoundarySurface) waterGroundSurface);
for (ADEProperty<?> property : new ArrayList<>(waterGroundSurface.getADEPropertiesOfWaterGroundSurface()))
visit(property);
}
@Override
public void visit(WaterSurface waterSurface) {
visit((AbstractWaterBoundarySurface) waterSurface);
for (ADEProperty<?> property : new ArrayList<>(waterSurface.getADEPropertiesOfWaterSurface()))
visit(property);
}
@Override
public void visit(Waterway waterway) {
visit((AbstractTransportationSpace) waterway);
for (SectionProperty property : new ArrayList<>(waterway.getSections()))
visit(property);
for (IntersectionProperty property : new ArrayList<>(waterway.getIntersections()))
visit(property);
for (ADEProperty<?> property : new ArrayList<>(waterway.getADEPropertiesOfWaterway()))
visit(property);
}
@Override
public void visit(Window window) {
visit((AbstractFillingElement) window);
for (ADEProperty<?> property : new ArrayList<>(window.getADEPropertiesOfWindow()))
visit(property);
}
@Override
public void visit(WindowSurface windowSurface) {
visit((AbstractFillingSurface) windowSurface);
for (ADEProperty<?> property : new ArrayList<>(windowSurface.getADEPropertiesOfWindowSurface()))
visit(property);
}
@Override
public void visit(X3DMaterial x3dMaterial) {
visit((AbstractSurfaceData) x3dMaterial);
for (ADEProperty<?> property : new ArrayList<>(x3dMaterial.getADEPropertiesOfX3DMaterial()))
visit(property);
}
@Override
public void visit(ADEObject adeObject) {
boolean visited = adeWalkerHelper.visitObject(adeObject, adeObject.getClass());
if (!visited) {
if (adeObject instanceof ADEProperty<?>)
visitObject(((ADEProperty<?>) adeObject).getValue());
else if (adeObject instanceof GMLObject) {
Class<?> parent = adeObject.getClass().getSuperclass();
if (parent != null)
adeWalkerHelper.visitObject(adeObject, parent);
adeWalkerHelper.visitFields(adeObject);
}
}
}
public void visit(GenericElement genericElement) {
}
public void visit(FeatureProperty<?> property) {
visit((AbstractProperty<?>) property);
if (shouldWalk && property != null && property.getGenericElement() != null)
visit(property.getGenericElement());
}
public void visit(AbstractFeatureMember<?> member) {
visit((AbstractInlineProperty<?>) member);
if (shouldWalk && member != null && member.getGenericElement() != null)
visit(member.getGenericElement());
}
protected void visitObject(Object object) {
if (object instanceof ADEObject)
visit((ADEObject) object);
else if (object instanceof Visitable)
((Visitable) object).accept(this);
else if (object instanceof AbstractCoverage)
((AbstractCoverage<?>) object).accept(this);
else if (object instanceof AbstractGeometry)
((AbstractGeometry) object).accept(this);
else if (object instanceof AbstractSurfacePatch)
((AbstractSurfacePatch) object).accept(this);
else if (object instanceof AbstractAssociation<?>)
visitProperty((AbstractAssociation<?>) object);
}
private void visitProperty(AbstractAssociation<?> property) {
if (property instanceof FeatureProperty<?>)
visit((FeatureProperty<?>) property);
else if (property instanceof GeometryProperty<?>)
visit((GeometryProperty<?>) property);
else if (property instanceof AbstractFeatureMember<?>)
visit((AbstractFeatureMember<?>) property);
else if (property instanceof Reference)
visit((Reference) property);
else if (property instanceof GeometryArrayProperty<?>)
visit((GeometryArrayProperty<?>) property);
else if (property instanceof SurfacePatchArrayProperty<?>)
visit((SurfacePatchArrayProperty<?>) property);
else if (property instanceof AbstractInlineGeometryProperty<?>)
visit((AbstractInlineGeometryProperty<?>) property);
else if (property instanceof AbstractInlineProperty<?>)
visit((AbstractInlineProperty<?>) property);
else if (property instanceof AbstractProperty<?>)
visit((AbstractProperty<?>) property);
else if (property instanceof AbstractInlineOrByReferenceProperty<?>)
visit((AbstractInlineOrByReferenceProperty<?>) property);
else if (property instanceof AbstractArrayProperty<?>)
visit((AbstractArrayProperty<?>) property);
}
private void visit(Value value) {
if (shouldWalk) {
if (value.getValue() != null)
visit(value.getValue());
else if (value.getGeometry() != null)
value.getGeometry().accept(this);
else if (value.getGenericElement() != null)
visit(value.getGenericElement());
}
}
private void visit(AbstractValue value) {
if (value instanceof ADEObject)
visit((ADEObject) value);
else if (value instanceof CompositeValue)
((CompositeValue) value).accept(this);
}
private void visit(TimeInstantProperty property) {
if (shouldWalk && property != null && property.getObject() != null)
property.getObject().accept(this);
}
private void visit(TimeValuePair timeValuePair) {
if (shouldWalk) {
if (timeValuePair.getGeometryValue() != null)
visit(timeValuePair.getGeometryValue());
else if (timeValuePair.getImplicitGeometryValue() != null)
visit(timeValuePair.getImplicitGeometryValue());
else if (timeValuePair.getAppearanceValue() != null)
visit(timeValuePair.getAppearanceValue());
}
}
}
|
package org.cojen.tupl.rows;
import java.lang.invoke.CallSite;
import java.lang.invoke.MethodHandle;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.invoke.VarHandle;
import java.lang.ref.WeakReference;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.TreeMap;
import java.util.function.IntFunction;
import org.cojen.maker.ClassMaker;
import org.cojen.maker.Field;
import org.cojen.maker.Label;
import org.cojen.maker.MethodMaker;
import org.cojen.maker.Variable;
import org.cojen.tupl.CorruptDatabaseException;
import org.cojen.tupl.Cursor;
import org.cojen.tupl.DatabaseException;
import org.cojen.tupl.filter.AndFilter;
import org.cojen.tupl.filter.ColumnToArgFilter;
import org.cojen.tupl.filter.ColumnToColumnFilter;
import org.cojen.tupl.filter.OrFilter;
import org.cojen.tupl.filter.Parser;
import org.cojen.tupl.filter.RowFilter;
import org.cojen.tupl.filter.Visitor;
import org.cojen.tupl.io.Utils;
/**
* Makes RowDecoderEncoder classes which are instantiated by a factory.
*
* @author Brian S O'Neill
*/
public class RowFilterMaker<R> {
private static long cFilterNum;
private static final VarHandle cFilterNumHandle;
static {
try {
cFilterNumHandle =
MethodHandles.lookup().findStaticVarHandle
(RowFilterMaker.class, "cFilterNum", long.class);
} catch (Throwable e) {
throw Utils.rethrow(e);
}
}
private final WeakReference<RowStore> mStoreRef;
private final Class<?> mViewClass;
private final Class<R> mRowType;
private final RowGen mRowGen;
private final long mIndexId;
private final String mFilterStr;
private final RowFilter mFilter;
private final ClassMaker mFilterMaker;
private final MethodMaker mFilterCtorMaker;
// Bound to mFilterCtorMaker.
private final ColumnCodec[] mKeyCodecs, mValueCodecs;
/**
* @param storeRef is passed along to the generated code
* @param base defines the encode methods; the decode method will be overridden
*/
public RowFilterMaker(WeakReference<RowStore> storeRef, Class<?> viewClass,
Class<? extends RowDecoderEncoder<R>> base,
Class<R> rowType, long indexId, String filterStr, RowFilter filter)
{
mStoreRef = storeRef;
mViewClass = viewClass;
mRowType = rowType;
mRowGen = RowInfo.find(rowType).rowGen();
mIndexId = indexId;
mFilterStr = filterStr;
mFilter = filter;
// Generate a sub-package with an increasing number to facilitate unloading.
long filterNum = (long) cFilterNumHandle.getAndAdd(1L);
mFilterMaker = mRowGen.beginClassMaker(getClass(), rowType, "f" + filterNum, "Filter")
.final_().extend(base).implement(RowDecoderEncoder.class);
mFilterCtorMaker = mFilterMaker.addConstructor(Object[].class).varargs().private_();
mFilterCtorMaker.invokeSuperConstructor();
mKeyCodecs = ColumnCodec.bind(mRowGen.keyCodecs(), mFilterCtorMaker);
mValueCodecs = ColumnCodec.bind(mRowGen.valueCodecs(), mFilterCtorMaker);
}
/**
* Returns a factory method.
*/
public MethodHandle finish() {
// Finish the filter class...
// Define the fields to hold the filter arguments.
mFilter.accept(new Visitor() {
private HashSet<Integer> mAdded = new HashSet<>();
@Override
public void visit(ColumnToArgFilter filter) {
int argNum = filter.argument();
if (mAdded.add(argNum)) {
int colNum = columnNumberFor(filter.column().name());
boolean in = filter.isIn(filter.operator());
Variable argVar = mFilterCtorMaker.param(0).aget(argNum);
codecFor(colNum).filterPrepare(in, argVar, argNum);
}
}
});
// The decode method is implemented using indy, to support multiple schema versions.
{
// Defined by RowDecoderEncoder.
MethodMaker mm = mFilterMaker.addMethod
(Object.class, "decodeRow", byte[].class, byte[].class, Object.class).public_();
var indy = mm.var(RowFilterMaker.class).indy
("indyDecodeRow", mStoreRef, mViewClass, mRowType, mIndexId, mFilterStr, mFilter);
var valueVar = mm.param(1);
var schemaVersion = RowViewMaker.decodeSchemaVersion(mm, valueVar);
mm.return_(indy.invoke(Object.class, "decodeRow", null,
schemaVersion, mm.this_(), mm.param(0), valueVar, mm.param(2)));
}
// Provide access to the inherited markAllClean method.
{
Class<?> rowClass = RowMaker.find(mRowType);
MethodMaker mm = mFilterMaker.addMethod(null, "markAllClean", rowClass).static_();
mm.super_().invoke("markAllClean", mm.param(0));
}
// Factory instances are weakly cached by AbstractRowView, and so this can cause the
// generated classes to get lost. They will eventually be GC'd, but this takes longer.
// To prevent a pile up of duplicate classes, maintain a strong reference to the
// factory. As long as the filter class exists, the factory exists, and so the cache
// entry exists.
mFilterMaker.addField(Object.class, "factory").private_().static_();
MethodHandles.Lookup filterLookup = mFilterMaker.finishLookup();
Class<?> filterClass = filterLookup.lookupClass();
MethodHandle factory;
try {
var mt = MethodType.methodType(RowDecoderEncoder.class, Object[].class);
factory = filterLookup.findConstructor(filterClass, mt.changeReturnType(void.class));
factory = factory.asType(mt);
filterLookup.findStaticVarHandle(filterClass, "factory", Object.class).set(factory);
} catch (Throwable e) {
throw Utils.rethrow(e);
}
return factory;
}
private Integer columnNumberFor(String colName) {
return mRowGen.columnNumbers().get(colName);
}
private ColumnCodec codecFor(int colNum) {
ColumnCodec[] codecs = mKeyCodecs;
return colNum < codecs.length ? codecs[colNum] : mValueCodecs[colNum - codecs.length];
}
public static CallSite indyDecodeRow(MethodHandles.Lookup lookup, String name, MethodType mt,
WeakReference<RowStore> storeRef,
Class<?> viewClass, Class<?> rowType, long indexId,
String filterStr, RowFilter filter)
{
var dm = new DecodeMaker
(lookup, mt, storeRef, viewClass, rowType, indexId, filterStr, filter);
return new SwitchCallSite(lookup, mt, dm);
}
private static class DecodeMaker implements IntFunction<Object> {
private final MethodHandles.Lookup mLookup;
private final MethodType mMethodType;
private final WeakReference<RowStore> mStoreRef;
private final Class<?> mViewClass;
private final Class<?> mRowType;
private final long mIndexId;
private final String mFilterStr;
// The DecodeMaker isn't defined as a lambda function because this field cannot be final.
private WeakReference<RowFilter> mFilterRef;
DecodeMaker(MethodHandles.Lookup lookup, MethodType mt,
WeakReference<RowStore> storeRef, Class<?> viewClass,
Class<?> rowType, long indexId,
String filterStr, RowFilter filter)
{
mLookup = lookup;
mMethodType = mt.dropParameterTypes(0, 1);
mStoreRef = storeRef;
mViewClass = viewClass;
mRowType = rowType;
mIndexId = indexId;
mFilterStr = filterStr;
mFilterRef = new WeakReference<>(filter);
}
/**
* Defined in IntFunction, needed by SwitchCallSite.
*
* @return MethodHandle or ExceptionCallSite.Failed
*/
@Override
public Object apply(int schemaVersion) {
MethodMaker mm = MethodMaker.begin(mLookup, "case", mMethodType);
RowFilter filter = mFilterRef.get();
if (filter == null) {
filter = AbstractRowView.parse(mRowType, mFilterStr);
mFilterRef = new WeakReference<>(filter);
}
RowStore store = mStoreRef.get();
if (store == null) {
mm.new_(DatabaseException.class, "Closed").throw_();
return mm.finish();
}
RowInfo dstRowInfo = RowInfo.find(mRowType);
RowInfo rowInfo;
MethodHandle decoder;
try {
if (schemaVersion != 0) {
rowInfo = store.rowInfo(mRowType, mIndexId, schemaVersion);
if (rowInfo == null) {
throw new CorruptDatabaseException
("Schema version not found: " + schemaVersion);
}
} else {
// No value columns to decode, and the primary key cannot change.
rowInfo = new RowInfo(dstRowInfo.name);
rowInfo.keyColumns = dstRowInfo.keyColumns;
rowInfo.valueColumns = Collections.emptyNavigableMap();
rowInfo.allColumns = new TreeMap<>(rowInfo.keyColumns);
}
// Obtain the MethodHandle which fully decodes the value columns.
decoder = (MethodHandle) mLookup.findStatic
(mLookup.lookupClass(), "decodeValueHandle",
MethodType.methodType(MethodHandle.class, int.class))
.invokeExact(schemaVersion);
} catch (Throwable e) {
return new ExceptionCallSite.Failed(mMethodType, mm, e);
}
Class<?> rowClass = RowMaker.find(mRowType);
RowGen rowGen = rowInfo.rowGen();
var visitor = new DecodeVisitor
(mm, schemaVersion, mViewClass, dstRowInfo, rowClass, rowGen, decoder);
filter.accept(visitor);
visitor.done();
return mm.finish();
}
}
/**
* Generates code to filter and decode rows for a specific schema version.
*/
private static class DecodeVisitor extends Visitor {
private final MethodMaker mMaker;
private final int mSchemaVersion;
private final Class<?> mViewClass;
private final RowInfo mDstRowInfo;
private final Class<?> mRowClass;
private final RowGen mRowGen;
private final MethodHandle mDecoder;
private final ColumnCodec[] mKeyCodecs, mValueCodecs;
private Label mPass, mFail;
private LocatedColumn[] mLocatedKeys;
private int mHighestLocatedKey;
private LocatedColumn[] mLocatedValues;
private int mHighestLocatedValue;
/**
* @param mm signature: R decodeRow(Decoder/filter, byte[] key, byte[] value, R row)
* @param viewClass current row view implementation class
* @param dstRowInfo current row defintion
* @param rowClass current row implementation
* @param rowGen actual row defintion to be decoded (can differ from dstRowInfo)
* @param decoder performs full decoding of the value columns
*/
DecodeVisitor(MethodMaker mm, int schemaVersion,
Class<?> viewClass, RowInfo dstRowInfo, Class<?> rowClass, RowGen rowGen,
MethodHandle decoder)
{
mMaker = mm;
mSchemaVersion = schemaVersion;
mViewClass = viewClass;
mDstRowInfo = dstRowInfo;
mRowClass = rowClass;
mRowGen = rowGen;
mDecoder = decoder;
mKeyCodecs = ColumnCodec.bind(rowGen.keyCodecs(), mm);
mValueCodecs = ColumnCodec.bind(rowGen.valueCodecs(), mm);
mPass = mm.label();
mFail = mm.label();
}
void done() {
mFail.here();
mMaker.return_(null);
mPass.here();
// FIXME: Some columns may have already been decoded, so don't double decode them.
var viewVar = mMaker.var(mViewClass);
var rowVar = mMaker.param(3).cast(mRowClass);
Label hasRow = mMaker.label();
rowVar.ifNe(null, hasRow);
rowVar.set(mMaker.new_(mRowClass));
hasRow.here();
viewVar.invoke("decodePrimaryKey", rowVar, mMaker.param(1));
// Invoke the schema-specific decoder directly, instead of calling the decodeValue
// method which redundantly examines the schema version and switches on it.
mMaker.invoke(mDecoder, rowVar, mMaker.param(2)); // param(2) is the byte array
// Param(0) is the generated filter class, which has access to the inherited
// markAllClean method.
mMaker.param(0).invoke("markAllClean", rowVar);
mMaker.return_(rowVar);
}
@Override
public void visit(OrFilter filter) {
final Label originalFail = mFail;
RowFilter[] subFilters = filter.subFilters();
mFail = mMaker.label();
subFilters[0].accept(this);
mFail.here();
// Only the state observed on the left tree path can be preserved, because it's
// guaranteed to have executed.
final int hk = mHighestLocatedKey;
final int hv = mHighestLocatedValue;
for (int i=1; i<subFilters.length; i++) {
mFail = mMaker.label();
subFilters[i].accept(this);
mFail.here();
}
resetHighestLocatedKey(hk);
resetHighestLocatedValue(hv);
mMaker.goto_(originalFail);
mFail = originalFail;
}
@Override
public void visit(AndFilter filter) {
final Label originalPass = mPass;
RowFilter[] subFilters = filter.subFilters();
mPass = mMaker.label();
subFilters[0].accept(this);
mPass.here();
// Only the state observed on the left tree path can be preserved, because it's
// guaranteed to have executed.
final int hk = mHighestLocatedKey;
final int hv = mHighestLocatedValue;
for (int i=1; i<subFilters.length; i++) {
mPass = mMaker.label();
subFilters[i].accept(this);
mPass.here();
}
resetHighestLocatedKey(hk);
resetHighestLocatedValue(hv);
mMaker.goto_(originalPass);
mPass = originalPass;
}
@Override
public void visit(ColumnToArgFilter filter) {
ColumnInfo colInfo = filter.column();
int op = filter.operator();
Variable argObjVar = mMaker.param(0); // contains the arg fields prepared earlier
int argNum = filter.argument();
Integer colNumObj = columnNumberFor(colInfo.name);
if (colNumObj != null) {
int colNum = colNumObj;
LocatedColumn located = decodeColumn(colNum, colInfo, op);
ColumnCodec codec = codecFor(colNum);
codec.filterCompare(colInfo, located.mSrcVar, located.mOffsetVar, null,
op, located.mDecoded, argObjVar, argNum, mPass, mFail);
} else {
// Column doesn't exist in the row, so compare against a default. This code
// assumes that value codecs always define an arg field which preserves the
// original argument, possibly converted to the correct type.
var argField = argObjVar.field(ColumnCodec.argFieldName(colInfo, argNum));
var columnVar = mMaker.var(colInfo.type);
Converter.setDefault(colInfo, columnVar);
CompareUtils.compare(mMaker, colInfo, columnVar,
colInfo, argField, op, mPass, mFail);
}
}
@Override
public void visit(ColumnToColumnFilter filter) {
// FIXME: visit(ColumnToColumnFilter)
throw null;
}
private Integer columnNumberFor(String colName) {
return mRowGen.columnNumbers().get(colName);
}
private ColumnCodec codecFor(int colNum) {
ColumnCodec[] codecs = mKeyCodecs;
return colNum < codecs.length ? codecs[colNum] : mValueCodecs[colNum - codecs.length];
}
/**
* Decodes a column and remembers it if requested again later.
*
* @param colInfo current definition for column
* @param op defined in ColumnFilter
*/
private LocatedColumn decodeColumn(int colNum, ColumnInfo colInfo, int op) {
Variable srcVar;
LocatedColumn[] located;
ColumnCodec[] codecs = mKeyCodecs;
int highestNum;
init: {
int startOffset;
if (colNum < codecs.length) {
// Key column.
highestNum = mHighestLocatedKey;
srcVar = mMaker.param(1);
if ((located = mLocatedKeys) != null) {
break init;
}
mLocatedKeys = located = new LocatedColumn[mRowGen.info.keyColumns.size()];
startOffset = 0;
} else {
// Value column.
colNum -= codecs.length;
highestNum = mHighestLocatedValue;
srcVar = mMaker.param(2);
codecs = mValueCodecs;
if ((located = mLocatedValues) != null) {
break init;
}
mLocatedValues = located = new LocatedColumn[mRowGen.info.valueColumns.size()];
startOffset = RowUtils.lengthPrefixPF(mSchemaVersion);
}
located[0] = new LocatedColumn();
located[0].located(srcVar, mMaker.var(int.class).set(startOffset));
}
if (colNum <= highestNum) {
LocatedColumn col = located[colNum];
if (col.isDecoded()) {
return col;
}
// Regress the highest to force the column to be decoded. The highest field
// won't regress, since the field assignment (at the end) checks this.
highestNum = colNum;
}
if (!located[highestNum].isLocated()) {
throw new AssertionError();
}
for (; highestNum <= colNum; highestNum++) {
// Offset will be mutated, and so a copy must be made before calling decode.
Variable offsetVar = located[highestNum].mOffsetVar;
LocatedColumn next;
copyOffsetVar: {
if (highestNum + 1 >= located.length) {
next = null;
} else {
next = located[highestNum + 1];
if (next == null) {
next = new LocatedColumn();
located[highestNum + 1] = next;
} else if (!next.isLocated()) {
// Can recycle the offset variable because it's not used.
Variable freeVar = next.mOffsetVar;
if (freeVar != null) {
freeVar.set(offsetVar);
offsetVar = freeVar;
break copyOffsetVar;
}
}
}
offsetVar = offsetVar.get();
}
ColumnCodec codec = codecs[highestNum];
Variable endVar = null;
if (highestNum < colNum) {
codec.decodeSkip(srcVar, offsetVar, endVar);
} else {
Object decoded = codec.filterDecode(colInfo, srcVar, offsetVar, endVar, op);
located[highestNum].decoded(decoded);
}
if (next != null && !next.isLocated()) {
// The decode call incremented offsetVar as a side-effect. Note that if the
// column is already located, then newly discovered offset will match. It
// can simply be replaced, but by discarding it, the compiler can discard
// some of the redundant steps which computed the offset again.
next.located(srcVar, offsetVar);
}
}
highestNum = Math.min(highestNum, located.length - 1);
if (located == mLocatedKeys) {
if (highestNum > mHighestLocatedKey) {
mHighestLocatedKey = highestNum;
}
} else {
if (highestNum > mHighestLocatedValue) {
mHighestLocatedValue = highestNum;
}
}
return located[colNum];
}
/**
* Reset the highest located key column. The trailing LocatedColumn instances can be
* re-used, reducing the number of Variables created.
*/
private void resetHighestLocatedKey(int colNum) {
if (colNum < mHighestLocatedKey) {
mHighestLocatedKey = colNum;
finishReset(mLocatedKeys, colNum);
}
}
/**
* Reset the highest located value column. The trailing LocatedColumn instances can be
* re-used, reducing the number of Variables created.
*
* @param colNum column number among all value columns
*/
private void resetHighestLocatedValue(int colNum) {
if (colNum < mHighestLocatedValue) {
mHighestLocatedValue = colNum;
finishReset(mLocatedValues, colNum);
}
}
private static void finishReset(LocatedColumn[] columns, int colNum) {
while (++colNum < columns.length) {
var col = columns[colNum];
if (col == null) {
break;
}
col.unlocated();
}
}
}
private static class LocatedColumn {
// Used by mState field.
private static final int UNLOCATED = 0, LOCATED = 1, DECODED = 2;
private int mState;
// Source byte array. Is valid when mState is LOCATED or DECODED.
Variable mSrcVar;
// Offset into the byte array. Is valid when mState is LOCATED or DECODED.
Variable mOffsetVar;
// Optional Object from ColumnCodec.filterDecode. Is valid when mState is DECODED.
Object mDecoded;
LocatedColumn() {
}
boolean isLocated() {
return mState >= LOCATED;
}
boolean isDecoded() {
return mState == DECODED;
}
/**
* @param srcVar source byte array
* @param offsetVar start offset into the byte array
*/
void located(Variable srcVar, Variable offsetVar) {
mSrcVar = srcVar;
mOffsetVar = offsetVar;
mState = LOCATED;
}
/**
* @param decoded object returned from ColumnCodec.filterDecode
*/
void decoded(Object decoded) {
if (mState == UNLOCATED) {
throw new IllegalStateException();
}
mDecoded = decoded;
mState = DECODED;
}
void unlocated() {
mDecoded = null;
mState = UNLOCATED;
}
}
}
|
package org.galibier.packet;
public class ProtocolNumber {
public static final byte ICMP = (byte)1;
public static final byte IGMP = (byte)2;
public static final byte IPv4 = (byte)4;
public static final byte TCP = (byte)6;
public static final byte UDP = (byte)17;
public static final byte IPv6 = (byte)41;
public static final byte RSVP = (byte)46;
public static final byte GRE = (byte)47;
public static final byte OSPF = (byte)89;
public static final byte L2TP = (byte)115;
public static final byte STP = (byte)118;
public static final byte SCTP = (byte)132;
}
|
package org.gololang.webconsole;
import com.google.appengine.api.capabilities.Capability;
import com.google.apphosting.api.ApiProxy;
import com.google.apphosting.api.ApiProxy.ApiConfig;
import com.google.apphosting.api.ApiProxy.ApiProxyException;
import com.google.apphosting.api.ApiProxy.Delegate;
import com.google.apphosting.api.ApiProxy.Environment;
import com.google.apphosting.api.ApiProxy.LogRecord;
import com.google.common.base.Charsets;
import com.google.common.io.ByteStreams;
import com.google.common.io.CharStreams;
import fr.insalyon.citi.golo.compiler.GoloCompilationException;
import fr.insalyon.citi.golo.compiler.parser.ParseException;
import fr.insalyon.citi.golo.compiler.parser.TokenMgrError;
import fr.insalyon.citi.golo.runtime.GoloClassLoader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.nio.charset.Charset;
import java.util.HashSet;
import java.util.List;
import java.util.concurrent.Future;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RunServlet extends HttpServlet {
public static class Context {
private StringBuilder builder = new StringBuilder();
public Context log(Object obj) {
builder.append(obj).append("\n");
return this;
}
}
@Override
public void init() throws ServletException {
super.init();
final HashSet<String> forbidden = new HashSet<String>() {
{
for (Field field : Capability.class.getFields()) {
if (field.getType() == Capability.class) {
try {
Capability cap = (Capability) field.get(null);
add(cap.getPackageName());
} catch (IllegalArgumentException | IllegalAccessException ex) {
throw new ServletException(ex);
}
}
}
}
};
final Delegate delegate = ApiProxy.getDelegate();
ApiProxy.setDelegate(new Delegate() {
@Override
public byte[] makeSyncCall(Environment env, String packageName, String methodName, byte[] request) throws ApiProxyException {
if (forbidden.contains(packageName)) {
throw new ApiProxyException("Access to " + packageName + " is forbidden");
}
return delegate.makeSyncCall(env, packageName, methodName, request);
}
@Override
public Future makeAsyncCall(Environment env, String packageName, String methodName, byte[] request, ApiConfig config) {
if (forbidden.contains(packageName)) {
throw new ApiProxyException("Access to " + packageName + " is forbidden");
}
return delegate.makeAsyncCall(env, packageName, methodName, request, config);
}
@Override
public void log(Environment env, LogRecord record) {
delegate.log(env, record);
}
@Override
public void flushLogs(Environment env) {
delegate.flushLogs(env);
}
@Override
public List getRequestThreads(Environment env) {
return delegate.getRequestThreads(env);
}
});
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/plain");
try (InputStreamReader reader = new InputStreamReader(request.getInputStream(), Charsets.UTF_8)) {
String code = CharStreams.toString(reader);
try (ByteArrayInputStream codeStream = new ByteArrayInputStream(code.getBytes())) {
GoloClassLoader classLoader = new GoloClassLoader(RunServlet.class.getClassLoader());
Class<?> module = classLoader.load("test.golo", codeStream);
try {
Context context = new Context();
context.log("-> run returned: " + module.getMethod("run", Object.class).invoke(null, context));
response.getWriter().write(context.builder.toString());
} catch (Throwable t) {
if (t.getMessage() == null) {
response.getWriter().write(t.getCause().toString());
}
}
} catch (GoloCompilationException e) {
if (e.getCause() != null) {
response.getWriter().write(e.getCause().getMessage());
}
for (GoloCompilationException.Problem problem : e.getProblems()) {
response.getWriter().write(problem.getDescription());
}
} catch (TokenMgrError e) {
response.getWriter().write(e.getMessage());
}
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.